Best Python code snippet using refurb_python
test_mixins.py
Source:test_mixins.py  
1from rest_framework import serializers2from rest_framework.exceptions import ValidationError3from api.common.mixins import FormattedErrorMessageMixin4class NestedSerializerBase(serializers.Serializer):5    """Sample nested serializer declared solely for test purposes"""6    int_field = serializers.IntegerField()7    custom_field = serializers.CharField(required=True)8    list_field = serializers.ListField(9        child=serializers.IntegerField()10    )11    class Meta:12        fields = ['int_field', 'custom_field', 'list_field', ]13    def validate(self, attrs):14        if attrs['custom_field'] == 'raise_non_field_error':15            raise ValidationError('nested-non-field-error')16        return attrs17    def validate_custom_field(self, s):18        if s == 'raise_field_error':19            raise ValidationError('nested-field-error')20        if s == 'raise_multiple_field_errors':21            raise ValidationError(['nested-field-error-1', 'nested-field-error-2'])22        return s23class NestedSerializerWithFormatting(FormattedErrorMessageMixin, NestedSerializerBase):24    """Sample nested serializer with formatting declared solely for test purposes"""25    pass26class MainSerializer(FormattedErrorMessageMixin, serializers.Serializer):27    """Sample parent serializer declared solely for test purposes"""28    int_field = serializers.IntegerField()29    custom_field = serializers.CharField()30    list_field = serializers.ListField(31        child=serializers.IntegerField()32    )33    nested_field = NestedSerializerWithFormatting()34    nested_list_field = NestedSerializerWithFormatting(many=True)35    nested_field_unformatted = NestedSerializerBase()36    nested_list_field_unformatted = NestedSerializerBase(many=True)37    def validate(self, attrs):38        data = self.initial_data39        if data['custom_field'] == 'raise_non_field_error':40            raise ValidationError('parent-non-field-error')41        if data['custom_field'] == 'override_list_fields':42            raise ValidationError({43                'nested_list_field': 'parent_overridden',44                'nested_list_field_unformatted': 'parent_overridden',45            })46        return attrs47    def validate_custom_field(self, s):48        if s == 'raise_field_error':49            raise ValidationError('parent-field-error')50        if s == 'raise_multiple_field_errors':51            raise ValidationError(['parent-field-error-1', 'parent-field-error-2'])52        return s53    class Meta:54        fields = ['int_field', 'custom_field', 'nested_field', 'nested_list_field']55class TestFormattedErrorMessageMixin(object):56    def test_plain_serializer_with_drf_error(self):57        data = {58            'custom_field': 'something',59            'list_field': [],60            'nested_field': {61                'int_field': 1,62                'custom_field': 'something',63                'list_field': []64            },65            'nested_field_unformatted': {66                'int_field': 1,67                'custom_field': 'something',68                'list_field': []69            },70            'nested_list_field': [],71            'nested_list_field_unformatted': []72        }73        serializer = MainSerializer(data=data)74        assert(not serializer.is_valid(raise_exception=False))75        assert(serializer.errors['non_field_errors'] == [])76        assert(serializer.errors['field_errors'] == {77            'int_field': [78                {'code': 'required'}79            ]80        })81    def test_plain_serializer_with_list_error(self):82        data = {83            'int_field': 1,84            'custom_field': 'something',85            'list_field': [1, 2, 'a', ],86            'nested_field': {87                'int_field': 1,88                'custom_field': 'something',89                'list_field': []90            },91            'nested_field_unformatted': {92                'int_field': 1,93                'custom_field': 'something',94                'list_field': []95            },96            'nested_list_field': [],97            'nested_list_field_unformatted': []98        }99        serializer = MainSerializer(data=data)100        assert (not serializer.is_valid(raise_exception=False))101        assert (serializer.errors['non_field_errors'] == [])102        assert (serializer.errors['field_errors'] == {103            'list_field': [104                {'code': 'invalid'}105            ]106        })107        data = {108            'int_field': 1,109            'custom_field': 'something',110            'list_field': 'not a list',111            'nested_field': {112                'int_field': 1,113                'custom_field': 'something',114                'list_field': []115            },116            'nested_field_unformatted': {117                'int_field': 1,118                'custom_field': 'something',119                'list_field': []120            },121            'nested_list_field': [],122            'nested_list_field_unformatted': []123        }124        serializer = MainSerializer(data=data)125        assert (not serializer.is_valid(raise_exception=False))126        assert (serializer.errors['non_field_errors'] == [])127        assert (serializer.errors['field_errors'] == {128            'list_field': [129                {'code': 'not_a_list'}130            ]131        })132    def test_plain_serializer_with_custom_error(self):133        data = {134            'int_field': 1,135            'custom_field': 'raise_field_error',136            'list_field': [],137            'nested_field': {138                'int_field': 1,139                'custom_field': 'something',140                'list_field': []141            },142            'nested_field_unformatted': {143                'int_field': 1,144                'custom_field': 'something',145                'list_field': []146            },147            'nested_list_field': [],148            'nested_list_field_unformatted': []149        }150        serializer = MainSerializer(data=data)151        assert (not serializer.is_valid(raise_exception=False))152        assert (serializer.errors['non_field_errors'] == [])153        assert (serializer.errors['field_errors'] == {154            'custom_field': [155                {'code': 'parent-field-error'}156            ]157        })158        data = {159            'int_field': 1,160            'custom_field': 'raise_multiple_field_errors',161            'list_field': [],162            'nested_field': {163                'int_field': 1,164                'custom_field': 'something',165                'list_field': []166            },167            'nested_field_unformatted': {168                'int_field': 1,169                'custom_field': 'something',170                'list_field': []171            },172            'nested_list_field': [],173            'nested_list_field_unformatted': []174        }175        serializer = MainSerializer(data=data)176        assert(not serializer.is_valid(raise_exception=False))177        assert(serializer.errors['non_field_errors'] == [])178        assert(179            frozenset(180                [e['code'] for e in serializer.errors['field_errors']['custom_field']]181            ) == frozenset(['parent-field-error-1', 'parent-field-error-2'])182        )183    def test_plain_serializer_with_non_field_custom_error(self):184        data = {185            'int_field': 1,186            'custom_field': 'raise_non_field_error',187            'list_field': [],188            'nested_field': {189                'int_field': 1,190                'custom_field': 'something',191                'list_field': []192            },193            'nested_field_unformatted': {194                'int_field': 1,195                'custom_field': 'something',196                'list_field': []197            },198            'nested_list_field': [],199            'nested_list_field_unformatted': []200        }201        serializer = MainSerializer(data=data)202        assert(not serializer.is_valid(raise_exception=False))203        assert(serializer.errors['field_errors'] == {})204        assert(serializer.errors['non_field_errors'] == [{'code': 'parent-non-field-error'}, ])205    def test_nested_serializer_with_drf_and_custom_errors(self):206        data = {207            'int_field': 1,208            'custom_field': 'something',209            'list_field': [],210            'nested_field': {211                'custom_field': 'raise_multiple_field_errors',212                'list_field': [1, 2, 'a']213            },214            'nested_field_unformatted': {215                'custom_field': 'raise_multiple_field_errors',216                'list_field': [1, 2, 'a']217            },218            'nested_list_field': [],219            'nested_list_field_unformatted': []220        }221        serializer = MainSerializer(data=data)222        assert (not serializer.is_valid(raise_exception=False))223        assert (serializer.errors['non_field_errors'] == [])224        assert (serializer.errors['field_errors'] == {225            'nested_field': {226                'code': 'err_api_exception',227                'field_errors': {228                    'custom_field': [229                        {'code': 'nested-field-error-1'},230                        {'code': 'nested-field-error-2'}231                    ],232                    'int_field': [{'code': 'required'}],233                    'list_field': [{'code': 'invalid'}]234                },235                'non_field_errors': []236            },237            'nested_field_unformatted': {238                'code': 'err_api_exception',239                'field_errors': {240                    'custom_field': [241                        {'code': 'nested-field-error-1'},242                        {'code': 'nested-field-error-2'}243                    ],244                    'int_field': [{'code': 'required'}],245                    'list_field': [{'code': 'invalid'}]246                },247                'non_field_errors': []248            },249        })250    def test_nested_list_serializer_with_drf_and_custom_error(self):251        data = {252            'int_field': 1,253            'custom_field': 'something',254            'list_field': [],255            'nested_field': {256                'int_field': 1,257                'custom_field': 'something',258                'list_field': []259            },260            'nested_field_unformatted': {261                'int_field': 1,262                'custom_field': 'something',263                'list_field': []264            },265            'nested_list_field': [266                {267                    'custom_field': 'raise_multiple_field_errors',268                    'list_field': [1, 2, 'a']269                },270                {271                    'int_field': 1,272                    'custom_field': 'something',273                    'list_field': []274                },275                {276                    'custom_field': 'raise_multiple_field_errors',277                    'list_field': [1, 2, 'a']278                }279            ],280            'nested_list_field_unformatted': [281                {282                    'custom_field': 'raise_multiple_field_errors',283                    'list_field': [1, 2, 'a']284                },285                {286                    'int_field': 1,287                    'custom_field': 'something',288                    'list_field': []289                },290                {291                    'custom_field': 'raise_multiple_field_errors',292                    'list_field': [1, 2, 'a']293                }294            ]295        }296        serializer = MainSerializer(data=data)297        assert (not serializer.is_valid(raise_exception=False))298        assert (serializer.errors['non_field_errors'] == [])299        assert (serializer.errors['field_errors'] == {300            'nested_list_field': [301                {302                    'code': 'err_api_exception',303                    'field_errors': {304                        'custom_field': [305                            {'code': 'nested-field-error-1'},306                            {'code': 'nested-field-error-2'}307                        ],308                        'int_field': [{'code': 'required'}],309                        'list_field': [{'code': 'invalid'}]310                    },311                    'non_field_errors': []312                },313                {},  # no error in this element314                {315                    'code': 'err_api_exception',316                    'field_errors': {317                        'custom_field': [318                            {'code': 'nested-field-error-1'},319                            {'code': 'nested-field-error-2'}320                        ],321                        'int_field': [{'code': 'required'}],322                        'list_field': [{'code': 'invalid'}]323                    },324                    'non_field_errors': []325                }326            ],327            'nested_list_field_unformatted': [328                {329                    'code': 'err_api_exception',330                    'field_errors': {331                        'custom_field': [332                            {'code': 'nested-field-error-1'},333                            {'code': 'nested-field-error-2'}334                        ],335                        'int_field': [{'code': 'required'}],336                        'list_field': [{'code': 'invalid'}]337                    },338                    'non_field_errors': []339                },340                {},  # no error in this element341                {342                    'code': 'err_api_exception',343                    'field_errors': {344                        'custom_field': [345                            {'code': 'nested-field-error-1'},346                            {'code': 'nested-field-error-2'}347                        ],348                        'int_field': [{'code': 'required'}],349                        'list_field': [{'code': 'invalid'}]350                    },351                    'non_field_errors': []352                }353            ]354        })355    def test_nested_list_serializer_with_parent_override(self):356        # Verify, that parent serializer can completely override357        # nested serializer's validation (this is effectively what we're doing358        # with service validation in AppointmentMixin359        data = {360            'int_field': 1,361            'custom_field': 'override_list_fields',362            'list_field': [],363            'nested_field': {364                'int_field': 1,365                'custom_field': 'something',366                'list_field': []367            },368            'nested_field_unformatted': {369                'int_field': 1,370                'custom_field': 'something',371                'list_field': []372            },373            'nested_list_field': [374                {375                    'int_field': 1,376                    'custom_field': 'something',377                    'list_field': []378                },379                {380                    'int_field': 1,381                    'custom_field': 'something',382                    'list_field': []383                }384            ],385            'nested_list_field_unformatted': [386                {387                    'int_field': 1,388                    'custom_field': 'something',389                    'list_field': []390                }391            ]392        }393        serializer = MainSerializer(data=data)394        assert (not serializer.is_valid(raise_exception=False))395        assert (serializer.errors['non_field_errors'] == [])396        assert (serializer.errors['field_errors'] == {397            'nested_list_field': [{'code': 'parent_overridden'}],398            'nested_list_field_unformatted': [{'code': 'parent_overridden'}]399        })400    def test_nested_serializer_with_non_field_custom_error(self):401        data = {402            'int_field': 1,403            'custom_field': 'something',404            'list_field': [],405            'nested_field': {406                'int_field': 3,407                'custom_field': 'raise_non_field_error',408                'list_field': []409            },410            'nested_field_unformatted': {411                'int_field': 4,412                'custom_field': 'raise_non_field_error',413                'list_field': []414            },415            'nested_list_field': [416                {417                    'int_field': 5,418                    'custom_field': 'raise_non_field_error',419                    'list_field': []420                }421            ],422            'nested_list_field_unformatted': [423                {424                    'int_field': 6,425                    'custom_field': 'raise_non_field_error',426                    'list_field': []427                }428            ]429        }430        serializer = MainSerializer(data=data)431        assert (not serializer.is_valid(raise_exception=False))432        assert(serializer.errors['field_errors'] == {433            'nested_field': {434                'code': 'err_api_exception',435                'field_errors': {},436                'non_field_errors': [437                    {'code': 'nested-non-field-error'}438                ]439            },440            'nested_field_unformatted': {441                'code': 'err_api_exception',442                'field_errors': {},443                'non_field_errors': [444                    {'code': 'nested-non-field-error'}445                ]446            },447            'nested_list_field': [448                {449                    'code': 'err_api_exception',450                    'field_errors': {},451                    'non_field_errors': [452                        {'code': 'nested-non-field-error'}453                    ]454                }455            ],456            'nested_list_field_unformatted': [457                {458                    'code': 'err_api_exception',459                    'field_errors': {},460                    'non_field_errors': [461                        {'code': 'nested-non-field-error'}462                    ]463                }464            ]...test_patched_urls.py
Source:test_patched_urls.py  
1from django.conf import settings2from django import template3from django.test import TestCase4from nose import tools5from unit.helpers import create_categories_site6class TestAbsoluteURLsCase(TestCase):7    def setUp(self):8        super(TestAbsoluteURLsCase, self).setUp()9        create_categories_site(self)10    # get_absolute_url tests11    def test_root_category_get_absolute_urls_works_unaffected(self):12        tools.assert_equals('http://example.com/', self.category_root.get_absolute_url())13    def test_category_get_absolute_url_is_patched(self):14        tools.assert_equals('http://nested-one.example.com/', self.category_nested_1.get_absolute_url())15    def test_category_get_absolute_url_works_for_second_level_categories(self):16        tools.assert_equals('http://nested-one.example.com/nested-nested-1/', self.category_nested_nested_1.get_absolute_url())17    def test_no_subdomain_category_get_absolute_url_works_unaffected(self):18        tools.assert_equals('http://example.com/nested-2/', self.category_nested_2.get_absolute_url())19    def test_no_subdomain_second_level_category_get_absolute_url_works_unaffected(self):20        tools.assert_equals('http://example.com/nested-2/nested-nested-2/', self.category_nested_nested_2.get_absolute_url())21    # pathed reverse tests22    def test_root_category_reverse_works_unaffected(self):23        from django.core.urlresolvers import reverse24        tools.assert_equals('http://example.com/', reverse('category_detail', args=('/',)))25    def test_category_reverse_is_patched(self):26        from django.core.urlresolvers import reverse27        tools.assert_equals('http://nested-one.example.com/', reverse('category_detail', args=(self.category_nested_1.tree_path,)))28    def test_category_reverse_works_for_second_level_categories(self):29        from django.core.urlresolvers import reverse30        tools.assert_equals('http://nested-one.example.com/nested-nested-1/', reverse('category_detail', args=(self.category_nested_nested_1.tree_path,)))31    def test_no_subdomain_category_reverse_works_unaffected(self):32        from django.core.urlresolvers import reverse33        tools.assert_equals('http://example.com/nested-2/', reverse('category_detail', args=(self.category_nested_2.tree_path,)))34    def test_no_subdomain_second_level_category_reverse_works_unaffected(self):35        from django.core.urlresolvers import reverse36        tools.assert_equals('http://example.com/nested-2/nested-nested-2/', reverse('category_detail', args=(self.category_nested_nested_2.tree_path,)))37    # url tag tests38    def test_root_category_url_tag_work_unaffected(self):39        t = template.Template('{% url category_detail category %}')40        var = {'category' : '/',}41        tools.assert_equals('http://example.com/', t.render(template.Context(var)))42    def test_url_tag_is_patched(self):43        t = template.Template('{% url category_detail category.tree_path %}')44        var = {'category' : self.category_nested_1,}45        tools.assert_equals('http://nested-one.example.com/', t.render(template.Context(var)))46    def test_url_tag_works_for_second_level_categories(self):47        t = template.Template('{% url category_detail category.tree_path %}')48        var = {'category' : self.category_nested_nested_1,}49        tools.assert_equals('http://nested-one.example.com/nested-nested-1/', t.render(template.Context(var)))50    def test_no_subdomain_category_url_tag_works_unaffected(self):51        t = template.Template('{% url category_detail category.tree_path %}')52        var = {'category' : self.category_nested_2,}53        tools.assert_equals('http://example.com/nested-2/', t.render(template.Context(var)))54    def test_no_subdomain_second_level_category_url_tag_works_unaffected(self):55        t = template.Template('{% url category_detail category.tree_path %}')56        var = {'category' : self.category_nested_nested_2,}57        tools.assert_equals('http://example.com/nested-2/nested-nested-2/', t.render(template.Context(var)))58    # article tests59    def test_root_article_get_absolute_urls_works_unaffected(self):60        tools.assert_equals('http://example.com/2011/9/1/articles/root-article/', self.article_root.get_absolute_url())61    def test_first_level_article_get_absolute_url_is_patched(self):62        tools.assert_equals('http://nested-one.example.com/2011/9/1/articles/nested-1-article/', self.article_nested_1.get_absolute_url())63    def test_root_article_url_tag_work_unaffected(self):64        t = template.Template('{% url object_detail category year month day content_type slug %}')65        var = {'category' : '/', 'content_type': 'articles', 'slug': self.placement_root.slug, 'year': 2011, 'month': 11, 'day': 1}66        tools.assert_equals('http://example.com/2011/11/1/articles/root-article/', t.render(template.Context(var)))67    def test_url_tag_works_first_level_article(self):68        t = template.Template('{% url object_detail category year month day content_type slug %}')69        var = {'category' : self.category_nested_1.tree_path, 'content_type': 'articles', 'slug': self.placement_nested_1.slug, 'year': 2011, 'month': 11, 'day': 1}70        tools.assert_equals('http://nested-one.example.com/2011/11/1/articles/nested-1-article/', t.render(template.Context(var)))71    def test_url_tag_works_second_level_article(self):72        t = template.Template('{% url object_detail category year month day content_type slug %}')73        var = {'category' : self.category_nested_nested_1.tree_path, 'content_type': 'articles', 'slug': self.placement_nested_nested_1.slug, 'year': 2011, 'month': 11, 'day': 1}74        tools.assert_equals('http://nested-one.example.com/nested-nested-1/2011/11/1/articles/nested-nested-1-article/', t.render(template.Context(var)))75    def test_no_subdomain_article_url_tag_work_unaffected(self):76        t = template.Template('{% url object_detail category year month day content_type slug %}')77        var = {'category' : self.category_nested_2.tree_path, 'content_type': 'articles', 'slug': self.placement_nested_2.slug, 'year': 2011, 'month': 11, 'day': 1}78        tools.assert_equals('http://example.com/nested-2/2011/11/1/articles/nested-2-article/', t.render(template.Context(var)))79    def test_no_subdomain_second_level_article_url_tag_work_unaffected(self):80        t = template.Template('{% url object_detail category year month day content_type slug %}')81        var = {'category' : self.category_nested_nested_2.tree_path, 'content_type': 'articles', 'slug': self.placement_nested_2.slug, 'year': 2011, 'month': 11, 'day': 1}82        tools.assert_equals('http://example.com/nested-2/nested-nested-2/2011/11/1/articles/nested-2-article/', t.render(template.Context(var)))83    # site 2 tests84class TestAbsoluteURLsSite2Case(TestCase):85    def setUp(self):86        super(TestAbsoluteURLsSite2Case, self).setUp()87        create_categories_site(self)88        settings.SITE_ID = self.site_2_id89    def test_site_2_root_category_get_absolute_url_works(self):90        tools.assert_equals('http://example1.com/', self.site_2_root.get_absolute_url())91    def test_site_2_category_get_absolute_url_is_patched(self):92        tools.assert_equals('http://nested-one.example1.com/', self.site_2_nested_1.get_absolute_url())93    def test_category_reverse_is_patched(self):94        from django.core.urlresolvers import reverse95        tools.assert_equals('http://nested-one.example1.com/', reverse('category_detail', args=(self.site_2_nested_1.tree_path,)))96    def test_site_2_url_tag_is_patched(self):97        t = template.Template('{% url category_detail category.tree_path %}')98        var = {'category' : self.site_2_nested_1,}99        tools.assert_equals('http://nested-one.example1.com/', t.render(template.Context(var)))100class TestAbsoluteURLsSite3Case(TestCase):101    def setUp(self):102        super(TestAbsoluteURLsSite3Case, self).setUp()103        create_categories_site(self)104        settings.SITE_ID = self.site_3_id105    def test_site_3_root_category_get_absolute_url_works(self):106        tools.assert_equals('http://www.example.com/', self.site_3_root.get_absolute_url())107    def test_site_3_category_get_absolute_url_is_patched(self):108        tools.assert_equals('http://nested-one.example.com/', self.site_3_nested_1.get_absolute_url())109    def test_category_reverse_is_patched(self):110        from django.core.urlresolvers import reverse111        tools.assert_equals('http://nested-one.example.com/', reverse('category_detail', args=(self.site_3_nested_1.tree_path,)))112    def test_site_3_url_tag_is_patched(self):113        t = template.Template('{% url category_detail category.tree_path %}')114        var = {'category' : self.site_3_nested_1,}115        tools.assert_equals('http://nested-one.example.com/', t.render(template.Context(var)))116class TestAbsoluteURLsSite4Case(TestCase):117    def setUp(self):118        super(TestAbsoluteURLsSite4Case, self).setUp()119        create_categories_site(self)120        settings.SITE_ID = self.site_4_id121    def test_site_4_root_category_get_absolute_url_works(self):122        tools.assert_equals('http://www.example.co.uk/', self.site_4_root.get_absolute_url())123    def test_site_4_category_get_absolute_url_is_patched(self):124        tools.assert_equals('http://nested-one.example.co.uk/', self.site_4_nested_1.get_absolute_url())125    def test_category_reverse_is_patched(self):126        from django.core.urlresolvers import reverse127        tools.assert_equals('http://nested-one.example.co.uk/', reverse('category_detail', args=(self.site_4_nested_1.tree_path,)))128    def test_site_4_url_tag_is_patched(self):129        t = template.Template('{% url category_detail category.tree_path %}')130        var = {'category' : self.site_4_nested_1,}...helpers.py
Source:helpers.py  
1import datetime2import logging3from django.contrib.auth.models import User4from django.contrib.contenttypes.models import ContentType5from django.contrib.sites.models import Site6from ella.core.models import Category7from ella.core.models import Author8from ella.core.models import Placement9from ella.articles.models import Article10from ella_category_subdomain.models import CategorySubdomain11def create_categories_site(case):12    # site 113    case.site_1 = Site.objects.create(name="example.com", domain="example.com")14    case.site_1.save()15    case.site_1_id = case.site_1.id16    # site 217    case.site_2 = Site.objects.create(name="example1.com", domain="example1.com")18    case.site_2.save()19    case.site_2_id = case.site_2.id20    # site 321    case.site_3 = Site.objects.create(name="www.example.com", domain="www.example.com")22    case.site_3.save()23    case.site_3_id = case.site_3.id24    # site 425    case.site_4 = Site.objects.create(name="www.example.co.uk", domain="www.example.co.uk")26    case.site_4.save()27    case.site_4_id = case.site_4.id28    # site 1 categories29    case.category_root = Category.objects.create(title='Root', slug='root_homepage', tree_parent=None, site=case.site_1)30    case.category_root.save()31    case.category_nested_1 = Category.objects.create(title='Nested 1', slug='nested-1', tree_parent=case.category_root, site=case.site_1)32    case.category_nested_1.save()33    case.category_nested_2 = Category.objects.create(title='Nested 2', slug='nested-2', tree_parent=case.category_root, site=case.site_1)34    case.category_nested_2.save()35    case.category_nested_nested_1 = Category.objects.create(title='Nested Nested 1', slug='nested-nested-1', tree_parent=case.category_nested_1, site=case.site_1)36    case.category_nested_nested_1.save()37    case.category_nested_nested_2 = Category.objects.create(title='Nested Nested 2', slug='nested-nested-2', tree_parent=case.category_nested_2, site=case.site_1)38    case.category_nested_nested_2.save()39    case.category_subdomain_nested_1 = CategorySubdomain.objects.create(category=case.category_nested_1, subdomain_slug='nested-one')40    case.category_subdomain_nested_1.save()41    # site 1 articles42    publish_from = datetime.datetime(2011, 9, 1)43    author = Author.objects.create(name='User', slug='user')44    author.save()45    case.article_root = Article(category=case.category_root, title='Root Article', slug='root-article',)46    case.article_root.save()47    case.article_root.authors.add(author)48    case.placement_root = Placement.objects.create(publishable=case.article_root, category=case.category_root, publish_from=publish_from,)49    case.placement_root.save()50    case.article_nested_1 = Article(category=case.category_nested_1, title='Nested 1 Article', slug='nested-1-article',)51    case.article_nested_1.save()52    case.article_nested_1.authors.add(author)53    case.placement_nested_1 = Placement.objects.create(publishable=case.article_nested_1, category=case.category_nested_1, publish_from=publish_from,)54    case.placement_nested_1.save()55    case.article_nested_nested_1 = Article(category=case.category_nested_nested_1, title='Nested Nested 1 Article', slug='nested-nested-1-article',)56    case.article_nested_nested_1.save()57    case.article_nested_nested_1.authors.add(author)58    case.placement_nested_nested_1 = Placement.objects.create(publishable=case.article_nested_nested_1, category=case.category_nested_nested_1, publish_from=publish_from,)59    case.placement_nested_nested_1.save()60    case.article_nested_2 = Article(category=case.category_nested_2, title='Nested 2 Article', slug='nested-2-article',)61    case.article_nested_2.save()62    case.article_nested_2.authors.add(author)63    case.placement_nested_2 = Placement.objects.create(publishable=case.article_nested_2, category=case.category_nested_2, publish_from=publish_from,)64    case.placement_nested_2.save()65    case.article_nested_nested_2 = Article(category=case.category_nested_nested_2, title='Nested 2 Article', slug='nested-2-article',)66    case.article_nested_nested_2.save()67    case.article_nested_nested_2.authors.add(author)68    case.placement_nested_nested_2 = Placement.objects.create(publishable=case.article_nested_nested_2, category=case.category_nested_nested_2, publish_from=publish_from,)69    case.placement_nested_nested_2.save()70    # site 2 categories71    case.site_2_root = Category.objects.create(title='Root', slug='s2-root', tree_parent=None, site=case.site_2)72    case.site_2_root.save()73    case.site_2_nested_1 = Category.objects.create(title='Nested 1', slug='s2-nested-1', tree_parent=case.site_2_root, site=case.site_2)74    case.site_2_nested_1.save()75    case.site_2_nested_2 = Category.objects.create(title='Nested 2', slug='s2-nested-2', tree_parent=case.site_2_root, site=case.site_2)76    case.site_2_nested_2.save()77    case.site_2_category_subdomain_nested_1 = CategorySubdomain.objects.create(category=case.site_2_nested_1, subdomain_slug='nested-one')78    case.site_2_category_subdomain_nested_1.save()79    # site 3 categories80    case.site_3_root = Category.objects.create(title='Root', slug='s3-root', tree_parent=None, site=case.site_3)81    case.site_3_root.save()82    case.site_3_nested_1 = Category.objects.create(title='Nested 1', slug='s3-nested-1', tree_parent=case.site_3_root, site=case.site_3)83    case.site_3_nested_1.save()84    case.site_3_nested_2 = Category.objects.create(title='Nested 2', slug='s3-nested-2', tree_parent=case.site_3_root, site=case.site_3)85    case.site_3_nested_2.save()86    case.site_3_category_subdomain_nested_1 = CategorySubdomain.objects.create(category=case.site_3_nested_1, subdomain_slug='nested-one')87    case.site_3_category_subdomain_nested_1.save()88    # site 4 categories89    case.site_4_root = Category.objects.create(title='Root', slug='s4-root', tree_parent=None, site=case.site_4)90    case.site_4_root.save()91    case.site_4_nested_1 = Category.objects.create(title='Nested 1', slug='s4-nested-1', tree_parent=case.site_4_root, site=case.site_4)92    case.site_4_nested_1.save()93    case.site_4_nested_2 = Category.objects.create(title='Nested 2', slug='s4-nested-2', tree_parent=case.site_4_root, site=case.site_4)94    case.site_4_nested_2.save()95    case.site_4_category_subdomain_nested_1 = CategorySubdomain.objects.create(category=case.site_4_nested_1, subdomain_slug='nested-one')...mock_test.py
Source:mock_test.py  
1#2# Copyright 2015 Google Inc.3#4# Licensed under the Apache License, Version 2.0 (the "License");5# you may not use this file except in compliance with the License.6# You may obtain a copy of the License at7#8#     http://www.apache.org/licenses/LICENSE-2.09#10# Unless required by applicable law or agreed to in writing, software11# distributed under the License is distributed on an "AS IS" BASIS,12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13# See the License for the specific language governing permissions and14# limitations under the License.15"""Tests for apitools.base.py.testing.mock."""16import unittest217from apitools.base.protorpclite import messages18import apitools.base.py as apitools_base19from apitools.base.py.testing import mock20from apitools.base.py.testing import testclient as fusiontables21class MockTest(unittest2.TestCase):22    def testMockFusionBasic(self):23        with mock.Client(fusiontables.FusiontablesV1) as client_class:24            client_class.column.List.Expect(request=1, response=2)25            client = fusiontables.FusiontablesV1(get_credentials=False)26            self.assertEqual(client.column.List(1), 2)27            with self.assertRaises(mock.UnexpectedRequestException):28                client.column.List(3)29    def testMockFusionException(self):30        with mock.Client(fusiontables.FusiontablesV1) as client_class:31            client_class.column.List.Expect(32                request=1,33                exception=apitools_base.HttpError({'status': 404}, '', ''))34            client = fusiontables.FusiontablesV1(get_credentials=False)35            with self.assertRaises(apitools_base.HttpError):36                client.column.List(1)37    def testMockFusionOrder(self):38        with mock.Client(fusiontables.FusiontablesV1) as client_class:39            client_class.column.List.Expect(request=1, response=2)40            client_class.column.List.Expect(request=2, response=1)41            client = fusiontables.FusiontablesV1(get_credentials=False)42            self.assertEqual(client.column.List(1), 2)43            self.assertEqual(client.column.List(2), 1)44    def testMockFusionWrongOrder(self):45        with mock.Client(fusiontables.FusiontablesV1) as client_class:46            client_class.column.List.Expect(request=1, response=2)47            client_class.column.List.Expect(request=2, response=1)48            client = fusiontables.FusiontablesV1(get_credentials=False)49            with self.assertRaises(mock.UnexpectedRequestException):50                self.assertEqual(client.column.List(2), 1)51            with self.assertRaises(mock.UnexpectedRequestException):52                self.assertEqual(client.column.List(1), 2)53    def testMockFusionTooMany(self):54        with mock.Client(fusiontables.FusiontablesV1) as client_class:55            client_class.column.List.Expect(request=1, response=2)56            client = fusiontables.FusiontablesV1(get_credentials=False)57            self.assertEqual(client.column.List(1), 2)58            with self.assertRaises(mock.UnexpectedRequestException):59                self.assertEqual(client.column.List(2), 1)60    def testMockFusionTooFew(self):61        with self.assertRaises(mock.ExpectedRequestsException):62            with mock.Client(fusiontables.FusiontablesV1) as client_class:63                client_class.column.List.Expect(request=1, response=2)64                client_class.column.List.Expect(request=2, response=1)65                client = fusiontables.FusiontablesV1(get_credentials=False)66                self.assertEqual(client.column.List(1), 2)67    def testFusionUnmock(self):68        with mock.Client(fusiontables.FusiontablesV1):69            client = fusiontables.FusiontablesV1(get_credentials=False)70            mocked_service_type = type(client.column)71        client = fusiontables.FusiontablesV1(get_credentials=False)72        self.assertNotEqual(type(client.column), mocked_service_type)73    def testClientUnmock(self):74        mock_client = mock.Client(fusiontables.FusiontablesV1)75        attributes = set(mock_client.__dict__.keys())76        mock_client = mock_client.Mock()77        self.assertTrue(set(mock_client.__dict__.keys()) - attributes)78        mock_client.Unmock()79        self.assertEqual(attributes, set(mock_client.__dict__.keys()))80class _NestedMessage(messages.Message):81    nested = messages.StringField(1)82class _NestedListMessage(messages.Message):83    nested_list = messages.MessageField(_NestedMessage, 1, repeated=True)84class _NestedNestedMessage(messages.Message):85    nested = messages.MessageField(_NestedMessage, 1)86class UtilTest(unittest2.TestCase):87    def testMessagesEqual(self):88        self.assertFalse(mock._MessagesEqual(89            _NestedNestedMessage(90                nested=_NestedMessage(91                    nested='foo')),92            _NestedNestedMessage(93                nested=_NestedMessage(94                    nested='bar'))))95        self.assertTrue(mock._MessagesEqual(96            _NestedNestedMessage(97                nested=_NestedMessage(98                    nested='foo')),99            _NestedNestedMessage(100                nested=_NestedMessage(101                    nested='foo'))))102    def testListedMessagesEqual(self):103        self.assertTrue(mock._MessagesEqual(104            _NestedListMessage(105                nested_list=[_NestedMessage(nested='foo')]),106            _NestedListMessage(107                nested_list=[_NestedMessage(nested='foo')])))108        self.assertTrue(mock._MessagesEqual(109            _NestedListMessage(110                nested_list=[_NestedMessage(nested='foo'),111                             _NestedMessage(nested='foo2')]),112            _NestedListMessage(113                nested_list=[_NestedMessage(nested='foo'),114                             _NestedMessage(nested='foo2')])))115        self.assertFalse(mock._MessagesEqual(116            _NestedListMessage(117                nested_list=[_NestedMessage(nested='foo')]),118            _NestedListMessage(119                nested_list=[_NestedMessage(nested='bar')])))120        self.assertFalse(mock._MessagesEqual(121            _NestedListMessage(122                nested_list=[_NestedMessage(nested='foo')]),123            _NestedListMessage(124                nested_list=[_NestedMessage(nested='foo'),...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
