Best Python code snippet using pytest-django_python
test_views.py
Source:test_views.py
...16 def setUp(self):17 self.client.force_login(self.superuser)18 def test_index(self):19 response = self.client.get(reverse('django-admindocs-docroot'))20 self.assertContains(response, '<h1>Documentation</h1>', html=True)21 self.assertContains(response, '<h1 id="site-name"><a href="/admin/">Django administration</a></h1>')22 self.client.logout()23 response = self.client.get(reverse('django-admindocs-docroot'), follow=True)24 # Should display the login screen25 self.assertContains(response, '<input type="hidden" name="next" value="/admindocs/">', html=True)26 def test_bookmarklets(self):27 response = self.client.get(reverse('django-admindocs-bookmarklets'))28 self.assertContains(response, '/admindocs/views/')29 def test_templatetag_index(self):30 response = self.client.get(reverse('django-admindocs-tags'))31 self.assertContains(response, '<h3 id="built_in-extends">extends</h3>', html=True)32 def test_templatefilter_index(self):33 response = self.client.get(reverse('django-admindocs-filters'))34 self.assertContains(response, '<h3 id="built_in-first">first</h3>', html=True)35 def test_view_index(self):36 response = self.client.get(reverse('django-admindocs-views-index'))37 self.assertContains(38 response,39 '<h3><a href="/admindocs/views/django.contrib.admindocs.views.BaseAdminDocsView/">/admindocs/</a></h3>',40 html=True41 )42 self.assertContains(response, 'Views by namespace test')43 self.assertContains(response, 'Name: <code>test:func</code>.')44 self.assertContains(45 response,46 '<h3><a href="/admindocs/views/admin_docs.views.XViewCallableObject/">'47 '/xview/callable_object_without_xview/</a></h3>',48 html=True,49 )50 def test_view_index_with_method(self):51 """52 Views that are methods are listed correctly.53 """54 response = self.client.get(reverse('django-admindocs-views-index'))55 self.assertContains(56 response,57 '<h3><a href="/admindocs/views/django.contrib.admin.sites.AdminSite.index/">/admin/</a></h3>',58 html=True59 )60 def test_view_detail(self):61 url = reverse('django-admindocs-views-detail', args=['django.contrib.admindocs.views.BaseAdminDocsView'])62 response = self.client.get(url)63 # View docstring64 self.assertContains(response, 'Base view for admindocs views.')65 @override_settings(ROOT_URLCONF='admin_docs.namespace_urls')66 def test_namespaced_view_detail(self):67 url = reverse('django-admindocs-views-detail', args=['admin_docs.views.XViewClass'])68 response = self.client.get(url)69 self.assertContains(response, '<h1>admin_docs.views.XViewClass</h1>')70 def test_view_detail_illegal_import(self):71 url = reverse('django-admindocs-views-detail', args=['urlpatterns_reverse.nonimported_module.view'])72 response = self.client.get(url)73 self.assertEqual(response.status_code, 404)74 self.assertNotIn("urlpatterns_reverse.nonimported_module", sys.modules)75 def test_view_detail_as_method(self):76 """77 Views that are methods can be displayed.78 """79 url = reverse('django-admindocs-views-detail', args=['django.contrib.admin.sites.AdminSite.index'])80 response = self.client.get(url)81 self.assertEqual(response.status_code, 200)82 def test_model_index(self):83 response = self.client.get(reverse('django-admindocs-models-index'))84 self.assertContains(85 response,86 '<h2 id="app-auth">Authentication and Authorization (django.contrib.auth)</h2>',87 html=True88 )89 def test_template_detail(self):90 response = self.client.get(reverse('django-admindocs-templates', args=['admin_doc/template_detail.html']))91 self.assertContains(response, '<h1>Template: "admin_doc/template_detail.html"</h1>', html=True)92 def test_missing_docutils(self):93 utils.docutils_is_available = False94 try:95 response = self.client.get(reverse('django-admindocs-docroot'))96 self.assertContains(97 response,98 '<h3>The admin documentation system requires Python\'s '99 '<a href="http://docutils.sf.net/">docutils</a> library.</h3>',100 html=True101 )102 self.assertContains(response, '<h1 id="site-name"><a href="/admin/">Django administration</a></h1>')103 finally:104 utils.docutils_is_available = True105 @modify_settings(INSTALLED_APPS={'remove': 'django.contrib.sites'})106 @override_settings(SITE_ID=None) # will restore SITE_ID after the test107 def test_no_sites_framework(self):108 """109 Without the sites framework, should not access SITE_ID or Site110 objects. Deleting settings is fine here as UserSettingsHolder is used.111 """112 Site.objects.all().delete()113 del settings.SITE_ID114 response = self.client.get(reverse('django-admindocs-views-index'))115 self.assertContains(response, 'View documentation')116@override_settings(TEMPLATES=[{117 'NAME': 'ONE',118 'BACKEND': 'django.template.backends.django.DjangoTemplates',119 'APP_DIRS': True,120}, {121 'NAME': 'TWO',122 'BACKEND': 'django.template.backends.django.DjangoTemplates',123 'APP_DIRS': True,124}])125@unittest.skipUnless(utils.docutils_is_available, "no docutils installed.")126class AdminDocViewWithMultipleEngines(AdminDocViewTests):127 def test_templatefilter_index(self):128 # Overridden because non-trivial TEMPLATES settings aren't supported129 # but the page shouldn't crash (#24125).130 response = self.client.get(reverse('django-admindocs-filters'))131 self.assertContains(response, '<title>Template filters</title>', html=True)132 def test_templatetag_index(self):133 # Overridden because non-trivial TEMPLATES settings aren't supported134 # but the page shouldn't crash (#24125).135 response = self.client.get(reverse('django-admindocs-tags'))136 self.assertContains(response, '<title>Template tags</title>', html=True)137@unittest.skipUnless(utils.docutils_is_available, "no docutils installed.")138class TestModelDetailView(TestDataMixin, AdminDocsTestCase):139 def setUp(self):140 self.client.force_login(self.superuser)141 with captured_stderr() as self.docutils_stderr:142 self.response = self.client.get(reverse('django-admindocs-models-detail', args=['admin_docs', 'Person']))143 def test_method_excludes(self):144 """145 Methods that begin with strings defined in146 ``django.contrib.admindocs.views.MODEL_METHODS_EXCLUDE``147 shouldn't be displayed in the admin docs.148 """149 self.assertContains(self.response, "<td>get_full_name</td>")150 self.assertNotContains(self.response, "<td>_get_full_name</td>")151 self.assertNotContains(self.response, "<td>add_image</td>")152 self.assertNotContains(self.response, "<td>delete_image</td>")153 self.assertNotContains(self.response, "<td>set_status</td>")154 self.assertNotContains(self.response, "<td>save_changes</td>")155 def test_methods_with_arguments(self):156 """157 Methods that take arguments should also displayed.158 """159 self.assertContains(self.response, "<h3>Methods with arguments</h3>")160 self.assertContains(self.response, "<td>rename_company</td>")161 self.assertContains(self.response, "<td>dummy_function</td>")162 self.assertContains(self.response, "<td>suffix_company_name</td>")163 def test_methods_with_arguments_display_arguments(self):164 """165 Methods with arguments should have their arguments displayed.166 """167 self.assertContains(self.response, "<td>new_name</td>")168 def test_methods_with_arguments_display_arguments_default_value(self):169 """170 Methods with keyword arguments should have their arguments displayed.171 """172 self.assertContains(self.response, "<td>suffix='ltd'</td>")173 def test_methods_with_multiple_arguments_display_arguments(self):174 """175 Methods with multiple arguments should have all their arguments176 displayed, but omitting 'self'.177 """178 self.assertContains(self.response, "<td>baz, rox, *some_args, **some_kwargs</td>")179 def test_method_data_types(self):180 company = Company.objects.create(name="Django")181 person = Person.objects.create(first_name="Human", last_name="User", company=company)182 self.assertEqual(get_return_data_type(person.get_status_count.__name__), 'Integer')183 self.assertEqual(get_return_data_type(person.get_groups_list.__name__), 'List')184 def test_descriptions_render_correctly(self):185 """186 The ``description`` field should render correctly for each field type.187 """188 # help text in fields189 self.assertContains(self.response, "<td>first name - The person's first name</td>")190 self.assertContains(self.response, "<td>last name - The person's last name</td>")191 # method docstrings192 self.assertContains(self.response, "<p>Get the full name of the person</p>")193 link = '<a class="reference external" href="/admindocs/models/%s/">%s</a>'194 markup = '<p>the related %s object</p>'195 company_markup = markup % (link % ("admin_docs.company", "admin_docs.Company"))196 # foreign keys197 self.assertContains(self.response, company_markup)198 # foreign keys with help text199 self.assertContains(self.response, "%s\n - place of work" % company_markup)200 # many to many fields201 self.assertContains(202 self.response,203 "number of related %s objects" % (link % ("admin_docs.group", "admin_docs.Group"))204 )205 self.assertContains(206 self.response,207 "all related %s objects" % (link % ("admin_docs.group", "admin_docs.Group"))208 )209 # "raw" and "include" directives are disabled210 self.assertContains(self.response, '<p>"raw" directive disabled.</p>',)211 self.assertContains(self.response, '.. raw:: html\n :file: admin_docs/evilfile.txt')212 self.assertContains(self.response, '<p>"include" directive disabled.</p>',)213 self.assertContains(self.response, '.. include:: admin_docs/evilfile.txt')214 out = self.docutils_stderr.getvalue()215 self.assertIn('"raw" directive disabled', out)216 self.assertIn('"include" directive disabled', out)217 def test_model_with_many_to_one(self):218 link = '<a class="reference external" href="/admindocs/models/%s/">%s</a>'219 response = self.client.get(220 reverse('django-admindocs-models-detail', args=['admin_docs', 'company'])221 )222 self.assertContains(223 response,224 "number of related %s objects" % (link % ("admin_docs.person", "admin_docs.Person"))225 )226 self.assertContains(227 response,228 "all related %s objects" % (link % ("admin_docs.person", "admin_docs.Person"))229 )230 def test_model_with_no_backward_relations_render_only_relevant_fields(self):231 """232 A model with ``related_name`` of `+` shouldn't show backward233 relationship links.234 """235 response = self.client.get(reverse('django-admindocs-models-detail', args=['admin_docs', 'family']))236 fields = response.context_data.get('fields')237 self.assertEqual(len(fields), 2)238 def test_model_docstring_renders_correctly(self):239 summary = (240 '<h2 class="subhead"><p>Stores information about a person, related to <a class="reference external" '241 'href="/admindocs/models/myapp.company/">myapp.Company</a>.</p></h2>'242 )243 subheading = '<p><strong>Notes</strong></p>'244 body = '<p>Use <tt class="docutils literal">save_changes()</tt> when saving this object.</p>'245 model_body = (246 '<dl class="docutils"><dt><tt class="'247 'docutils literal">company</tt></dt><dd>Field storing <a class="'248 'reference external" href="/admindocs/models/myapp.company/">'249 'myapp.Company</a> where the person works.</dd></dl>'250 )251 self.assertContains(self.response, 'DESCRIPTION')252 self.assertContains(self.response, summary, html=True)253 self.assertContains(self.response, subheading, html=True)254 self.assertContains(self.response, body, html=True)255 self.assertContains(self.response, model_body, html=True)256 def test_model_detail_title(self):257 self.assertContains(self.response, '<h1>admin_docs.Person</h1>', html=True)258 def test_app_not_found(self):259 response = self.client.get(reverse('django-admindocs-models-detail', args=['doesnotexist', 'Person']))260 self.assertEqual(response.context['exception'], "App 'doesnotexist' not found")261 self.assertEqual(response.status_code, 404)262 def test_model_not_found(self):263 response = self.client.get(reverse('django-admindocs-models-detail', args=['admin_docs', 'doesnotexist']))264 self.assertEqual(response.context['exception'], "Model 'doesnotexist' not found in app 'admin_docs'")265 self.assertEqual(response.status_code, 404)266class CustomField(models.Field):267 description = "A custom field type"268class DescriptionLackingField(models.Field):269 pass270class TestFieldType(unittest.TestCase):271 def setUp(self):...
test_templates.py
Source:test_templates.py
...20 request.user = user21 cls.user, cls.request = user, request22 def test_PasswordResetView(self):23 response = PasswordResetView.as_view(success_url='dummy/')(self.request)24 self.assertContains(response, '<title>Password reset</title>')25 self.assertContains(response, '<h1>Password reset</h1>')26 def test_PasswordResetDoneView(self):27 response = PasswordResetDoneView.as_view()(self.request)28 self.assertContains(response, '<title>Password reset sent</title>')29 self.assertContains(response, '<h1>Password reset sent</h1>')30 def test_PasswordResetConfirmView_invalid_token(self):31 # PasswordResetConfirmView invalid token32 client = PasswordResetConfirmClient()33 url = reverse('password_reset_confirm', kwargs={'uidb64': 'Bad', 'token': 'Bad-Token'})34 response = client.get(url)35 self.assertContains(response, '<title>Password reset unsuccessful</title>')36 self.assertContains(response, '<h1>Password reset unsuccessful</h1>')37 def test_PasswordResetConfirmView_valid_token(self):38 # PasswordResetConfirmView valid token39 client = PasswordResetConfirmClient()40 default_token_generator = PasswordResetTokenGenerator()41 token = default_token_generator.make_token(self.user)42 uidb64 = urlsafe_base64_encode(str(self.user.pk).encode()).decode()43 url = reverse('password_reset_confirm', kwargs={'uidb64': uidb64, 'token': token})44 response = client.get(url)45 self.assertContains(response, '<title>Enter new password</title>')46 self.assertContains(response, '<h1>Enter new password</h1>')47 def test_PasswordResetCompleteView(self):48 response = PasswordResetCompleteView.as_view()(self.request)49 self.assertContains(response, '<title>Password reset complete</title>')50 self.assertContains(response, '<h1>Password reset complete</h1>')51 def test_PasswordResetChangeView(self):52 response = PasswordChangeView.as_view(success_url='dummy/')(self.request)53 self.assertContains(response, '<title>Password change</title>')54 self.assertContains(response, '<h1>Password change</h1>')55 def test_PasswordChangeDoneView(self):56 response = PasswordChangeDoneView.as_view()(self.request)57 self.assertContains(response, '<title>Password change successful</title>')...
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!!