<commit_before>"""
Unit tests of the Dashboard application
"""
import contextlib
import datetime
import hashlib
import xmlrpclib

from django.contrib.auth.models import User, Group
from django.core.files.base import ContentFile
from django.db import IntegrityError
from django.test import TestCase
from django.test.client import Client

from dashboard_app import fixtures
from dashboard_app.models import (
        Bundle,
        BundleDeserializationError,
        BundleStream,
        HardwareDevice,
        SoftwarePackage,
        Test,
        TestCase as TestCaseModel,
        TestRun,
        )
from dashboard_app.dispatcher import (
        DjangoXMLRPCDispatcher,
        FaultCodes,
        xml_rpc_signature,
        )
from dashboard_app.xmlrpc import errors
from launch_control.thirdparty.mocker import Mocker, expect
from launch_control.utils.call_helper import ObjectFactoryMixIn


class SoftwarePackageTestCase(TestCase, ObjectFactoryMixIn):

    class Dummy:
        class SoftwarePackage:
            name = 'libfoo'
            version = '1.2.0'

    def test_creation_1(self):
        dummy, sw_package = self.make_and_get_dummy(SoftwarePackage)
        sw_package.save()
        self.assertEqual(sw_package.name, dummy.name)
        self.assertEqual(sw_package.version, dummy.version)

    def test_uniqueness(self):
        pkg1 = self.make(SoftwarePackage)
        pkg1.save()
        pkg2 = self.make(SoftwarePackage)
        self.assertRaises(IntegrityError, pkg2.save)


class HardwarePackageTestCase(TestCase, ObjectFactoryMixIn):

    class Dummy:
        class HardwareDevice:
            device_type = 'device.cpu'
            description = 'some cpu'

    def test_creation(self):
        dummy, hw_device = self.make_and_get_dummy(HardwareDevice)
        hw_device.save()
        self.assertEqual(hw_device.device_type, dummy.device_type)
        self.assertEqual(hw_device.description, dummy.description)

    def test_attributes(self):
        hw_device = self.make(HardwareDevice)
        hw_device.save()
        hw_device.attributes.create(name="connection-bus", value="usb")
        self.assertEqual(hw_device.attributes.count(), 1)
        attr = hw_device.attributes.get()
        self.assertEqual(attr.name, "connection-bus")
        self.assertEqual(attr.value, "usb")

    def test_attributes_uniqueness(self):
        hw_device = self.make(HardwareDevice)
        hw_device.save()
        hw_device.attributes.create(name="name", value="value")
        self.assertRaises(IntegrityError, hw_device.attributes.create,
                name="name", value="value")


class BundleTest(TestCase):

    _NAME = "name"
    _SLUG = "slug"
    _GROUPNAME = "group"
    _USERNAME = "user"

    scenarios = [
        ('anonymous-no-slug', {
            'pathname': '/anonymous/',
            }),
        ('anonymous-with-slug', {
            'name': _NAME,
            'slug': _SLUG,
            'pathname': '/anonymous/slug/',
            }),
        ('personal-no-slug', {
            'username': _USERNAME,
            'pathname': '/personal/user/',
            }),
        ('personal-with-slug', {
            'username': _USERNAME,
            'name': _NAME,
            'slug': _SLUG,
            'pathname': '/personal/user/slug/',
            }),
        ('team-no-slug', {
            'groupname': _GROUPNAME,
            'pathname': '/team/group/',
            }),
        ('team-with-slug', {
            'groupname': _GROUPNAME,
            'name': _NAME,
            'slug': _SLUG,
            'pathname': '/team/group/slug/',
            }),
        ]

    groupname = None
    username = None
    group = None
    user = None
    name = ''
    slug = ''

    def setUp(self):
        super(BundleTest, self).setUp()
        if self.username is not None:
            self.user = User.objects.create(username='user')
        if self.groupname is not None:
            self.group = Group.objects.create(name='group')

    def test_creation(self):
        bundle_stream = BundleStream.objects.create(user=self.user,
                group=self.group, name=self.name, slug=self.slug)
        bundle_stream.save()
        self.assertEqual(bundle_stream.user, self.user)
        self.assertEqual(bundle_stream.group, self.group)
        self.assertEqual(bundle_stream.name, self.name)
        self.assertEqual(bundle_stream.slug, self.slug)

    def test_team_named_stream(self):
        bundle_stream = BundleStream.objects.create(user=self.user,
                group=self.group, name=self.name, slug=self.slug)
        bundle_stream.save()
        self.assertEqual(bundle_stream.pathname, self.pathname)

    def test_pathname_uniqueness(self):
        bundle_stream = BundleStream.objects.create(user=self.user,
                group=self.group, name=self.name, slug=self.slug)
        bundle_stream.save()
        self.assertRaises(IntegrityError,
                BundleStream.objects.create,
                user=self.user, group=self.group, slug=self.slug,
                name=self.name)

    def test_pathname_update(self):
        bundle_stream = BundleStream.objects.create(user=self.user,
                group=self.group, name=self.name, slug=self.slug)
        bundle_stream.save()
        old_pathname = bundle_stream.pathname
        bundle_stream.slug += "-changed"
        bundle_stream.save()
        self.assertNotEqual(bundle_stream.pathname, old_pathname)
        self.assertEqual(bundle_stream.pathname,
                bundle_stream._calc_pathname())


class BundleDeserializationTestCase(TestCase):

    scenarios = [
        ('dummy_import_failure', {
            'pathname': '/anonymous/',
            'content': 'bogus',
            'content_filename': 'test1.json',
        }),
    ]

    def setUp(self):
        super(BundleDeserializationTestCase, self).setUp()
        self.bundle = fixtures.create_bundle(
            self.pathname, self.content, self.content_filename)
        self.mocker = Mocker()

    def tearDown(self):
        super(BundleDeserializationTestCase, self).tearDown()
        self.bundle.delete()
        self.mocker.restore()
        self.mocker.verify()

    def test_deserialize_failure_leaves_trace(self):
        mock = self.mocker.patch(self.bundle)
        expect(mock._do_deserialize()).throw(Exception("boom"))
        self.mocker.replay()
        self.bundle.deserialize()
        self.assertFalse(self.bundle.is_deserialized)
        self.assertEqual(self.bundle.deserialization_error.error_message, "boom")

    def test_deserialize_ignores_deserialized_bundles(self):
        self.mocker.replay()
        self.bundle.is_deserialized = True
        self.bundle.deserialize()
        self.assertTrue(self.bundle.is_deserialized)

    def test_deserialize_sets_is_serialized_on_success(self):
        mock = self.mocker.patch(self.bundle)<commit_msg>Add comment to mysterious mocker usage<commit_after>"""
Unit tests of the Dashboard application
"""
import contextlib
import datetime
import hashlib
import xmlrpclib

from django.contrib.auth.models import User, Group
from django.core.files.base import ContentFile
from django.db import IntegrityError
from django.test import TestCase
from django.test.client import Client

from dashboard_app import fixtures
from dashboard_app.models import (
        Bundle,
        BundleDeserializationError,
        BundleStream,
        HardwareDevice,
        SoftwarePackage,
        Test,
        TestCase as TestCaseModel,
        TestRun,
        )
from dashboard_app.dispatcher import (
        DjangoXMLRPCDispatcher,
        FaultCodes,
        xml_rpc_signature,
        )
from dashboard_app.xmlrpc import errors
from launch_control.thirdparty.mocker import Mocker, expect
from launch_control.utils.call_helper import ObjectFactoryMixIn


class SoftwarePackageTestCase(TestCase, ObjectFactoryMixIn):

    class Dummy:
        class SoftwarePackage:
            name = 'libfoo'
            version = '1.2.0'

    def test_creation_1(self):
        dummy, sw_package = self.make_and_get_dummy(SoftwarePackage)
        sw_package.save()
        self.assertEqual(sw_package.name, dummy.name)
        self.assertEqual(sw_package.version, dummy.version)

    def test_uniqueness(self):
        pkg1 = self.make(SoftwarePackage)
        pkg1.save()
        pkg2 = self.make(SoftwarePackage)
        self.assertRaises(IntegrityError, pkg2.save)


class HardwarePackageTestCase(TestCase, ObjectFactoryMixIn):

    class Dummy:
        class HardwareDevice:
            device_type = 'device.cpu'
            description = 'some cpu'

    def test_creation(self):
        dummy, hw_device = self.make_and_get_dummy(HardwareDevice)
        hw_device.save()
        self.assertEqual(hw_device.device_type, dummy.device_type)
        self.assertEqual(hw_device.description, dummy.description)

    def test_attributes(self):
        hw_device = self.make(HardwareDevice)
        hw_device.save()
        hw_device.attributes.create(name="connection-bus", value="usb")
        self.assertEqual(hw_device.attributes.count(), 1)
        attr = hw_device.attributes.get()
        self.assertEqual(attr.name, "connection-bus")
        self.assertEqual(attr.value, "usb")

    def test_attributes_uniqueness(self):
        hw_device = self.make(HardwareDevice)
        hw_device.save()
        hw_device.attributes.create(name="name", value="value")
        self.assertRaises(IntegrityError, hw_device.attributes.create,
                name="name", value="value")


class BundleTest(TestCase):

    _NAME = "name"
    _SLUG = "slug"
    _GROUPNAME = "group"
    _USERNAME = "user"

    scenarios = [
        ('anonymous-no-slug', {
            'pathname': '/anonymous/',
            }),
        ('anonymous-with-slug', {
            'name': _NAME,
            'slug': _SLUG,
            'pathname': '/anonymous/slug/',
            }),
        ('personal-no-slug', {
            'username': _USERNAME,
            'pathname': '/personal/user/',
            }),
        ('personal-with-slug', {
            'username': _USERNAME,
            'name': _NAME,
            'slug': _SLUG,
            'pathname': '/personal/user/slug/',
            }),
        ('team-no-slug', {
            'groupname': _GROUPNAME,
            'pathname': '/team/group/',
            }),
        ('team-with-slug', {
            'groupname': _GROUPNAME,
            'name': _NAME,
            'slug': _SLUG,
            'pathname': '/team/group/slug/',
            }),
        ]

    groupname = None
    username = None
    group = None
    user = None
    name = ''
    slug = ''

    def setUp(self):
        super(BundleTest, self).setUp()
        if self.username is not None:
            self.user = User.objects.create(username='user')
        if self.groupname is not None:
            self.group = Group.objects.create(name='group')

    def test_creation(self):
        bundle_stream = BundleStream.objects.create(user=self.user,
                group=self.group, name=self.name, slug=self.slug)
        bundle_stream.save()
        self.assertEqual(bundle_stream.user, self.user)
        self.assertEqual(bundle_stream.group, self.group)
        self.assertEqual(bundle_stream.name, self.name)
        self.assertEqual(bundle_stream.slug, self.slug)

    def test_team_named_stream(self):
        bundle_stream = BundleStream.objects.create(user=self.user,
                group=self.group, name=self.name, slug=self.slug)
        bundle_stream.save()
        self.assertEqual(bundle_stream.pathname, self.pathname)

    def test_pathname_uniqueness(self):
        bundle_stream = BundleStream.objects.create(user=self.user,
                group=self.group, name=self.name, slug=self.slug)
        bundle_stream.save()
        self.assertRaises(IntegrityError,
                BundleStream.objects.create,
                user=self.user, group=self.group, slug=self.slug,
                name=self.name)

    def test_pathname_update(self):
        bundle_stream = BundleStream.objects.create(user=self.user,
                group=self.group, name=self.name, slug=self.slug)
        bundle_stream.save()
        old_pathname = bundle_stream.pathname
        bundle_stream.slug += "-changed"
        bundle_stream.save()
        self.assertNotEqual(bundle_stream.pathname, old_pathname)
        self.assertEqual(bundle_stream.pathname,
                bundle_stream._calc_pathname())


class BundleDeserializationTestCase(TestCase):

    scenarios = [
        ('dummy_import_failure', {
            'pathname': '/anonymous/',
            'content': 'bogus',
            'content_filename': 'test1.json',
        }),
    ]

    def setUp(self):
        super(BundleDeserializationTestCase, self).setUp()
        self.bundle = fixtures.create_bundle(
            self.pathname, self.content, self.content_filename)
        self.mocker = Mocker()

    def tearDown(self):
        super(BundleDeserializationTestCase, self).tearDown()
        self.bundle.delete()
        self.mocker.restore()
        self.mocker.verify()

    def test_deserialize_failure_leaves_trace(self):
        mock = self.mocker.patch(self.bundle)
        expect(mock._do_deserialize()).throw(Exception("boom"))
        self.mocker.replay()
        self.bundle.deserialize()
        self.assertFalse(self.bundle.is_deserialized)
        self.assertEqual(self.bundle.deserialization_error.error_message, "boom")

    def test_deserialize_ignores_deserialized_bundles(self):
        self.mocker.replay() # this just makes our mocker happy
        self.bundle.is_deserialized = True
        self.bundle.deserialize()
        self.assertTrue(self.bundle.is_deserialized)

    def test_deserialize_sets_is_serialized_on_success(self):
        mock = self.mocker.patch(self.bundle)
{'fraction_non_alphanumeric': 0.10813362381989833, 'fraction_numerical': 0.0014524328249818446, 'mean_word_length': 2.4748927580116074, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 6}, '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': '6777139', 'n_tokens_mistral': 4047, 'n_tokens_neox': 3979, 'n_words': 676}