def test_get_average_rating_with_custom_choices(self):
        self.assertFalse(self.review.get_average_rating(), msg=(
            'If there are no ratings, it should return False.'))
        rating1 = mixer.blend('review.Rating', review=self.review, value='4')
        # we create choices to simulate, that the previous value was the max
        for i in range(0, 5):
            mixer.blend('review.RatingCategoryChoiceTranslation',
                        language_code='en-us',
                        ratingcategory=rating1.category, value=i)
        rating2 = mixer.blend('review.Rating', review=self.review, value='6')
        # we create choices to simulate, that the previous value was the max
        for i in range(0, 7):
            mixer.blend('review.RatingCategoryChoiceTranslation',
                        language_code='en-us',
                        ratingcategory=rating2.category, value=i)
        mixer.blend('review.Rating', category=rating2.category,
                    review=self.review, value='6')
        mixer.blend('review.Rating', category=rating2.category,
                    review=self.review, value=None)
        # testing the absolute max voting
        self.assertEqual(self.review.get_average_rating(6), 6, msg=(
            'Should return the average rating value.'))
        self.assertEqual(self.review.get_average_rating(4), 4, msg=(
            'Should return the average rating value.'))
        self.assertEqual(self.review.get_average_rating(100), 100, msg=(
            'Should return the average rating value.'))

        # testing the category averages
        """
 def setUp(self):
     self.user = mixer.blend('auth.User')
     self.doc = mixer.blend('document_library.Document')
     self.doc_en = self.doc.translate('en')
     self.doc_en.save()
     self.doc_de = self.doc.translate('de')
     self.doc_de.save()
 def setUp(self):
     self.extra_info = mixer.blend(
         'review.ReviewExtraInfo',
         review=mixer.blend('review.Review',
                            content_type=ContentType.objects.get_for_model(
                                WeatherCondition)),
         content_type=ContentType.objects.get_for_model(WeatherCondition))
    def test_deletion(self):
        self.is_not_callable(kwargs={
            'pk': 5,
            'year': self.event.start.date().year,
            'month': self.event.start.date().month,
            'day': self.event.start.date().day,
        }, user=self.event.created_by, msg=('Wrong event pk.'))

        self.is_not_callable(kwargs={
            'pk': self.event.pk,
            'year': self.event.start.date().year,
            'month': '999',
            'day': self.event.start.date().day,
        }, user=self.event.created_by, msg=('Wrong dates.'))

        new_rule = mixer.blend('calendarium.Rule', name='weekly',
                               frequency='WEEKLY')
        new_event = mixer.blend(
            'calendarium.Event',
            rule=new_rule,
            end_recurring_period=now() + timedelta(days=200),
            start=now() - timedelta(hours=5),
        )
        test_date = self.event.start.date() - timedelta(days=5)
        self.is_not_callable(kwargs={
            'pk': new_event.pk,
            'year': test_date.year,
            'month': test_date.month,
            'day': test_date.day,
        }, user=self.event.created_by, msg=(
            'No occurrence available for this day.'))

        self.is_callable(user=self.event.created_by)
        self.is_postable(user=self.event.created_by, to='/',
                         data={'decision': 'this one'})
예제 #5
0
    def test_add_asignaturas_alumnos(self):
        """
        Comprueba la vista add_asignatura_alumnos

        Comprueba que si no se le pasa nada, se muestra el formulario.
        Comprueba que se dirige a añadir las asignaturas al alumno
        Comprueba que no te dirige a añadir las asignaturas al alumno si los datos no son correctos.
        """
        grado = mixer.blend(Grado, titulo="GIISI", identificador=1)
        alumno = User.objects.get(username="******")
        mixer.blend(Asignatura, grados=grado, id=10)
        self.client = Client()
        self.client.login(username="******", password="******")
        session = self.client.session
        session['alumno'] = alumno.id
        session['grado'] = 1
        session.save()
        response = self.client.post("/miPanel/addAsignaturasAlumno/", {})
        boolean = True if not response.context['asignaturas'] else False
        self.assertEquals(boolean, False)

        response = self.client.post("/miPanel/addAsignaturasAlumno/", {'choices': 'error'})
        boolean = True if not response.context['asignaturas'] else False
        self.assertEquals(boolean, False)

        response = self.client.post("/miPanel/addAsignaturasAlumno/", {'choices': '10'})
        boolean = True if not response.context else False
        self.assertEquals(boolean, True)
예제 #6
0
    def test_add_grados_profesor(self):
        """
        Comprueba la vista add_grados_profesor

        Comprueba que si no se le pasan datos muestra el formulario.
        Comprueba que se muestra al añadir un profesor.
        Comprueba que si no se le pasan los datos correctamente no te dirige a añadir los grados.
        """
        profesor = User.objects.get(username="******")
        mixer.blend(Grado, profesores=profesor, id=10)
        self.client = Client()
        self.client.login(username="******", password="******")
        session = self.client.session
        session['profesor'] = profesor.id
        session.save()
        response = self.client.post("/miPanel/addGradosProfesor/", {})
        boolean = True if not response.context['grados'] else False
        self.assertEquals(boolean, False)

        response = self.client.post("/miPanel/addGradosProfesor/", {'choices': 'error'})
        boolean = True if not response.context['grados'] else False
        self.assertEquals(boolean, False)

        response = self.client.post("/miPanel/addGradosProfesor/", {'choices': '10'})
        boolean = True if not response.context else False
        self.assertEquals(boolean, True)
    def test_import_with_invalid_url_format(self):
        """test what happens if the data contains invalid data"""
        global CURRENT_PRODUCT_MIGRATION_TEST_DATA
        CURRENT_PRODUCT_MIGRATION_TEST_DATA = pd.DataFrame(
            [
                [
                    "Product A",
                    "Existing Migration Source",
                    "Replacement Product ID",
                    "comment of the migration",
                    "Invalid URL"
                ]
            ], columns=PRODUCT_MIGRATION_TEST_DATA_COLUMNS
        )
        mixer.blend("productdb.Product", product_id="Product A", vendor=Vendor.objects.get(id=1))
        mixer.blend("productdb.ProductMigrationSource", name="Existing Migration Source")

        product_migrations_file = ProductMigrationsExcelImporter("virtual_file.xlsx")
        assert product_migrations_file.is_valid_file() is False

        product_migrations_file.verify_file()
        assert product_migrations_file.is_valid_file() is True

        product_migrations_file.import_to_database()
        assert ProductMigrationOption.objects.count() == 0
        assert "cannot save Product Migration for Product A: {'migration_product_info_url': " \
               "['Enter a valid URL.']}" in product_migrations_file.import_result_messages

        Product.objects.all().delete()
        ProductMigrationOption.objects.all().delete()
        ProductMigrationSource.objects.all().delete()
예제 #8
0
 def test_relate_existing_object_to_task(self):
     """Test POST to relate existing note/record to a task
     """
     # First, ensure that a task, record and note all exist.
     task = mixer.blend(Task, referral=self.ref)
     note = mixer.blend(Note, referral=self.ref)
     record = mixer.blend(Record, referral=self.ref)
     init_records = task.records.count()
     init_notes = task.notes.count()
     url = reverse('referral_create_child_related', kwargs={
         'pk': self.ref.pk,
         'model': 'task',
         'id': task.pk,
         'type': 'addrecord'})
     resp = self.client.post(url, {'records': [record.pk]})
     self.assertEqual(resp.status_code, 302)
     self.assertTrue(task.records.count() > init_records)
     url = reverse('referral_create_child_related', kwargs={
         'pk': self.ref.pk,
         'model': 'task',
         'id': task.pk,
         'type': 'addnote'})
     resp = self.client.post(url, {'notes': [note.pk]})
     self.assertEqual(resp.status_code, 302)
     self.assertTrue(task.notes.count() > init_notes)
예제 #9
0
 def test_security(self):
     user = mixer.blend('auth.User', first_name='Martin')
     post = mixer.blend('birdie.Post')
     req = RequestFactory().post('/', data={})
     req.user = user
     with pytest.raises(Http404):
         views.PostUpdateView.as_view()(req, pk=post.pk)
    def test_valid_product_import_in_update_only_mode(self):
        test_product_ids = [
            'WS-C2960S-48FPD-L'
        ]
        products = [
            {
                'product id': 'WS-C2960S-48FPD-L',
                'description': 'Catalyst 2960S 48 GigE PoE 740W, 2 x 10G SFP+ LAN Base',
                'list price': 8795,
                'currency': 'USD',
                'vendor': 'Cisco Systems',
            }
        ]
        mixer.blend("productdb.Product", product_id="WS-C2960S-48FPD-L", vendor=Vendor.objects.get(id=1))

        product_file = self.prepare_import_products_excel_file("excel_import_products_test.xlsx", start_import=False)
        product_file.import_to_database(update_only=True)

        assert product_file.valid_imported_products == 1
        assert product_file.invalid_products == 0
        assert product_file.amount_of_products == 25
        assert product_file.import_result_messages is not None

        # verify that the expected products are created in the database
        for pid in test_product_ids:
            Product.objects.get(product_id=pid)

        # look at the imported values from the
        for product in products:
            p = Product.objects.get(product_id=product['product id'])
            assert p.description == product['description']
            assert p.list_price == product['list price']
            assert p.currency == product['currency']
            assert p.vendor.name == product['vendor']
예제 #11
0
def test_random(mixer):
    user = mixer.blend(
        'auth.User', username=mixer.RANDOM('mixer', 'its', 'fun'))
    assert user.username in ('mixer', 'its', 'fun')

    rabbit = mixer.blend(Rabbit, url=mixer.RANDOM)
    assert '/' in rabbit.url
    def test_valid_import(self):
        mixer.blend("productdb.Product", product_id="Product A", vendor=Vendor.objects.get(id=1))
        mixer.blend("productdb.ProductMigrationSource", name="Existing Migration Source")

        product_migrations_file = ProductMigrationsExcelImporter("virtual_file.xlsx")
        assert product_migrations_file.is_valid_file() is False

        product_migrations_file.verify_file()
        assert product_migrations_file.is_valid_file() is True

        product_migrations_file.import_to_database()
        assert ProductMigrationSource.objects.count() == 2
        assert ProductMigrationOption.objects.count() == 2
        assert len(product_migrations_file.import_result_messages) == 3
        assert "Product Migration Source \"New Migration Source\" was created with a preference of 10" in product_migrations_file.import_result_messages
        assert "create Product Migration path \"New Migration Source\" for Product \"Product A\"" in product_migrations_file.import_result_messages
        assert "create Product Migration path \"Existing Migration Source\" for Product \"Product A\"" in product_migrations_file.import_result_messages

        product_migrations_file.import_to_database()
        assert ProductMigrationSource.objects.count() == 2
        assert ProductMigrationOption.objects.count() == 2
        assert len(product_migrations_file.import_result_messages) == 2
        assert "update Product Migration path \"New Migration Source\" for Product \"Product A\"" in product_migrations_file.import_result_messages
        assert "update Product Migration path \"Existing Migration Source\" for Product \"Product A\"" in product_migrations_file.import_result_messages

        del product_migrations_file
        Product.objects.all().delete()
        ProductMigrationOption.objects.all().delete()
        ProductMigrationSource.objects.all().delete()
예제 #13
0
    def test_form(self):
        data = {'text': 'Foo'}
        form = forms.MessageForm(user=self.user, conversation=None, data=data,
                                 initial_user=self.other_user)
        self.assertFalse(form.errors)
        self.assertTrue(form.is_valid())
        conversation = form.save()
        self.assertEqual(Conversation.objects.count(), 1, msg=(
            'A new conversation should\'ve been started with the message.'))
        form = forms.MessageForm(user=self.user, data=data, initial_user=None,
                                 conversation=conversation)

        form.save()
        self.assertEqual(Conversation.objects.count(), 1, msg=(
            'The existing conversation should\'ve been re-used.'))

        blocked_user = mixer.blend('conversation.BlockedUser',
                                   blocked_by=self.user, user=self.other_user)
        form = forms.MessageForm(user=self.user, data=data, initial_user=None,
                                 conversation=conversation)
        self.assertTrue(form.errors, msg=(
            'Conversation should have been blocked'))

        blocked_user.delete()
        mixer.blend('conversation.BlockedUser',
                    user=self.user, blocked_by=self.other_user)
        form = forms.MessageForm(user=self.user, data=data, initial_user=None,
                                 conversation=conversation)
        self.assertTrue(form.errors, msg=(
            'Conversation should have been blocked'))
예제 #14
0
def node(data, parent=None):
    new_node = None
    # Create topics
    if data['kind_id'] == "topic":
        new_node = cc.ContentNode(kind=topic(), parent=parent, title=data['title'], node_id=data['node_id'])
        new_node.save()

        for child in data['children']:
            node(child, parent=new_node)

    # Create videos
    elif data['kind_id'] == "video":
        new_node = cc.ContentNode(kind=video(), parent=parent, title=data['title'], node_id=data['node_id'], license=license_wtfpl())
        new_node.save()
        video_file = fileobj_video(contents="Video File")
        video_file.contentnode = new_node
        video_file.preset_id = format_presets.VIDEO_HIGH_RES
        video_file.save()

    # Create exercises
    elif data['kind_id'] == "exercise":
        extra_fields = "{{\"mastery_model\":\"{}\",\"randomize\":true,\"m\":{},\"n\":{}}}".format(data['mastery_model'], data.get('m') or 0, data.get('n') or 0)
        new_node = cc.ContentNode(kind=exercise(), parent=parent, title=data['title'], node_id=data[
                                  'node_id'], license=license_wtfpl(), extra_fields=extra_fields)
        new_node.save()
        for assessment_item in data['assessment_items']:
            mixer.blend(cc.AssessmentItem,
                        contentnode=new_node,
                        assessment_id=assessment_item['assessment_id'],
                        question=assessment_item['question'],
                        type=assessment_item['type'],
                        answers=json.dumps(assessment_item['answers'])
                        )

    return new_node
예제 #15
0
def test_many_to_many_through(mixer):
    pointa = mixer.blend('django_app.pointa', other=mixer.RANDOM)
    assert pointa.other.all()

    pointb = mixer.blend('pointb')
    pointa = mixer.blend('pointa', other=pointb)
    assert list(pointa.other.all()) == [pointb]
예제 #16
0
파일: test_django.py 프로젝트: f4bsch/mixer
    def test_generic(self):
        from mixer.backend.django import mixer

        hole = mixer.blend(Hole)
        rabbit = mixer.blend(Rabbit, content_object=hole)
        self.assertEqual(rabbit.object_id, hole.pk)
        self.assertEqual(rabbit.content_type.model_class(), Hole)
예제 #17
0
파일: test_django.py 프로젝트: checko/mixer
 def test_invalid_scheme():
     from mixer.backend.django import mixer
     try:
         mixer.blend('django_app.Unknown')
     except ValueError:
         return False
     raise Exception('test.failed')
예제 #18
0
 def test_copy_relations(self):
     old_obj = mixer.blend('people.PersonPluginModel')
     new_obj = mixer.blend('people.PersonPluginModel')
     new_obj.copy_relations(old_obj)
     self.assertEqual(new_obj.person, old_obj.person, msg=(
         'Should copy the person instance from the old object to the new'
         ' object.'))
    def test_product_migration_source_names_set(self):
        site = AdminSite()
        product_admin = admin.ProductAdmin(models.Product, site)
        obj = mixer.blend(
            "productdb.Product",
            name="Product",
            eox_update_time_stamp=None
        )

        result = product_admin.product_migration_source_names(obj)
        expected = ""
        assert result == expected

        mixer.blend(
            "productdb.ProductMigrationOption",
            product=obj,
            migration_source=ProductMigrationSource.objects.create(name="test"),
            replacement_product_id="MyProductId"
        )

        result = product_admin.product_migration_source_names(obj)
        expected = "test"
        assert result == expected
        mixer.blend(
            "productdb.ProductMigrationOption",
            product=obj,
            migration_source=ProductMigrationSource.objects.create(name="test2"),
            replacement_product_id="MyProductId"
        )

        result = product_admin.product_migration_source_names(obj)
        expected = "test\ntest2"
        assert result == expected
 def setUp(self):
     self.user = mixer.blend('auth.User')
     self.admin = mixer.blend('auth.User', is_superuser=True)
     self.entry = mixer.blend('multilingual_news.NewsEntry')
     self.en_entry = self.entry.translate('en')
     self.en_entry.slug = 'foo'
     self.en_entry.save()
예제 #21
0
def test_fields(mixer):
    rabbit = mixer.blend('django_app.rabbit')

    assert isinstance(rabbit, Rabbit)
    assert rabbit.id
    assert rabbit.pk
    assert rabbit.pk == 1
    assert len(rabbit.title) <= 16
    assert isinstance(rabbit.active, bool)
    assert isinstance(rabbit.object_id, int)
    assert rabbit.object_id >= 0
    assert isinstance(rabbit.error_code, int)
    assert rabbit.error_code >= 0
    assert isinstance(rabbit.created_at, datetime.date)
    assert isinstance(rabbit.updated_at, datetime.datetime)
    assert isinstance(rabbit.opened_at, datetime.time)
    assert '@' in rabbit.email
    assert isinstance(rabbit.speed, decimal.Decimal)
    assert rabbit.custom
    assert rabbit.text
    assert len(rabbit.text) <= 512
    assert rabbit.picture.read() == b'pylama\n'

    assert rabbit.ip.count('.') == 3
    for ip_section in rabbit.ip.split('.'):
        assert 0 <= int(ip_section) <= 255

    assert rabbit.ip6.count(':') == 7
    for ip_section in rabbit.ip6.split(':'):
        assert 0 <= int(ip_section, 16) <= 65535

    assert isinstance(rabbit.file_path, str)

    rabbit = mixer.blend('rabbit')
    assert rabbit
예제 #22
0
 def setUp(self):
     self.user = mixer.blend('auth.User')
     self.other_user = mixer.blend('auth.User')
     self.review = mixer.blend(
         'review.Review', user=self.user,
         object_id=mixer.blend('test_app.WeatherCondition').pk,
         content_type=ContentType.objects.get_for_model(WeatherCondition))
 def test_is_not_subscribed(self):
     sub1 = mixer.blend('subscribe.Subscription',
                        content_object=mixer.blend('test_app.DummyModel'))
     sub2 = mixer.blend('subscribe.Subscription',
                        content_object=mixer.blend('test_app.DummyModel'))
     result = is_subscribed(sub1.user, sub2.content_object)
     self.assertFalse(result)
    def test_form(self):
        form = ProductListForm(data={})
        assert form.is_valid() is False
        assert "name" in form.errors
        assert "description" not in form.errors, "Null/Blank values are allowed"
        assert "string_product_list" in form.errors

        data = {
            "name": "Test Product List",
            "description": "",
            "string_product_list": ""
        }
        form = ProductListForm(data=data)
        assert form.is_valid() is False
        assert "name" not in form.errors, "Should be allowed (can be any string)"
        assert "description" not in form.errors, "Null/Blank values are allowed"
        assert "string_product_list" in form.errors, "At least one Product is required"

        data = {
            "name": "Test Product List",
            "description": "",
            "string_product_list": "Product"
        }
        mixer.blend("productdb.Product", product_id="Product")
        form = ProductListForm(data=data)
        assert form.is_valid() is True, form.errors
    def test_import_with_missing_product_value(self):
        """test import with missing product (ignore it)"""
        global CURRENT_PRODUCT_MIGRATION_TEST_DATA
        CURRENT_PRODUCT_MIGRATION_TEST_DATA = pd.DataFrame(
            [
                [
                    None,
                    "Existing Migration Source",
                    "Replacement Product ID",
                    "comment of the migration",
                    "Invalid URL"
                ]
            ], columns=PRODUCT_MIGRATION_TEST_DATA_COLUMNS
        )
        mixer.blend("productdb.Product", product_id="Product A", vendor=Vendor.objects.get(id=1))
        mixer.blend("productdb.ProductMigrationSource", name="Existing Migration Source")

        product_migrations_file = ProductMigrationsExcelImporter("no file.xlsx")
        assert product_migrations_file.is_valid_file() is False

        product_migrations_file.verify_file()
        assert product_migrations_file.is_valid_file() is True

        product_migrations_file.import_to_database()
        assert ProductMigrationOption.objects.count() == 0
        assert len(product_migrations_file.import_result_messages) == 0

        Product.objects.all().delete()
        ProductMigrationOption.objects.all().delete()
        ProductMigrationSource.objects.all().delete()
예제 #26
0
 def test_form(self):
     account = mixer.blend('account_keeping.Account')
     data = {
         'transaction_type': 'd',
         'transaction_date': now().strftime('%Y-%m-%d'),
         'account': account.pk,
         'payee': mixer.blend('account_keeping.Payee').pk,
         'category': mixer.blend('account_keeping.Category').pk,
         'currency': mixer.blend('currency_history.Currency').pk,
         'amount_net': 0,
         'amount_gross': 0,
         'vat': 0,
         'value_net': 0,
         'value_gross': 0,
         'mark_invoice': True,
     }
     form = forms.TransactionForm(data=data, branch=account.branch)
     self.assertFalse(form.errors)
     transaction = form.save()
     transaction.invoice = mixer.blend('account_keeping.Invoice',
                                       payment_date=None)
     transaction.invoice.save()
     self.assertFalse(transaction.invoice.payment_date)
     data.update({'invoice': transaction.invoice.pk})
     form = forms.TransactionForm(data=data, branch=account.branch)
     self.assertFalse(form.errors)
     transaction = form.save()
     self.assertTrue(transaction.invoice.payment_date)
    def test_form_suppress_notification_only_for_superusers(self):
        # anonymous users are not allowed to add a notification
        files = {"excel_file": SimpleUploadedFile("myfile.xlsx", b"yxz")}
        data = {"suppress_notification": False}
        form = ImportProductsFileUploadForm(user=AnonymousUser(), data=data, files=files)

        assert form.is_valid() is True
        assert form.fields["suppress_notification"].disabled is True
        assert form.cleaned_data["suppress_notification"] is True

        # authenticated users are not allowed to add a notification
        authuser = mixer.blend("auth.User")
        files = {"excel_file": SimpleUploadedFile("myfile.xlsx", b"yxz")}
        data = {"suppress_notification": False}
        form = ImportProductsFileUploadForm(user=authuser, data=data, files=files)

        assert form.is_valid() is True
        assert form.fields["suppress_notification"].disabled is True
        assert form.cleaned_data["suppress_notification"] is True

        # superusers are allowed to change the parameter
        superuser = mixer.blend("auth.User", is_superuser=True)
        files = {"excel_file": SimpleUploadedFile("myfile.xlsx", b"yxz")}
        data = {"suppress_notification": False}
        form = ImportProductsFileUploadForm(user=superuser, data=data, files=files)

        assert form.is_valid() is True
        assert form.fields["suppress_notification"].disabled is False
        assert form.cleaned_data["suppress_notification"] is False
예제 #28
0
파일: test_django.py 프로젝트: timka/mixer
def test_custom(mixer):
    mixer.register(Rabbit, title=lambda: 'Mr. Rabbit')

    rabbit = mixer.blend(Rabbit)
    assert rabbit.title == 'Mr. Rabbit'

    from mixer.backend.django import GenFactory

    def getter(*args, **kwargs):
        return "Always same"

    class MyFactory(GenFactory):
        generators = {models.CharField: getter}

    fabric = MyFactory.gen_maker(models.CharField)
    assert next(fabric()) == "Always same"

    mixer = Mixer(factory=MyFactory, fake=False)
    assert mixer._Mixer__factory == MyFactory

    test = mixer.blend(Rabbit)
    assert test.title == "Always same"

    @mixer.middleware('auth.user')
    def encrypt_password(user): # noqa
        user.set_password(user.password)
        return user

    user = mixer.blend('auth.User', password='******')
    assert user.check_password('test')

    user = user.__class__.objects.get(pk=user.pk)
    assert user.check_password('test')
예제 #29
0
 def test_tag(self):
     self.assertFalse(conversation_tags.is_blocked('foo', 'bar'))
     user1 = mixer.blend('auth.User')
     user2 = mixer.blend('auth.User')
     self.assertFalse(conversation_tags.is_blocked(user1, user2))
     mixer.blend('conversation.BlockedUser', blocked_by=user1, user=user2)
     self.assertTrue(conversation_tags.is_blocked(user1, user2))
    def test_with_invalid_product_id(self):
        """test the behavior of the import function if a product was not found in the database"""
        global CURRENT_PRODUCT_MIGRATION_TEST_DATA
        CURRENT_PRODUCT_MIGRATION_TEST_DATA = pd.DataFrame(
            [
                [
                    "Product that is not in the Database",
                    "Existing Migration Source",
                    "Replacement Product ID",
                    "comment of the migration",
                    "Invalid URL"
                ]
            ], columns=PRODUCT_MIGRATION_TEST_DATA_COLUMNS
        )
        mixer.blend("productdb.Product", product_id="Product A", vendor=Vendor.objects.get(id=1))
        mixer.blend("productdb.ProductMigrationSource", name="Existing Migration Source")

        product_migrations_file = ProductMigrationsExcelImporter("virtual_file.xlsx")
        assert product_migrations_file.is_valid_file() is False

        product_migrations_file.verify_file()
        assert product_migrations_file.is_valid_file() is True

        product_migrations_file.import_to_database()
        assert ProductMigrationOption.objects.count() == 0
        assert "Product Product that is not in the Database not found in database, skip " \
               "entry" in product_migrations_file.import_result_messages

        Product.objects.all().delete()
        ProductMigrationOption.objects.all().delete()
        ProductMigrationSource.objects.all().delete()
예제 #31
0
def test_create_user():
    user = mixer.blend(get_user_model())
    assert user.pk > 0
예제 #32
0
 def setUp(self):
     self.teacher = create_teacher(works_24x7=True)
     self.customer = create_customer()
     self.lesson = mixer.blend(lessons.MasterClass,
                               host=self.teacher,
                               slots=15)
예제 #33
0
 def test_get_excerpt(self):
     obj = mixer.blend('birdie.Post', body='Hello World!')
     result = obj.get_excerpt(5)
     assert result == 'Hello', 'Should return first 5 characters'
예제 #34
0
 def test_user_model(self):
     obj = mixer.blend(get_user_model())
     assert obj.pk == 1, 'Should create a User instance'
예제 #35
0
 def test_get_state(self):
     obj = mixer.blend('mueni.State',
                       name='Ashley',
                       description='suspended')
     result = StateService().get_state(description=obj.description)
     assert result is not None
예제 #36
0
 def test_get_library_record(self):
     member = mixer.blend('mueni.Member', first_name='Lucas')
     book = mixer.blend('mueni.Book', title='Alice')
     obj = mixer.blend('mueni.LibraryRecord', member=member, book=book)
     result = LibraryRecordService().get_library_record(member=obj.member)
     assert result is not None
예제 #37
0
 def test_get_member(self):
     obj = mixer.blend('mueni.Member',
                       first_name='Fredrick',
                       last_name='Mueni')
     result = MemberService().get_member(first_name=obj.first_name)
     assert result is not None
예제 #38
0
 def test_product_view_authenticated(self):
     path = reverse('detail', kwargs={'pk': 1})
     request = self.factory.get(path)
     request.user = mixer.blend(User)
     response = product_detail(request, pk=1)
     assert response.status_code == 200
예제 #39
0
 def setUpClass(cls):
     super(TestViews, cls).setUpClass()
     mixer.blend(Product)
     cls.factory = RequestFactory()
예제 #40
0
 def test_init(self):
     obj = mixer.blend('musilux.Song')
     assert obj.pk == 1, 'Does not exist'
예제 #41
0
    def create_project(self):
        project = mixer.blend('server.Project')

        return project
예제 #42
0
    def create_label(self):
        label = mixer.blend('server.Label')

        return label
예제 #43
0
 def test_superuser_authenticated(self):
     user = mixer.blend('auth.User', is_superuser=True)
     req = RequestFactory().get('/')
     req.user = user
     resp = views.AdminView.as_view()(req)
     assert resp.status_code == 200, "Should allow authenticate user to access"
예제 #44
0
 def test_get(self):
     req = RequestFactory().get('/')
     req.user = AnonymousUser()
     obj = mixer.blend('birdie.Post')
     resp = views.PostUpdateView.as_view()(req, pk=obj.pk)
     assert resp.status_code == 200, "Should be callable by anyone"
예제 #45
0
 def setUp(self):
     self.product = mixer.blend(Product)
예제 #46
0
    def test_model_puser_create(self):

        obj = mixer.blend('users.PUser')
        assert obj.pk == 1, 'Should create a user instance'
예제 #47
0
 def test_get(self):
     user = mixer.blend('auth.User', user_logged_in=True)
     req = RequestFactory().get('/')
     req.user = user
     resp = views.PostCreateView.as_view()(req)
     assert resp.status_code == 200, 'Should be callable by logged in users'
예제 #48
0
 def setUp(self):
     self.district = mixer.blend(District)
     self.company = mixer.blend(Company, districts=self.district)
     mixer.blend(Company)
예제 #49
0
    def setUp(self):
        self.test_user_employee, self.test_employee, self.test_profile_employee = self._make_user(
            'employee',
            userkwargs={
                "username": "******",
                "email": "*****@*****.**",
                "is_active": True
            },
            employexkwargs={
                "ratings": 0,
                "total_ratings": 0
            })
        self.test_user_employee2, self.test_employee2, self.test_profile_employee2 = self._make_user(
            'employee',
            userkwargs={
                "username": "******",
                "email": "*****@*****.**",
                "is_active": True
            },
            employexkwargs={
                "ratings": 0,
                "total_ratings": 0
            })
        self.test_user_employer, self.test_employer, self.test_profile_employer = self._make_user(
            'employer',
            userkwargs={
                "username": '******',
                "email": '*****@*****.**',
                "is_active": True
            },
            employexkwargs={
                "maximum_clockin_delta_minutes": 15,
                "maximum_clockout_delay_minutes": 15,
                "rating": 0,
                "total_ratings": 0
            })
        self.test_user_employer2, self.test_employer2, self.test_profile_employer2 = self._make_user(
            'employer',
            userkwargs={
                "username": '******',
                "email": '*****@*****.**',
                "is_active": True
            },
            employexkwargs={
                "maximum_clockin_delta_minutes": 15,
                "maximum_clockout_delay_minutes": 15,
                "rating": 0,
                "total_ratings": 0
            })

        begin_date = timezone.now() - timedelta(days=21)
        begin_date = datetime(begin_date.year,
                              begin_date.month,
                              begin_date.day,
                              0,
                              0,
                              0,
                              tzinfo=pytz.timezone(settings.TIME_ZONE))
        self.test_period = self._make_period(self.test_employer, begin_date)
        self.test_employer.payroll_period_starting_time = begin_date
        self.test_employer.save()
        _, shift, _, _ = self._make_periodpayment(employer=self.test_employer,
                                                  employee=self.test_employee,
                                                  period=self.test_period,
                                                  mykwargs={
                                                      "status": "APPROVED",
                                                      "regular_hours": 10,
                                                      "over_time": 8,
                                                      "breaktime_minutes": 15,
                                                      "hourly_rate": 20,
                                                      "total_amount": 360
                                                  })
        _, _, _, _ = self._make_periodpayment(employer=self.test_employer,
                                              employee=self.test_employee,
                                              period=self.test_period,
                                              mykwargs={
                                                  "status": "APPROVED",
                                                  "regular_hours": 25,
                                                  "over_time": 5,
                                                  "breaktime_minutes": 15,
                                                  "hourly_rate": 15,
                                                  "total_amount": 450
                                              },
                                              relatedkwargs={'shift': shift})
        _, _, _, _ = self._make_periodpayment(employer=self.test_employer,
                                              employee=self.test_employee2,
                                              period=self.test_period,
                                              mykwargs={
                                                  "status": "APPROVED",
                                                  "regular_hours": 12,
                                                  "over_time": 3,
                                                  "breaktime_minutes": 0,
                                                  "hourly_rate": 20,
                                                  "total_amount": 300
                                              })

        begin_date = begin_date + timedelta(days=7)
        self.test_period2 = self._make_period(self.test_employer, begin_date)
        _, _, _, _ = self._make_periodpayment(employer=self.test_employer,
                                              employee=self.test_employee,
                                              period=self.test_period2,
                                              mykwargs={"status": "APPROVED"},
                                              relatedkwargs={'shift': shift})

        begin_date2 = begin_date - timedelta(days=35)
        self.test_period3 = self._make_period(self.test_employer, begin_date2)
        _, _, _, _ = self._make_periodpayment(employer=self.test_employer,
                                              employee=self.test_employee2,
                                              period=self.test_period3,
                                              mykwargs={"status": "PENDING"},
                                              relatedkwargs={'shift': shift})

        # update date and time from clockin registries, for usage in PayrollPeriod creation
        clockin_date = begin_date + timedelta(days=9)
        mixer.blend('api.Clockin',
                    started_at=clockin_date.strftime('%Y-%m-%dT20:20:00Z'),
                    ended_at=clockin_date.strftime('%Y-%m-%dT23:45:00Z'),
                    shift=shift,
                    status="APPROVED")
        clockin_date = clockin_date + timedelta(days=1)
        mixer.blend('api.Clockin',
                    started_at=clockin_date.strftime('%Y-%m-%dT20:20:00Z'),
                    ended_at=clockin_date.strftime('%Y-%m-%dT23:45:00Z'),
                    shift=shift,
                    status="APPROVED")
        self.qty = PayrollPeriod.objects.count()
        self.payroll_payment_qty = PayrollPeriodPayment.objects.count()
예제 #50
0
 def test_superuser(self):
     user = mixer.blend('auth.User', is_superuser=True)
     req = RequestFactory().get('/')
     req.user = user
     resp = views.AdminView.as_view()(req)
     assert resp.status_code == 200, 'Should be callable by admin'
예제 #51
0
 def test_insert_legislator(self):
     obj = mixer.blend('open_secrets.Legislator')
     assert obj.pk == 1, 'Should save an instance'
예제 #52
0
 def test_init(self):
     obj = mixer.blend('birdie.Post')
     assert obj.pk == 1, 'Should save an isntance'
예제 #53
0
    def test_dom_leg_gsp_with_exclusions_to_gsp(self, mocked_requests):
        country = mixer.blend(Country, scenario="DOM_LEG_GSP_WITH_EXCLUSIONS")

        mocked_requests.get(
            "https://www.trade-tariff.service.gov.uk/api/v2/geographical_areas",
            json={
                "data": [
                    {
                        "id": "1111",
                        "relationships": {
                            "children_geographical_areas": {
                                "data": [{
                                    "id": "1"
                                }, {
                                    "id": "2"
                                }],
                            },
                        },
                    },
                    {
                        "id": GSP_ENHANCED_ID,
                        "relationships": {
                            "children_geographical_areas": {
                                "data": [{
                                    "id": "1"
                                }],
                            },
                        },
                    },
                ]
            },
        )
        update_scenario(country)
        self.assertEqual(country.scenario, "DOM_LEG_GSP_WITH_EXCLUSIONS")

        mocked_requests.get(
            "https://www.trade-tariff.service.gov.uk/api/v2/geographical_areas",
            json={
                "data": [
                    {
                        "id": "1111",
                        "relationships": {
                            "children_geographical_areas": {
                                "data": [{
                                    "id": "1"
                                }, {
                                    "id": "2"
                                }],
                            },
                        },
                    },
                    {
                        "id": GSP_ENHANCED_ID,
                        "relationships": {
                            "children_geographical_areas": {
                                "data": [{
                                    "id": country.country_code
                                }],
                            },
                        },
                    },
                ]
            },
        )
        update_scenario(country)
        self.assertEqual(country.scenario, "GSP")
예제 #54
0
def cosme():
    return mixer.blend("user.User", email="*****@*****.**")
예제 #55
0
    def test_properties(self):
        user = mixer.blend(get_user_model())

        assert user.user_privilege == 0
        assert user.is_guest
        assert not user.is_shifter
        assert not user.is_shiftleader
        assert not user.is_expert
        assert not user.is_admin
        assert not user.has_shifter_rights
        assert not user.has_shift_leader_rights
        assert user.is_staff is False
        assert user.is_superuser is False

        user.extra_data = {"groups": ["tkdqmdoctor-shifters"]}
        user.update_privilege()
        assert user.user_privilege == 10
        assert not user.is_guest
        assert user.is_shifter
        assert not user.is_shiftleader
        assert not user.is_expert
        assert not user.is_admin
        assert user.has_shifter_rights
        assert not user.has_shift_leader_rights
        assert user.is_staff is False
        assert user.is_superuser is False

        user.extra_data.get("groups").append("cms-tracker-offline-shiftleader")
        user.update_privilege()
        assert user.user_privilege == 20
        assert not user.is_guest
        assert not user.is_shifter
        assert user.is_shiftleader
        assert not user.is_expert
        assert not user.is_admin
        assert user.has_shifter_rights
        assert user.has_shift_leader_rights
        assert user.is_staff is True
        assert user.is_superuser is False

        user.extra_data.get("groups").append("tkdqmdoctor-experts")
        user.update_privilege()
        assert user.user_privilege == 30
        assert not user.is_guest
        assert not user.is_shifter
        assert not user.is_shiftleader
        assert user.is_expert
        assert not user.is_admin
        assert user.has_shifter_rights
        assert user.has_shift_leader_rights
        assert user.is_staff is True
        assert user.is_superuser is False

        user.extra_data.get("groups").append("tkdqmdoctor-admins")
        user.update_privilege()
        assert user.user_privilege == 50
        assert not user.is_guest
        assert not user.is_shifter
        assert not user.is_shiftleader
        assert not user.is_expert
        assert user.is_admin
        assert user.has_shifter_rights
        assert user.has_shift_leader_rights
        assert user.is_staff is True
        assert user.is_superuser is True
예제 #56
0
 def setUpClass(cls):
     super(TestViews, cls).setUpClass()
     mixer.blend('news.News')
     cls.factory = RequestFactory()
예제 #57
0
 def test_get_category(self):
     obj = mixer.blend('mueni.Category', name='Ashley', description='math')
     result = CategoryService().get_category(description=obj.description)
     assert result is not None
예제 #58
0
 def test_update_category(self):
     obj = mixer.blend('mueni.Category', name='Ashley', description='math')
     result = CategoryService().update_category(obj.id,
                                                description='horror')
     assert result is not None, 'should  change math into horror'
예제 #59
0
 def test_update_state(self):
     obj = mixer.blend('mueni.State',
                       name='Ashley',
                       description='suspended')
     result = StateService().update_state(obj.id, name='Smith')
     assert result is not None, 'should change Ashley into Smith'
예제 #60
0
    def test_no_transition(self):
        country = mixer.blend(Country, scenario="MADE_UP")

        update_scenario(country)

        self.assertEqual(country.scenario, "MADE_UP")