Best Python code snippet using avocado_python
test_page_modeladmin.py
Source:test_page_modeladmin.py  
1from __future__ import absolute_import, unicode_literals2from django.contrib.auth import get_user_model3from django.contrib.auth.models import Group, Permission4from django.test import TestCase5from wagtail.tests.testapp.models import BusinessIndex, EventCategory, EventPage6from wagtail.tests.utils import WagtailTestUtils7from wagtail.wagtailcore.models import GroupPagePermission, Page8class TestIndexView(TestCase, WagtailTestUtils):9    # wagtail/tests/testapp/fixtures/test_specific.json10    fixtures = ['test_specific.json']11    def setUp(self):12        self.login()13    def get(self, **params):14        return self.client.get('/admin/tests/eventpage/', params)15    def test_simple(self):16        response = self.get()17        self.assertEqual(response.status_code, 200)18        # There are four event pages in the test data19        self.assertEqual(response.context['result_count'], 4)20        # User has add permission21        self.assertEqual(response.context['user_can_create'], True)22    def test_filter(self):23        # Filter by audience24        response = self.get(audience__exact='public')25        self.assertEqual(response.status_code, 200)26        # Only three of the event page in the test data are 'public'27        self.assertEqual(response.context['result_count'], 3)28        for eventpage in response.context['object_list']:29            self.assertEqual(eventpage.audience, 'public')30    def test_search(self):31        response = self.get(q='Someone')32        self.assertEqual(response.status_code, 200)33        # There are two eventpage's where the title contains 'Someone'34        self.assertEqual(response.context['result_count'], 1)35    def test_ordering(self):36        response = self.get(o='0.1')37        self.assertEqual(response.status_code, 200)38        # There should still be four results39        self.assertEqual(response.context['result_count'], 4)40class TestExcludeFromExplorer(TestCase, WagtailTestUtils):41    fixtures = ['test_specific.json']42    def setUp(self):43        self.login()44    def test_attribute_effects_explorer(self):45        # The two VenuePages should appear in the venuepage list46        response = self.client.get('/admin/modeladmintest/venuepage/')47        self.assertContains(response, "Santa's Grotto")48        self.assertContains(response, "Santa's Workshop")49        # But when viewing the children of 'Christmas' event in explorer50        response = self.client.get('/admin/pages/4/')51        self.assertNotContains(response, "Santa's Grotto")52        self.assertNotContains(response, "Santa's Workshop")53        # But the other test page should...54        self.assertContains(response, "Claim your free present!")55class TestCreateView(TestCase, WagtailTestUtils):56    # wagtail/tests/testapp/fixtures/test_specific.json57    fixtures = ['test_specific.json']58    def setUp(self):59        self.login()60    def test_redirect_to_choose_parent(self):61        # When more than one possible parent page exists, redirect to choose_parent62        response = self.client.get('/admin/tests/eventpage/create/')63        self.assertRedirects(response, '/admin/tests/eventpage/choose_parent/')64    def test_one_parent_exists(self):65        # Create a BusinessIndex page that BusinessChild can exist under66        homepage = Page.objects.get(url_path='/home/')67        business_index = BusinessIndex(title='Business Index')68        homepage.add_child(instance=business_index)69        # When one possible parent page exists, redirect straight to the page create view70        response = self.client.get('/admin/tests/businesschild/create/')71        expected_path = '/admin/pages/add/tests/businesschild/%d/' % business_index.pk72        expected_next_path = '/admin/tests/businesschild/'73        self.assertRedirects(response, '%s?next=%s' % (expected_path, expected_next_path))74class TestInspectView(TestCase, WagtailTestUtils):75    # wagtail/tests/testapp/fixtures/test_specific.json76    fixtures = ['test_specific.json']77    def setUp(self):78        self.login()79    def get(self, id):80        return self.client.get('/admin/tests/eventpage/inspect/%d/' % id)81    def test_simple(self):82        response = self.get(4)83        self.assertEqual(response.status_code, 200)84    def test_title_present(self):85        """86        The page title should appear twice. Once in the header, and once87        more in the field listing88        """89        response = self.get(4)90        self.assertContains(response, 'Christmas', 2)91    def test_manytomany_output(self):92        """93        Because ManyToMany fields are output InspectView by default, the94        `categories` for the event should output as a comma separated list95        once populated.96        """97        eventpage = EventPage.objects.get(pk=4)98        free_category = EventCategory.objects.create(name='Free')99        child_friendly_category = EventCategory.objects.create(name='Child-friendly')100        eventpage.categories = (free_category, child_friendly_category)101        eventpage.save()102        response = self.get(4)103        self.assertContains(response, '<dd>Free, Child-friendly</dd>', html=True)104    def test_false_values_displayed(self):105        """106        Boolean fields with False values should display False, rather than the107        value of `get_empty_value_display()`. For this page, those should be108        `locked`, `expired` and `has_unpublished_changes`109        """110        response = self.get(4)111        self.assertContains(response, '<dd>False</dd>', count=3, html=True)112    def test_location_present(self):113        """114        The location should appear once, in the field listing115        """116        response = self.get(4)117        self.assertContains(response, 'The North Pole', 1)118    def test_non_existent(self):119        response = self.get(100)120        self.assertEqual(response.status_code, 404)121class TestEditView(TestCase, WagtailTestUtils):122    # wagtail/tests/testapp/fixtures/test_specific.json123    fixtures = ['test_specific.json']124    def setUp(self):125        self.login()126    def get(self, obj_id):127        return self.client.get('/admin/tests/eventpage/edit/%d/' % obj_id)128    def test_simple(self):129        response = self.get(4)130        expected_path = '/admin/pages/4/edit/'131        expected_next_path = '/admin/tests/eventpage/'132        self.assertRedirects(response, '%s?next=%s' % (expected_path, expected_next_path))133    def test_non_existent(self):134        response = self.get(100)135        self.assertEqual(response.status_code, 404)136class TestDeleteView(TestCase, WagtailTestUtils):137    # wagtail/tests/testapp/fixtures/test_specific.json138    fixtures = ['test_specific.json']139    def setUp(self):140        self.login()141    def get(self, obj_id):142        return self.client.get('/admin/tests/eventpage/delete/%d/' % obj_id)143    def test_simple(self):144        response = self.get(4)145        expected_path = '/admin/pages/4/delete/'146        expected_next_path = '/admin/tests/eventpage/'147        self.assertRedirects(response, '%s?next=%s' % (expected_path, expected_next_path))148class TestChooseParentView(TestCase, WagtailTestUtils):149    # wagtail/tests/testapp/fixtures/test_specific.json150    fixtures = ['test_specific.json']151    def setUp(self):152        self.login()153    def test_simple(self):154        response = self.client.get('/admin/tests/eventpage/choose_parent/')155        self.assertEqual(response.status_code, 200)156    def test_no_parent_exists(self):157        response = self.client.get('/admin/tests/businesschild/choose_parent/')158        self.assertEqual(response.status_code, 403)159    def test_post(self):160        response = self.client.post('/admin/tests/eventpage/choose_parent/', {161            'parent_page': 2,162        })163        expected_path = '/admin/pages/add/tests/eventpage/2/'164        expected_next_path = '/admin/tests/eventpage/'165        self.assertRedirects(response, '%s?next=%s' % (expected_path, expected_next_path))166class TestChooseParentViewForNonSuperuser(TestCase, WagtailTestUtils):167    # wagtail/tests/testapp/fixtures/test_specific.json168    fixtures = ['test_specific.json']169    def setUp(self):170        homepage = Page.objects.get(url_path='/home/')171        business_index = BusinessIndex(title='Public Business Index')172        homepage.add_child(instance=business_index)173        another_business_index = BusinessIndex(title='Another Business Index')174        homepage.add_child(instance=another_business_index)175        secret_business_index = BusinessIndex(title='Private Business Index')176        homepage.add_child(instance=secret_business_index)177        business_editors = Group.objects.create(name='Business editors')178        business_editors.permissions.add(Permission.objects.get(codename='access_admin'))179        GroupPagePermission.objects.create(180            group=business_editors,181            page=business_index,182            permission_type='add'183        )184        GroupPagePermission.objects.create(185            group=business_editors,186            page=another_business_index,187            permission_type='add'188        )189        user = get_user_model().objects._create_user(username='test2', email='test2@email.com', password='password', is_staff=True, is_superuser=False)190        user.groups.add(business_editors)191        # Login192        self.client.login(username='test2', password='password')193    def test_simple(self):194        response = self.client.get('/admin/tests/businesschild/choose_parent/')195        self.assertEqual(response.status_code, 200)196        self.assertContains(response, 'Public Business Index')197        self.assertNotContains(response, 'Private Business Index')198class TestEditorAccess(TestCase):199    # wagtail/tests/testapp/fixtures/test_specific.json200    fixtures = ['test_specific.json']201    expected_status_code = 403202    def login(self):203        # Create a user204        user = get_user_model().objects._create_user(username='test2', email='test2@email.com', password='password', is_staff=True, is_superuser=False)205        user.groups.add(Group.objects.get(pk=2))206        # Login207        self.client.login(username='test2', password='password')208        return user209    def setUp(self):210        self.login()211    def test_delete_permitted(self):212        response = self.client.get('/admin/tests/eventpage/delete/4/')213        self.assertEqual(response.status_code, self.expected_status_code)214class TestModeratorAccess(TestCase):215    # wagtail/tests/testapp/fixtures/test_specific.json216    fixtures = ['test_specific.json']217    expected_status_code = 302218    def login(self):219        # Create a user220        user = get_user_model().objects._create_user(username='test3', email='test3@email.com', password='password', is_staff=True, is_superuser=False)221        user.groups.add(Group.objects.get(pk=1))222        # Login223        self.client.login(username='test2', password='password')224        return user225    def setUp(self):226        self.login()227    def test_delete_permitted(self):228        response = self.client.get('/admin/tests/eventpage/delete/4/')...manuscript_test.py
Source:manuscript_test.py  
1# encoding=utf-82import pytest3from sefaria.model import *4from sefaria.system.exceptions import *5def make_testing_manuscript_page(manuscript_slug, page_id, **kwargs) -> ManuscriptPage:6    """7    Convenience method, sets the required url attributes to filler values, and giving a valid ManuscriptPage instance.8    Other parameters can be set with a keyword argument.9    :param manuscript_slug:10    :param page_id:11    :return:12    """13    data_dict = {14        'image_url': 'foo',15        'thumbnail_url': 'foo.thumb',16        'page_id': page_id,17        'manuscript_slug': manuscript_slug18    }19    for attr in ManuscriptPage.required_attrs:20        if attr in kwargs:21            data_dict[attr] = kwargs[attr]22    return ManuscriptPage().load_from_dict(data_dict)23def make_testing_manuscript(title, **kwargs) -> Manuscript:24    """25    Convenience method, sets all the required attributes except the title and return a valid Manuscript instance.26    Other parameters can be set with a keyword argument.27    :param title:28    :return:29    """30    data_dict = {  # slug gets defined from the title, we do not need to set it manually31        'title': title,32        'he_title': 'פ×',33        'source': 'This manuscript is a forgery',34        'description': 'testing manuscript, delete this',35        'he_description': '×¤× ×ר'36    }37    for attr in Manuscript.required_attrs:38        if attr in kwargs:39            data_dict[attr] = kwargs[attr]40    return Manuscript().load_from_dict(data_dict)41def setup_module():42    teardown_module()43    m = make_testing_manuscript('Delete Me')44    m.save()45    for i in range(5):46        page = make_testing_manuscript_page(m.slug, i)47        page.save()48def teardown_module():49    possible_titles = ['Delete Me', 'Remove Me']50    for title in possible_titles:51        m = Manuscript().load({'slug': Manuscript.normalize_slug(title)})52        if m:53            m.delete()54        ManuscriptPageSet({'manuscript_slug': Manuscript.normalize_slug(title)}).delete()55class TestDataValidation:56    def test_check_for_parent(self):57        foo = make_testing_manuscript_page('no_parent', 1)58        assert not foo.validate()59        with pytest.raises(ManuscriptError):60            foo.save()61    def test_duplicate_manuscript(self):62        with pytest.raises(DuplicateRecordError):63            make_testing_manuscript('Delete Me').save()64        num_test_manuscripts = ManuscriptSet({'title': 'Delete Me'})65        assert num_test_manuscripts.count() == 166class TestPageRefs:67    @classmethod68    def setup_class(cls):69        refs = [70            'Job 3',71            'Job 4',72            'Job 5-6',73        ]74        slug = Manuscript.normalize_slug('Delete Me')75        for i, r in enumerate(refs):76            mp = ManuscriptPage().load({'manuscript_slug': slug, 'page_id': i})77            if r not in mp.contained_refs:78                mp.add_ref(r)79                mp.save()80    def test_new_ref_overlap(self):81        mp = ManuscriptPage().load({'expanded_refs': 'Job 3:1'})82        assert mp is not None83        with pytest.raises(ManuscriptError):84            mp.add_ref('Job 3-4')85    def test_load_by_segment(self):86        mps = ManuscriptPageSet.load_by_ref(Ref('Job 3:1'))87        test_specific = [m for m in mps if m.manuscript_slug == Manuscript.normalize_slug('Delete Me')]88        assert len(test_specific) == 189    def test_load_by_section(self):90        mps = ManuscriptPageSet.load_by_ref(Ref('Job 3'))91        test_specific = [m for m in mps if m.manuscript_slug == Manuscript.normalize_slug('Delete Me')]92        assert len(test_specific) == 193    def test_load_range(self):94        mps = ManuscriptPageSet.load_by_ref(Ref("Job 4:2-6:3"))95        test_specific = [m for m in mps if m.manuscript_slug == Manuscript.normalize_slug('Delete Me')]96        assert len(test_specific) == 297    def test_load_for_client(self):98        slug = Manuscript.normalize_slug('Delete Me')99        data = ManuscriptPageSet.load_set_for_client("Job 4")100        data = [d for d in data if d['manuscript_slug'] == slug][0]  # this is here to limit us to just the testing data101        mock_page = make_testing_manuscript_page(slug, 1)102        mock_page.add_ref("Job 4")103        mock_page = mock_page.contents()104        mock_page['manuscript'] = make_testing_manuscript('Delete Me').contents()105        mock_page['manuscript']['slug'] = slug106        mock_page['anchorRef'] = "Job 4"107        mock_page['anchorRefExpanded'] = mock_page['expanded_refs']108        del mock_page['expanded_refs']109        del mock_page['contained_refs']110        for key, value in mock_page.items():111            if isinstance(value, list):112                assert sorted(data[key]) == sorted(value)113            else:114                assert data[key] == value115class TestDependencies:116    def test_rename_manuscript(self):117        original_title, new_title = 'Delete Me', 'Remove Me'118        m = Manuscript().load({'slug': Manuscript.normalize_slug(original_title)})119        m.title = new_title120        m.save()121        assert m.slug == Manuscript.normalize_slug(new_title)122        mps = ManuscriptPageSet({'manuscript_slug': Manuscript.normalize_slug(original_title)})123        assert mps.count() == 0124        mps = ManuscriptPageSet({'manuscript_slug': Manuscript.normalize_slug(new_title)})125        assert mps.count() == 5126        m.title = original_title127        m.save()128        mps = ManuscriptPageSet({'manuscript_slug': Manuscript.normalize_slug(original_title)})129        assert mps.count() == 5130        mps = ManuscriptPageSet({'manuscript_slug': Manuscript.normalize_slug(new_title)})131        assert mps.count() == 0132    def test_delete_manuscript(self):133        slug = Manuscript.normalize_slug('Delete Me')134        m = Manuscript().load({'slug': slug})135        m.delete()136        mps = ManuscriptPageSet({'manuscript_slug': slug})137        assert mps.count() == 0...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!!
