我们从Python开源项目中,提取了以下42个代码示例,用于说明如何使用django.test()。
def test_instance_details_unauthorized(self): server = self.servers.first() api.nova.server_get(IsA(http.HttpRequest), server.id)\ .AndRaise(self.exceptions.nova_unauthorized) self.mox.ReplayAll() url = reverse('horizon:project:instances:detail', args=[server.id]) # Avoid the log message in the test # when unauthorized exception will be logged logging.disable(logging.ERROR) res = self.client.get(url) logging.disable(logging.NOTSET) self.assertEqual(302, res.status_code) self.assertEqual(('Location', settings.TESTSERVER + settings.LOGIN_URL + '?' + REDIRECT_FIELD_NAME + '=' + url), res._headers.get('location', None),)
def test_delete_files_or_folders_action_with_mixed_types(self): # add more files/images so we can test the polymorphic queryset with multiple types self.create_file(folder=self.src_folder) self.create_image(folder=self.src_folder) self.create_file(folder=self.src_folder) self.create_image(folder=self.src_folder) self.assertNotEqual(File.objects.count(), 0) self.assertNotEqual(Image.objects.count(), 0) url = reverse('admin:filer-directory_listing', args=(self.folder.id,)) folders = [] for f in File.objects.filter(folder=self.folder): folders.append('file-%d' % (f.id,)) folders.append('folder-%d' % self.sub_folder1.id) response = self.client.post(url, { 'action': 'delete_files_or_folders', 'post': 'yes', helpers.ACTION_CHECKBOX_NAME: folders, }) self.assertEqual(File.objects.filter(folder__in=[self.folder.id, self.sub_folder1.id]).count(), 0)
def test_search_special_characters(self): """ Regression test for https://github.com/divio/django-filer/pull/945. Because of a wrong unquoting function being used, searches with some "_XX" sequences got unquoted as unicode characters. For example, "_ec" gets unquoted as u'ì'. """ url = reverse('admin:filer-directory_listing', kwargs={'folder_id': self.parent.id}) # Create a file with a problematic filename problematic_file = django.core.files.base.ContentFile('some data') filename = u'christopher_eccleston' problematic_file.name = filename self.spam_file = File.objects.create( owner=self.staff_user, original_filename=filename, file=problematic_file, folder=self.parent) # Valid search for the filename, should have one result response = self.client.get(url, {'q': filename}) item_list = response.context['paginated_items'].object_list self.assertEqual(len(item_list), 1)
def test_order_by_two_virtual_fields(self): ca = Category.objects.create(name='foo a', title='test a', title_nl='testje a') cb = Category.objects.create(name='foo b', title='test b', title_nl='testje b') Blog.objects.bulk_create([ Blog(title='a', title_nl='d', category=cb), Blog(title='b', title_nl='c', category=cb), Blog(title='c', title_nl='b', category=cb), Blog(title='z', title_nl='a', category=ca), Blog(title='y', title_nl='b', category=ca), Blog(title='x', title_nl='c', category=ca) ]) qs = Blog.objects.filter(category__title_nl__contains='test').order_by( '-category__title_nl', '-title_nl' ) self.assertEquals([m.title for m in qs], 'a b c x y z'.split())
def test_reverse(self): """Test all code paths through reverse_fallback and reverse_any""" self.assertEqual( reverse_fallback('test', reverse, 'not-exists'), 'test', ) self.assertEqual( reverse_fallback('test', reverse, 'admin:index'), '/admin/', ) self.assertEqual( reverse_any(( 'not-exists', 'admin:index', )), '/admin/', ) with six.assertRaisesRegex( self, NoReverseMatch, "Reverse for any of 'not-exists-1', 'not-exists-2' with" " arguments '\[\]' and keyword arguments '{}' not found." ): reverse_any(('not-exists-1', 'not-exists-2'))
def setUpClass(cls): from django.test.utils import setup_test_environment from django.core.management import call_command from django.conf import settings settings.configure( INSTALLED_APPS=[ 'django.contrib.auth', 'django.contrib.contenttypes', 'lifter.contrib.django', ], DATABASES={ 'default': {'NAME': ':memory:', 'ENGINE': 'django.db.backends.sqlite3'} }, ) django.setup() setup_test_environment() super(DjangoTestCase, cls).setUpClass() call_command('migrate')
def test_has_perm(self): user = self.UserModel._default_manager.get(pk=self.user.pk) self.assertEqual(user.has_perm('auth.test'), False) user.is_staff = True user.save() self.assertEqual(user.has_perm('auth.test'), False) user.is_superuser = True user.save() self.assertEqual(user.has_perm('auth.test'), True) user.is_staff = True user.is_superuser = True user.is_active = False user.save() self.assertEqual(user.has_perm('auth.test'), False)
def test_read(self): value = b'abcd' * 2 ** 20 result = cache.set(b'test-key', value) self.assertTrue(result) with cache.read(b'test-key') as reader: self.assertEqual(reader.read(), value) try: with cache.read(b'dne') as reader: error = False except KeyError: error = True self.assertTrue(error)
def create_test_user(self): User = get_user_model() test_users = User.objects.filter( username='test' ) if test_users.count() > 0: self.test_user = test_users[0] else: self.test_user = User.objects.create_user( username='test', email='' ) self.test_user.set_password('test') self.test_user.save() return ('test', 'test') # Admin user is the overlord for the system. #
def test_user_factory(self): R = Roles.objects.create(rank=6) P = People.objects.create(firstname='asdf') U = Users.objects.create(username='adsf', role=R, person=P, is_active=1) D = VariantsDb.objects.get(filename=settings.DB_TEST) u = user_factory(U) self.assertIsInstance(u, User) self.assertEqual(u.username, U.username) self.assertGreaterEqual(len(u.databases), 0) # Add access to test db - it should reflect in User.databases DbAccess.objects.create(user=U, variants_db=D, is_active=1) u = user_factory(U) self.assertGreaterEqual(len(u.databases), 1) # Make the db inactive - it should get ignored again D.is_active = 0 D.save() u = user_factory(U) self.assertGreaterEqual(len(u.databases), 0)
def _assert_datetime_not_equal(self, datetime_1, datetime_2): """ Assert two datetime.datetime values are NOT equal. This method does NOT compare any division of time smaller than a minute, i.e. seconds and milliseconds, if present, are not considered in the equality test. This could also be implemented with datetime.replace() to zero out seconds and microseconds. Args: datetime_1 (datetime.datetime): The first (left) value to compare. datetime_2 (datetime.datetime): The second (right) value to compare. """ required_datetime_attributes = ['date', 'hour', 'minute'] datetime_1_has_interface = set(dir(datetime_1)).issuperset(required_datetime_attributes) datetime_2_has_interface = set(dir(datetime_2)).issuperset(required_datetime_attributes) if datetime_1_has_interface and datetime_2_has_interface: self.assertNotEqual(datetime_1.date(), datetime_2.date()) self.assertNotEqual(datetime_1.hour, datetime_2.hour) self.assertNotEqual(datetime_1.minute, datetime_2.minute) else: self.assertNotEqual(datetime_1, datetime_2)
def test_update(self): """ Test that an UPDATE statement works correctly in specific cases. Test that the timestamp field value is unchanged when only auto_now_add is enabled and test that the timestamp field is automatically updated when only auto_now_update is enabled. Unfortunately, this test is impossible to isolate from any side effects of a broken INSERT operation in the timestamp field. """ for alias in test_utils.get_db_aliases(): engine = django.db.connections[alias].settings_dict['ENGINE'] with self.subTest(backend=engine): self._test_update_no_auto(alias) self._test_update_auto(alias)
def test_proxy_get_real_instance_class(self): """ The call to ``get_real_instance()`` also checks whether the returned model is of the correct type. This unit test guards that this check is working properly. For instance, proxy child models need to be handled separately. """ name = "Item1" nonproxychild = NonProxyChild.objects.create(name=name) pb = ProxyBase.objects.get(id=1) self.assertEqual(pb.get_real_instance_class(), NonProxyChild) self.assertEqual(pb.get_real_instance(), nonproxychild) self.assertEqual(pb.name, name) pbm = ProxyChild.objects.get(id=1) self.assertEqual(pbm.get_real_instance_class(), NonProxyChild) self.assertEqual(pbm.get_real_instance(), nonproxychild) self.assertEqual(pbm.name, name)
def test_parent_link_and_related_name(self): t = TestParentLinkAndRelatedName(field1="TestParentLinkAndRelatedName") t.save() p = ModelShow1_plain.objects.get(field1="TestParentLinkAndRelatedName") # check that p is equal to the self.assertIsInstance(p, TestParentLinkAndRelatedName) self.assertEqual(p, t) # check that the accessors to parent and sublass work correctly and return the right object p = ModelShow1_plain.objects.non_polymorphic().get(field1="TestParentLinkAndRelatedName") self.assertNotEqual(p, t) # p should be Plain1 and t TestParentLinkAndRelatedName, so not equal self.assertEqual(p, t.superclass) self.assertEqual(p.related_name_subclass, t) # test that we can delete the object t.delete()
def _get_jinja2_env(self): import jinja2 import jinja2.ext from compressor.offline.jinja2 import url_for, SpacelessExtension from compressor.contrib.jinja2ext import CompressorExtension # Extensions needed for the test cases only. extensions = [ CompressorExtension, SpacelessExtension, jinja2.ext.with_, jinja2.ext.do, ] loader = self._get_jinja2_loader() env = jinja2.Environment(extensions=extensions, loader=loader) env.globals['url_for'] = url_for return env
def setup_django(): """Provide a test database and django configuration""" from yawn.worker.models import Queue # these are positional arguments, written out for clarity verbosity = 1 interactive = False # whether to ask before deleting old_config = runner.setup_databases(verbosity, interactive) # create the default queue outside the transaction Queue.get_default_queue() yield for connection, old_name, destroy in old_config: connection.creation.destroy_test_db(old_name)
def test_post(self): # Build a fake file fake_file = ContentFile(b("A boring example document")) fake_file.name = 'test.txt' # Submit post_data = { 'title': "Test document", 'file': fake_file, } response = self.client.post(reverse('wagtaildocs:add'), post_data) # User should be redirected back to the index self.assertRedirects(response, reverse('wagtaildocs:index')) # Document should be created, and be placed in the root collection self.assertTrue(models.Document.objects.filter(title="Test document").exists()) root_collection = Collection.get_first_root_node() self.assertEqual( models.Document.objects.get(title="Test document").collection, root_collection )
def test_post(self): # Build a fake file fake_file = ContentFile(b("A boring example document")) fake_file.name = 'test.txt' # Submit post_data = { 'title': "Test document", 'file': fake_file, } response = self.client.post(reverse('wagtaildocs:add'), post_data) # User should be redirected back to the index self.assertRedirects(response, reverse('wagtaildocs:index')) # Document should be created in the 'evil plans' collection, # despite there being no collection field in the form, because that's the # only one the user has access to self.assertTrue(models.Document.objects.filter(title="Test document").exists()) self.assertEqual( models.Document.objects.get(title="Test document").collection, self.evil_plans_collection )
def test_post(self): # Build a fake file fake_file = ContentFile(b("A boring example document")) fake_file.name = 'test.txt' # Submit title change post_data = { 'title': "Test document changed!", 'file': fake_file, } response = self.client.post(reverse('wagtaildocs:edit', args=(self.document.id,)), post_data) # User should be redirected back to the index self.assertRedirects(response, reverse('wagtaildocs:index')) # Document title should be changed self.assertEqual(models.Document.objects.get(id=self.document.id).title, "Test document changed!")
def test_post(self): # Build a fake file fake_file = ContentFile(b("A boring example document")) fake_file.name = 'test.txt' # Submit post_data = { 'title': "Test document", 'file': fake_file, } response = self.client.post(reverse('wagtaildocs:chooser_upload'), post_data) # Check that the response is a javascript file saying the document was chosen self.assertTemplateUsed(response, 'wagtaildocs/chooser/document_chosen.js') self.assertContains(response, "modal.respond('documentChosen'") # Document should be created self.assertTrue(models.Document.objects.filter(title="Test document").exists())
def add_document(self, **params): # Build a fake file fake_file = ContentFile(b("A boring example document")) fake_file.name = 'test.txt' # Submit post_data = { 'title': "Test document", 'file': fake_file, } post_data.update(params) response = self.client.post(reverse('wagtaildocs:add'), post_data) # User should be redirected back to the index self.assertRedirects(response, reverse('wagtaildocs:index')) # Document should be created doc = models.Document.objects.filter(title=post_data['title']) self.assertTrue(doc.exists()) return doc.first()
def test_level(self): """Test if the level is correct when buying baracks""" #Have no baracks self.UnitTest4.addBarrack(0) self.assertEqual(self.UnitTest4.level, 0) #have negative baracks, shouldnt ever happen but test it anyway. self.UnitTest2.addBarrack(0) self.assertEqual(self.UnitTest2.level, 0) #have -3 baracks and add 4 but don't have enough money (-900) self.UnitTest2.addBarrack(4) self.assertEqual(self.UnitTest2.level, 0) #have -3 baracks and add 4 with enough money (900) self.UnitTest6.addBarrack(4) self.assertEqual(self.UnitTest6.level, 1) #have 1 barack self.UnitTest5.addBarrack(0) self.assertEqual(self.UnitTest5.level, 1) #Player is already level 4 and levels up by getting 1 barack self.UnitTest7.addBarrack(1) self.assertEqual(self.UnitTest7.level, 5)
def test_home_status(self): """ Home page returns HTTP 200 """ # create GET request request = self.factory.get('home') # simulate logged-out user request.user = AnonymousUser() # test the view response = views.home_view(request) # check that the response is 200 OK self.assertEqual(response.status_code, 200)
def test_home_content(self): """ Home page returns correct content """ # create GET request request = self.factory.get('home') # simulate logged-out user request.user = AnonymousUser() # test the view response = views.home_view(request) # check that the correct content is displayed self.assertContains(response, "Streamlined Roleplaying", status_code=200) self.assertContains(response, "Login", status_code=200) self.assertContains(response, "Sign up", status_code=200) self.assertContains(response, "Features", status_code=200) self.assertContains(response, "Users", status_code=200) self.assertContains(response, "Campaigns", status_code=200) self.assertContains(response, "Creatures", status_code=200) self.assertContains(response, "Donate", status_code=200) self.assertContains(response, "Copyright", status_code=200)
def setUpTestData(cls): cls.header = settings.SHIBAUTH_REMOTE_USER_HEADER cls.headers = settings.SAMPLE_HEADERS # Usernames to be passed in REMOTE_USER for the test_known_user test case. cls.known_user = 'knownuser' cls.known_user2 = 'knownuser2' reload(middleware)
def test_valid_string_list_model_form_save(self): form_class = modelform_factory(StringListModel, fields=('values',)) form = form_class({'values': "This,is,a,test"}) self.assertTrue(form.is_valid()) self.assertEqual( form.cleaned_data['values'], ['This', 'is', 'a', 'test'] ) obj = form.save() self.assertEqual(obj.values, ['This', 'is', 'a', 'test'])
def fake_conn_request(self): # print a stacktrace to illustrate where the unmocked API call # is being made from traceback.print_stack() # forcing a test failure for missing mock self.missing_mocks = True
def tearDown(self): HTTPConnection.connect = self._real_conn_request context_processors.openstack = self._real_context_processor utils.get_user = self._real_get_user mock.patch.stopall() super(TestCase, self).tearDown() # cause a test failure if an unmocked API call was attempted if self.missing_mocks: raise AssertionError("An unmocked API call was made.")
def test_filer_remember_last_opened_directory(self): folder = Folder.objects.create(name='remember me please') get_last_folder = lambda: self.client.get(reverse('admin:filer-directory_listing-last'), follow=True) self.client.get(reverse('admin:filer-directory_listing', kwargs={'folder_id': folder.id})) self.assertEqual(int(self.client.session['filer_last_folder_id']), folder.id) self.assertEqual(get_last_folder().context['folder'], folder) # let's test fallback folder.delete() self.assertTrue(isinstance(get_last_folder().context['folder'], FolderRoot))
def test_copy_files_and_folders_action(self): # TODO: Test recursive (files and folders tree) copy self.assertEqual(self.src_folder.files.count(), 1) self.assertEqual(self.dst_folder.files.count(), 0) self.assertEqual(self.image_obj.original_filename, 'test_file.jpg') url = reverse('admin:filer-directory_listing', kwargs={ 'folder_id': self.src_folder.id, }) response = self.client.post(url, { 'action': 'copy_files_and_folders', 'post': 'yes', 'suffix': 'test', 'destination': self.dst_folder.id, helpers.ACTION_CHECKBOX_NAME: 'file-%d' % (self.image_obj.id,), }) self.assertEqual(response.status_code, 302) # check if copying to the same folder gives 403 response = self.client.post(url, { 'action': 'copy_files_and_folders', 'post': 'yes', 'suffix': 'test', 'destination': self.src_folder.id, helpers.ACTION_CHECKBOX_NAME: 'file-%d' % (self.image_obj.id,), }) self.assertEqual(response.status_code, 403) self.assertEqual(self.src_folder.files.count(), 1) self.assertEqual(self.dst_folder.files.count(), 1) self.assertEqual(self.src_folder.files[0].id, self.image_obj.id) dst_image_obj = self.dst_folder.files[0] self.assertEqual(dst_image_obj.original_filename, 'test_filetest.jpg')
def test_render_add_view(self): """ Really stupid and simple test to see if the add Permission view can be rendered """ response = self.client.get(reverse('admin:filer_folderpermission_add')) self.assertEqual(response.status_code, 200)
def test_order_by_lower(self): from django.db.models.functions import Lower c = Category.objects.create(name='test') Blog.objects.create(title='A', title_nl='c', category=c) Blog.objects.create(title='a', title_nl='b', category=c) filtered = Blog.objects.filter(category=c) # order by title should result in aA because it is case sensitive. qs = filtered.order_by('title', 'title_nl') self.assertEquals(key(qs, 'title'), ['a', 'A']) # order by Lower('title') should result in Aa because lower('A') == lower('A') # so the title_nl field should determine the sorting qs = filtered.order_by(Lower('title'), 'title_nl') self.assertEquals(key(qs, 'title'), ['a', 'A']) # applying lower to title_nl should not matter since it is not the same letter qs = filtered.order_by(Lower('title_nl')) self.assertEquals(key(qs, 'title'), ['a', 'A']) # should be the same as previous with override('nl'): qs = filtered.order_by(Lower('title_i18n')) self.assertEquals(key(qs, 'title'), ['a', 'A'])
def test_protected_media(self): m = SomeModel() m.protected_file = SimpleUploadedFile( "protected_file.txt", "A test file" ) m.protected_image = SimpleUploadedFile( "protected_image.png", "A test image" ) m.public_file = SimpleUploadedFile( "public_file.txt", "A test file" ) m.public_image = SimpleUploadedFile( "public_image.png", "A test image" ) self.assertEqual(m.protected_file.name, "protected_file.txt") self.assertEqual(m.protected_file.url, "/myprotectedmedia/protected_file.txt") self.assertEqual(m.protected_image.name, "protected_image.png") self.assertEqual(m.protected_image.url, "/myprotectedmedia/protected_image.png") self.assertEqual(m.public_file.name, "public_file.txt") self.assertEqual(m.public_file.url, "/media/public_file.txt") self.assertEqual(m.public_image.name, "public_image.png") self.assertEqual(m.public_image.url, "/media/public_image.png")
def setUp(self): # Every view test needs a client. self.client = Client()
def test_check_custom_user_model(self): # Django doesn't re-register admins when using `override_settings`, # so we have to do it manually in this test case. admin.site.register(get_user_model(), HijackUserAdmin) warnings = checks.check_custom_user_model(HijackAdminConfig) self.assertFalse(warnings) admin.site.unregister(get_user_model())
def test_check_custom_user_model_default_admin(self): # Django doesn't re-register admins when using `override_settings`, # so we have to do it manually in this test case. admin.site.register(get_user_model(), UserAdmin) warnings = checks.check_custom_user_model(HijackAdminConfig) expected_warnings = [ Warning( 'django-hijack-admin does not work out the box with a custom user model.', hint='Please mix HijackUserAdminMixin into your custom UserAdmin.', obj=settings.AUTH_USER_MODEL, id='hijack_admin.W001', ) ] self.assertEqual(warnings, expected_warnings) admin.site.unregister(get_user_model())
def test_add_empty_page(self): """Add a page without content, test path generation etc""" client = self.login() response = client.post( '/admin/testapp/page/add/', merge_dicts( { 'title': 'Home EN', 'slug': 'home-en', 'path': '/en/', 'static_path': 1, 'language_code': 'en', 'application': '', 'is_active': 1, 'menu': 'main', 'template_key': 'standard', }, zero_management_form_data('testapp_richtext_set'), zero_management_form_data('testapp_image_set'), zero_management_form_data('testapp_snippet_set'), zero_management_form_data('testapp_external_set'), zero_management_form_data('testapp_html_set'), ), ) self.assertRedirects( response, '/admin/testapp/page/', ) page = Page.objects.get() self.assertEqual(page.slug, 'home-en') self.assertEqual(page.path, '/en/') # static_path! response = client.get(page.get_absolute_url()) self.assertContains( response, '<h1>Home EN</h1>', 1, )
def test_positional(self): @positional(2) def test(a, b, c): pass with self.assertRaises(TypeError): test(1, 2, 3) test(1, 2, c=3)
def setUp(self): self.url = reverse("django_admin_shell:shell") username = "test" password = "test" self.user = get_user_model()(username=username) self.user.set_password(password) self.user.save() self.client_auth = Client() self.client_auth.login(username=username, password=password)
def test_single_code(self): """ Run simple code in pure python """ code = "1 + 1" result = run_code(code) assert result["code"] == code assert result["status"] == "success" assert result["out"] == "" code = "print(1 + 1)" result = run_code(code) assert result["code"] == code assert result["status"] == "success" assert result["out"] == "2\n" # !!! Warning # Not use: """ because indention will be incorect code = "class Test(object):\n" code += " def pow(self, a, b):\n" code += " return a**b\n" code += "test = Test()\n" code += "ret = test.pow(2, 10)\n" code += "print(ret)" result = run_code(code) assert result["code"] == code assert result["status"] == "success" assert result["out"] == "1024\n"
def test_interact_with_env(self): """ Run code having access to something from environ, settings etc. Heck if code runing in django environ """ code = "from django.conf import settings\n" code += "print(settings.DEBUG)" # Default in test DEBUG is False result = run_code(code) assert result["code"] == code assert result["status"] == "success" assert result["out"] == "False\n" with self.settings(DEBUG=True): result = run_code(code) assert result["code"] == code assert result["status"] == "success" assert result["out"] == "True\n" code = "from django.conf import settings\n" code += "print(settings.SECRET_KEY)" result = run_code(code) assert result["code"] == code assert result["status"] == "success" assert result["out"] == "{0}\n".format("x" * 55) code = "import django\n" code += "print(django.VERSION)" result = run_code(code) assert result["code"] == code assert result["status"] == "success" assert result["out"] == "{0}\n".format(str(django.VERSION))