<commit_before>import os
import shutil
import tempfile
from typing import Optional, List
from unittest import mock

from django.http import HttpRequest
from django.utils import timezone
from rest_framework import status

from general.testing import DatabaseTestCase
from projects.models import Project, Snapshot
from lib.converter_facade import (
    ConverterIo,
    ConverterIoType,
    ConverterContext,
)

# Set up
snapshots_dir = tempfile.mkdtemp()
snapshot_1_dir = os.path.join(snapshots_dir, "1")
os.mkdir(snapshot_1_dir)
with open(os.path.join(snapshot_1_dir, "test.txt"), "w") as file:
    file.write("Test content")


class MockSnapshotter:
    """Returns a new snapshot but does not create snapshot dir etc."""

    def __init__(self, storage_root: str) -> None:
        pass

    def snapshot_project(
        self, request: HttpRequest, project: Project, tag: Optional[str] = None
    ) -> Snapshot:
        return Snapshot.objects.create(
            project=project,
            version_number=1,
            tag=tag or None,
            path=snapshot_1_dir,
            creator=request.user,
            created=timezone.now(),
            completed=timezone.now(),
        )


class MockConverter:
    """Just copies the input path to the output path."""

    def __init__(self, converter_binary: List[str]) -> None:
        pass

    def convert(
        self,
        input_data: ConverterIo,
        output_data: ConverterIo,
        context: ConverterContext,
    ) -> None:
        assert input_data.io_type == ConverterIoType.PATH
        assert output_data.io_type == ConverterIoType.PATH
        dir = os.path.dirname(output_data.data)
        if not os.path.exists(dir):
            os.makedirs(dir)
        shutil.copyfile(input_data.data, output_data.data)


class SnapshotAPIViewsTest(DatabaseTestCase):
    """
    Test API views for snapshots.

    Tests for the `ProjectSnapshotter` should be done elsewhere.
    It is mocked in these tests.
    """

    def setUp(self):
        super().setUp()
        self.patch_snapshotter = mock.patch(
            "projects.api.views.snapshots.ProjectSnapshotter", new=MockSnapshotter,
        )
        self.patch_snapshotter.start()

        self.patch_snapshotter = mock.patch(
            "projects.api.views.snapshots.ConverterFacade", new=MockConverter,
        )
        self.patch_snapshotter.start()

    def tearDown(self):
        self.patch_snapshotter.stop()

    # Type specific CRUD methods (no U & D methods though)

    def list_snaps(self, user, project: Project):
        return self.list(user, "snapshots", kwargs={"pk": project.pk})

    def create_snap(self, user, project: Project, tag: Optional[str] = None):
        return self.create(
            user, "snapshots", kwargs={"pk": project.pk}, data={"tag": tag}
        )

    def retrieve_snap(self, user, project: Project, number: int, **kwargs):
        return self.retrieve(
            user, "snapshots", kwargs={"pk": project.pk, "number": number}, **kwargs
        )

    def retrieve_file(self, user, project: Project, number: int, path: str, **kwargs):
        return self.retrieve(
            user,
            "api-snapshots-retrieve-file",
            kwargs={"pk": project.pk, "number": number, "path": path},
            **kwargs,
        )

    # Testing methods

    def test_create_ok(self):<commit_msg>test(Snapshots API): Fix start and stop patches<commit_after>import os
import shutil
import tempfile
from typing import Optional, List
from unittest import mock

from django.http import HttpRequest
from django.utils import timezone
from rest_framework import status

from general.testing import DatabaseTestCase
from projects.models import Project, Snapshot
from lib.converter_facade import (
    ConverterIo,
    ConverterIoType,
    ConverterContext,
)


# Set up temporary folders to run tests on
snapshots_dir = tempfile.mkdtemp()
snapshot_1_dir = os.path.join(snapshots_dir, "1")
os.mkdir(snapshot_1_dir)
with open(os.path.join(snapshot_1_dir, "test.txt"), "w") as file:
    file.write("Test content")


class MockSnapshotter:
    """Returns a new snapshot but does not create snapshot dir etc."""

    def __init__(self, storage_root: str) -> None:
        pass

    def snapshot_project(
        self, request: HttpRequest, project: Project, tag: Optional[str] = None
    ) -> Snapshot:
        return Snapshot.objects.create(
            project=project,
            version_number=1,
            tag=tag or None,
            path=snapshot_1_dir,
            creator=request.user,
            created=timezone.now(),
            completed=timezone.now(),
        )


class MockConverter:
    """Just copies the input path to the output path."""

    def __init__(self, converter_binary: List[str]) -> None:
        pass

    def convert(
        self,
        input_data: ConverterIo,
        output_data: ConverterIo,
        context: ConverterContext,
    ) -> None:
        assert input_data.io_type == ConverterIoType.PATH
        assert output_data.io_type == ConverterIoType.PATH
        dir = os.path.dirname(output_data.data)
        if not os.path.exists(dir):
            os.makedirs(dir)
        shutil.copyfile(input_data.data, output_data.data)


class SnapshotsAPIViewsTest(DatabaseTestCase):
    """Test API views for snapshots."""

    def setUp(self):
        super().setUp()
        self.patch_snapshotter = mock.patch(
            "projects.api.views.snapshots.ProjectSnapshotter", new=MockSnapshotter,
        )
        self.patch_snapshotter.start()

        self.patch_converter = mock.patch(
            "projects.api.views.snapshots.ConverterFacade", new=MockConverter,
        )
        self.patch_converter.start()

    def tearDown(self):
        self.patch_snapshotter.stop()
        self.patch_converter.stop()

    # Type specific CRUD methods (no U & D methods though)

    def list_snaps(self, user, project: Project):
        return self.list(user, "snapshots", kwargs={"pk": project.pk})

    def create_snap(self, user, project: Project, tag: Optional[str] = None):
        return self.create(
            user, "snapshots", kwargs={"pk": project.pk}, data={"tag": tag}
        )

    def retrieve_snap(self, user, project: Project, number: int, **kwargs):
        return self.retrieve(
            user, "snapshots", kwargs={"pk": project.pk, "number": number}, **kwargs
        )

    def retrieve_file(self, user, project: Project, number: int, path: str, **kwargs):
        return self.retrieve(
            user,
            "api-snapshots-retrieve-file",
            kwargs={"pk": project.pk, "number": number, "path": path},
            **kwargs,
        )

    # Testing methods

    def test_create_ok(self):
{'fraction_non_alphanumeric': 0.10747733016203359, 'fraction_numerical': 0.0017838561022744165, 'mean_word_length': 2.7419354838709675, 'pattern_counts': {'":': 16, '<': 3, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6711325', 'n_tokens_mistral': 1971, 'n_tokens_neox': 1944, 'n_words': 506}