我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.test.TestCase()。
def test_default_alpha(self): default_alpha = LanguageList.ALL+"-alpha" lg_names = ["Ccc", "Bbb", "Aaa"] self.setup_language_list(lg_names) self.db[Language].delete() alpha_list = LanguageList.objects.get(name=default_alpha) alpha_list_names = [ l.ascii_name for l in alpha_list.languages.all().order_by("languagelistorder")] self.assertNotEqual(lg_names, sorted(lg_names)) self.assertEqual(alpha_list_names, sorted(lg_names)) # class NexusExportFormTests(TestCase): # # def setUp(self): # self.form = ChooseNexusOutputForm() # # def test_defaults(self): # self.assertTrue(self.form.is_valid())
def setUp(self): assert self.migrate_from and self.migrate_to, \ "TestCase '{}' must define migrate_from and migrate_to properties".format(type(self).__name__) migrate_from = [(self.app, self.migrate_from)] migrate_to = [(self.app, self.migrate_to)] executor = MigrationExecutor(connection) old_apps = executor.loader.project_state(migrate_from).apps # Reverse to the original migration executor.migrate(migrate_from) self.setUpBeforeMigration(old_apps) # Run the migration to test executor = MigrationExecutor(connection) executor.loader.build_graph() # reload. executor.migrate(migrate_to) self.apps = executor.loader.project_state(migrate_to).apps
def test_values_slicing(self): reset_search_queries() self.assertEqual(len(connections['elasticsearch'].queries), 0) # TODO: this would be a good candidate for refactoring into a TestCase subclass shared across backends # The values will come back as strings because Hasytack doesn't assume PKs are integers. # We'll prepare this set once since we're going to query the same results in multiple ways: expected_pks = [str(i) for i in [3, 2, 4, 5, 6, 7, 8, 9, 10, 11]] results = self.sqs.all().order_by('pub_date').values('pk') self.assertListEqual([i['pk'] for i in results[1:11]], expected_pks) results = self.sqs.all().order_by('pub_date').values_list('pk') self.assertListEqual([i[0] for i in results[1:11]], expected_pks) results = self.sqs.all().order_by('pub_date').values_list('pk', flat=True) self.assertListEqual(results[1:11], expected_pks) self.assertEqual(len(connections['elasticsearch'].queries), 3)
def test_values_slicing(self): reset_search_queries() self.assertEqual(len(connections['default'].queries), 0) # TODO: this would be a good candidate for refactoring into a TestCase subclass shared across backends # The values will come back as strings because Hasytack doesn't assume PKs are integers. # We'll prepare this set once since we're going to query the same results in multiple ways: expected_pks = [str(item) for item in [3, 2, 4, 5, 6, 7, 8, 9, 10, 11]] results = self.sqs.all().order_by('pub_date').values('pk') self.assertListEqual([item['pk'] for item in results[1:11]], expected_pks) results = self.sqs.all().order_by('pub_date').values_list('pk') self.assertListEqual([item[0] for item in results[1:11]], expected_pks) results = self.sqs.all().order_by('pub_date').values_list('pk', flat=True) self.assertListEqual(results[1:11], expected_pks) self.assertEqual(len(connections['default'].queries), 3)
def test_request_get(): class TheCase(APITestCase, TestCase): view_class = APITestView user = User(username='user') case = TheCase() response = case.request(user=user, get_data={'key': 'value'}) assert case._request.user == user assert case._request.method == 'GET' assert case._request.GET.get('key') == 'value' assert response.status_code == 200 assert isinstance(response.content, dict) assert response.content == {"some": "json"} assert response.location is None assert 'content-type' in response.headers assert response.headers['content-type'][1] == 'application/json' assert len(response.messages) == 0
def test_request_post(): class TheCase(APITestCase, TestCase): view_class = APITestView post_data = {'some': 'json'} user = User(username='user') case = TheCase() response = case.request(user=user, method='POST') assert case._request.user == user assert case._request.method == 'POST' assert response.status_code == 200 assert isinstance(response.content, dict) assert response.content == {"some": "json"} assert response.location is None assert 'content-type' in response.headers assert response.headers['content-type'][1] == 'application/json' assert len(response.messages) == 0
def test_request_post_multipart(): class TheCase(APITestCase, TestCase): view_class = APITestView post_data = {'some': 'json'} user = User(username='user') case = TheCase() response = case.request(user=user, method='POST', content_type='multipart/form-data') assert case._request.user == user assert case._request.method == 'POST' assert response.status_code == 200 assert isinstance(response.content, dict) assert response.content == {"some": ["json"]} assert response.location is None assert 'content-type' in response.headers assert response.headers['content-type'][1] == 'application/json' assert len(response.messages) == 0
def test_request_viewset_actions(): class TheCase(APITestCase, TestCase): view_class = APIViewSetTestView viewset_actions = {'get': 'list'} user = User(username='user') case = TheCase() response = case.request(user=user) assert case._request.user == user assert case._request.method == 'GET' assert response.status_code == 200 assert isinstance(response.content, dict) assert response.content == {"some": "json"} assert response.location is None assert 'content-type' in response.headers assert response.headers['content-type'][1] == 'application/json' assert len(response.messages) == 0
def test_request_get(): class TheCase(ViewTestCase, TestCase): view_class = views.GenericView request_meta = {'HTTP_REFERER': 'http://example.com'} user = User(username='user') case = TheCase() response = case.request(user=user) assert case._request.user == user assert case._request.method == 'GET' assert case._request.META['SERVER_NAME'] == 'testserver' assert case._request.META['SERVER_PORT'] == '80' assert case._request.META['HTTP_REFERER'] == 'http://example.com' assert response.status_code == 200 assert response.content == '<h1>Test content<h1>' assert response.location is None assert 'content-type' in response.headers assert len(response.messages) == 1 assert 'Hello world.' in response.messages
def test_request_get_template_response(): class TheCase(ViewTestCase, TestCase): view_class = views.GenericTemplateView user = User(username='user') case = TheCase() response = case.request(user=user) assert case._request.user == user assert case._request.method == 'GET' assert response.status_code == 200 assert response.content == '<h1>test-id</h1>\n' assert response.location is None assert 'content-type' in response.headers assert len(response.messages) == 0
def test_request_redirect_response(): class TheCase(ViewTestCase, TestCase): view_class = views.GenericRedirectView user = User(username='user') case = TheCase() response = case.request(user=user) assert case._request.user == user assert case._request.method == 'GET' assert response.status_code == 302 assert response.content is '' assert response.location == '/redirect/' assert 'content-type' in response.headers assert len(response.messages) == 0
def test_request_post(): class TheCase(ViewTestCase, TestCase): view_class = views.GenericView post_data = {'data': 'abc def :/?#[]@!$&\'()*+,;='} user = User(username='user') case = TheCase() response = case.request(user=user, method='POST') assert case._request.user == user assert case._request.method == 'POST' assert response.status_code == 200 assert response.content == '<h1>data: abc def :/?#[]@!$&\'()*+,;=<h1>' assert response.location is None assert 'content-type' in response.headers assert len(response.messages) == 0
def test_request_post_with_number(): class TheCase(ViewTestCase, TestCase): view_class = views.GenericView post_data = {'data': 1} user = User(username='user') case = TheCase() response = case.request(user=user, method='POST') assert case._request.user == user assert case._request.method == 'POST' assert response.status_code == 200 assert response.content == '<h1>data: 1<h1>' assert response.location is None assert 'content-type' in response.headers assert len(response.messages) == 0
def test_request_post_with_bool(): class TheCase(ViewTestCase, TestCase): view_class = views.GenericView post_data = {'data': True} user = User(username='user') case = TheCase() response = case.request(user=user, method='POST') assert case._request.user == user assert case._request.method == 'POST' assert response.status_code == 200 assert response.content == '<h1>data: True<h1>' assert response.location is None assert 'content-type' in response.headers assert len(response.messages) == 0
def test_request_get_with_session_data(): class TheCase(ViewTestCase, TestCase): view_class = views.GenericView case = TheCase() session_data = {'s_data': 'Session Data'} response = case.request(method='GET', session_data=session_data) assert case._request.method == 'GET' assert case._request.session['s_data'] == 'Session Data' assert response.status_code == 200 assert response.content == '<h1>Test content<h1><p>Session Data</p>' assert response.location is None assert 'content-type' in response.headers assert len(response.messages) == 1 assert 'Hello world.' in response.messages
def test_values_slicing(self): reset_search_queries() self.assertEqual(len(connections['default'].queries), 0) # TODO: this would be a good candidate for refactoring into a TestCase subclass shared across backends # The values will come back as strings because Hasytack doesn't assume PKs are integers. # We'll prepare this set once since we're going to query the same results in multiple ways: expected_pks = [str(i) for i in [3, 2, 4, 5, 6, 7, 8, 9, 10, 11]] results = self.sqs.all().order_by('pub_date').values('pk') self.assertListEqual([i['pk'] for i in results[1:11]], expected_pks) results = self.sqs.all().order_by('pub_date').values_list('pk') self.assertListEqual([i[0] for i in results[1:11]], expected_pks) results = self.sqs.all().order_by('pub_date').values_list('pk', flat=True) self.assertListEqual(results[1:11], expected_pks) self.assertEqual(len(connections['default'].queries), 3)
def test_scrape_parliament_members(self): members = scraper.parliament_members.search_members() filepath = './data/tmp/members.csv' try: scraper.parliament_members.create_members_csv(members, filepath) finally: os.remove(filepath) # class TestParliamentMembersParlementComScraper(TestCase): # # def test_scrape(self): # members_json = scraper.parliament_members.search_members_check_json() # # with open('./data/secret/parliament_members_check.json', 'w') as fileout: # # fileout.write(str(members_json)) # members = json.loads(members_json) # for member in members: # self.assertNotEqual(member['name'], '') # self.assertNotEqual(member['initials'], '') # self.assertNotEqual(member['date_ranges'], [])
def test_update_default_tester_via_email(self): # test for https://github.com/kiwitcms/Kiwi/issues/85 url = reverse('ajax-update_cases_default_tester') response = self.client.post(url, { 'from_plan': self.plan.pk, 'case': [case.pk for case in TestCase.objects.filter(plan=self.plan)], 'target_field': 'default_tester', 'new_value': self.tester.email }) self.assertEqual(http.client.OK, response.status_code) result = json.loads(str(response.content, encoding=settings.DEFAULT_CHARSET)) self.assertEqual(result['rc'], 0) self.assertEqual(result['response'], 'ok') self._assert_default_tester_is(self.tester)
def test_update_case_priority(self): self.client.login(username=self.tester.username, password='password') response = self.client.post( self.case_update_url, { 'target_field': 'priority', 'from_plan': self.plan.pk, 'case': [self.case_1.pk, self.case_3.pk], 'new_value': Priority.objects.get(value='P3').pk, }) self.assertJSONEqual( str(response.content, encoding=settings.DEFAULT_CHARSET), {'rc': 0, 'response': 'ok'}) for pk in (self.case_1.pk, self.case_3.pk): self.assertEqual('P3', TestCase.objects.get(pk=pk).priority.value)
def test_update_cases_category(self): self.client.login(username=self.tester.username, password='password') post_data = { 'from_plan': self.plan.pk, 'product': self.product.pk, 'case': [self.case_1.pk, self.case_3.pk], 'a': 'update', 'o_category': self.case_cat_full_auto.pk, } response = self.client.post(self.case_category_url, post_data) self.assertJSONEqual( str(response.content, encoding=settings.DEFAULT_CHARSET), {'rc': 0, 'response': 'ok', 'errors_list': []}) for pk in (self.case_1.pk, self.case_3.pk): case = TestCase.objects.get(pk=pk) self.assertEqual(self.case_cat_full_auto, case.category)
def test_edit_a_case(self): self.login_tester() edit_data = self.edit_data.copy() new_summary = 'Edited: {0}'.format(self.case_1.summary) edit_data['summary'] = new_summary response = self.client.post(self.case_edit_url, edit_data) redirect_url = '{0}?from_plan={1}'.format( reverse('testcases-get', args=[self.case_1.pk]), self.plan.pk, ) self.assertRedirects(response, redirect_url) edited_case = TestCase.objects.get(pk=self.case_1.pk) self.assertEqual(new_summary, edited_case.summary)
def test_get_m2m_fields(self): fields = list(self.plan_serializer._get_m2m_fields()) fields.sort() expected_fields = list(MockTestPlanSerializer.m2m_fields) expected_fields.sort() self.assertEqual(expected_fields, fields) fields = list(self.case_serializer._get_m2m_fields()) fields.sort() expected_fields = [field.name for field in TestCase._meta.many_to_many] expected_fields.sort() self.assertEqual(expected_fields, fields) fields = self.product_serializer._get_m2m_fields() expected_fields = tuple(field.name for field in Product._meta.many_to_many) self.assertEqual(fields, ()) self.assertEqual(expected_fields, fields)
def test_runner_include_queries(self): class Test(TestCase): def test_foo(self): self.client.get('/url-1') self.test_runner.run_tests( None, TestLoader().loadTestsFromTestCase(testCaseClass=Test) ) # Assert it ran one test self.assertEqual(len(RequestQueryCountManager.queries.queries_by_testcase), 1) test_foo_id = self.get_id(Test, 'test_foo') self.assertIn(test_foo_id, RequestQueryCountManager.queries.queries_by_testcase) self.assertEqual( RequestQueryCountManager.queries.queries_by_testcase[test_foo_id].total, 1 )
def test_excluded_test(self): class Test(TestCase): @exclude_query_count() def test_foo(self): self.client.get('/url-1') def test_bar(self): self.client.get('/url-1') self.test_runner.run_suite( TestLoader().loadTestsFromTestCase(testCaseClass=Test) ) # Assert test_foo has excluded queries self.assertEqual( RequestQueryCountManager.queries.queries_by_testcase[ self.get_id(Test, 'test_foo')].total, 0 ) # Assert test_bar has some queries self.assertEqual( RequestQueryCountManager.queries.queries_by_testcase[ self.get_id(Test, 'test_bar')].total, 1 )
def test_excluded_class(self): @exclude_query_count() class Test(TestCase): def test_foo(self): self.client.get('path-1') def test_bar(self): self.client.get('path-1') self.test_runner.run_suite( TestLoader().loadTestsFromTestCase(testCaseClass=Test) ) # Assert test_foo has excluded queries self.assertEqual( RequestQueryCountManager.queries.queries_by_testcase[ self.get_id(Test, 'test_foo')].total, 0 ) self.assertEqual( RequestQueryCountManager.queries.queries_by_testcase[ self.get_id(Test, 'test_bar')].total, 0 )
def test_nested_class_method_exclude(self): @exclude_query_count(path='url-1') class Test(TestCase): @exclude_query_count(method='post') def test_foo(self): self.client.get('/url-1') self.client.post('/url-2') self.client.put('/url-3') self.test_runner.run_suite( TestLoader().loadTestsFromTestCase(testCaseClass=Test) ) self.assertEqual( RequestQueryCountManager.queries.queries_by_testcase[ self.get_id(Test, 'test_foo')].total, 1 )
def test_custom_setup_teardown(self): class Test(TestCase): def setUp(self): pass def tearDown(self): pass def test_foo(self): self.client.get('/url-1') self.test_runner.run_suite( TestLoader().loadTestsFromTestCase(testCaseClass=Test) ) self.assertIn( self.get_id(Test, 'test_foo'), RequestQueryCountManager.queries.queries_by_testcase ) self.assertEqual( RequestQueryCountManager.queries.queries_by_testcase[ self.get_id(Test, 'test_foo')].total, 1 )
def setUp(self): super(TestCase, self).setUp() self.mox = mox.Mox() self._setup_test_data() self._setup_factory() self._setup_user() self._setup_request() middleware.HorizonMiddleware().process_request(self.request) AuthenticationMiddleware().process_request(self.request) os.environ["HORIZON_TEST_RUN"] = "True"
def tearDown(self): super(TestCase, self).tearDown() self.mox.UnsetStubs() self.mox.VerifyAll() del os.environ["HORIZON_TEST_RUN"]
def partition_suite_by_case(suite): """ Partitions a test suite by test case, preserving the order of tests. """ groups = [] suite_class = type(suite) for test_type, test_group in itertools.groupby(suite, type): if issubclass(test_type, unittest.TestCase): groups.append(suite_class(test_group)) else: for item in test_group: groups.extend(partition_suite_by_case(item)) return groups
def django_test_case(): return TestCase()
def test_set_defaults_calls_get_models(self, apps_mock, get_class_mock): # Patched modules don't get passed into the TestCase setUp method setUp(self, apps_mock, get_class_mock) base = {} set_all_class_defaults(base) apps_mock.get_models.assert_called_once_with()
def test_set_defaults_calls_get_class(self, apps_mock, get_class_mock): # Patched modules don't get passed into the TestCase setUp method setUp(self, apps_mock, get_class_mock) base = {} set_all_class_defaults(base) get_class_mock.assert_called_once_with(self.DjangoModelMock, base)
def test_field_has_no_default(self, apps_mock, get_class_mock): # Patched modules don't get passed into the TestCase setUp method setUp(self, apps_mock, get_class_mock) base = {} field_mock = MagicMock() self.DjangoModelMock._meta.fields = [field_mock] has_default_mock = Mock(return_value=False) field_mock.attach_mock(has_default_mock, 'has_default') set_all_class_defaults(base) has_default_mock.assert_called_once_with()
def test_field_has_default_no_column(self, ColumnDefaultMock, apps_mock, get_class_mock): # Patched modules don't get passed into the TestCase setUp method setUp(self, apps_mock, get_class_mock) baseclass = MagicMock() baseclass.attach_mock(MagicMock(), '__table__') baseclass.__table__.columns = {} get_class_mock.return_value = baseclass field_mock = MagicMock() self.DjangoModelMock._meta.fields = [field_mock] has_default_mock = Mock(return_value=True) field_mock.attach_mock(has_default_mock, 'has_default') field_mock.attname = 'test' set_all_class_defaults({}) ColumnDefaultMock.assert_not_called()
def test_field_no_class(self, ColumnDefaultMock, apps_mock, get_class_mock): # Patched modules don't get passed into the TestCase setUp method setUp(self, apps_mock, get_class_mock) baseclass = MagicMock() baseclass.attach_mock(MagicMock(), '__table__') baseclass.__table__.columns = {} get_class_mock.side_effect = ClassNotFoundError() set_all_class_defaults({}) ColumnDefaultMock.assert_not_called()
def test_dont_save_customer(self): self.assertFalse(Customer.objects.exists()) # class TemplateRegressionTest(TestCase): # def test_template_has_non_field_errors(self): # invalid_data = dict(name='Adam Smith', email='adam') # response = self.client.post(r('bookstore:customer_add'), invalid_data) # self.assertContains(response, '<ul class="errorlist nonfield">')
def test_get_post_data_multipart(): class TheCase(APITestCase, TestCase): post_data = {'some': 'data'} case = TheCase() post_data = case._get_post_data(content_type='multipart/form-data') assert (post_data.decode() == '--BoUnDaRyStRiNg\r\nContent-Disposition: ' 'form-data; name="some"\r\n\r\ndata\r\n--' 'BoUnDaRyStRiNg--\r\n')
def test_request_overwrite(): class TheCase(APITestCase, TestCase): view_class = APITestView request_meta = {'HTTP_REFERER': 'http://example.com'} case = TheCase() case.request( request_meta={'HTTP_REFERER': 'http://example.com/blah'}) assert case._request.method == 'GET' assert case._request.META['SERVER_NAME'] == 'testserver' assert case._request.META['SERVER_PORT'] == '80' assert case._request.META['HTTP_REFERER'] == 'http://example.com/blah'
def test_request_overwrite_view_kwargs(): # default view_kwargs are {'test_arg': False}; by overwriting view_kwargs # in request(), setup_view should be called with # view_kwargs={'test_arg': True} class TheCase(APITestCase, TestCase): view_class = APITestView case = TheCase() case.setup_view = MagicMock() case.request(view_kwargs={'test_arg': True}) case.setup_view.assert_called_with(view_kwargs={'test_arg': True})
def test_get_url_params(): class TheCase(ViewTestCase, TestCase): def setup_get_data(self): return { 'some': 'abc def :/?#[]@!$&\'()*+,;=', 'key': 'value'} case = TheCase() url_params = case._get_url_params() reserved_str = '%3A%2F%3F%23%5B%5D%40%21%24%26%27%28%29%2A%2B%2C%3B%3D' assert 'some=abc+def+%s' % reserved_str in url_params assert 'key=value' in url_params
def test_setup_models(): class TheCase(ViewTestCase, TestCase): id = 0 def setup_models(self): self.id = 1 case = TheCase() assert case.id == 0 case.setUp() assert case.id == 1
def test_setup_models_not_present(): class TheCase(ViewTestCase, TestCase): id = 0 case = TheCase() assert case.id == 0 case.setUp() assert case.id == 0
def test_setup_view_from_view_class(): class TheCase(ViewTestCase, TestCase): view_class = views.GenericView case = TheCase() view = case.setup_view() assert view.__name__ == views.GenericView.__name__
def test_setup_view_from_view_class_with_view_kwargs(): class TheCase(ViewTestCase, TestCase): view_class = views.GenericView case = TheCase() view = case.setup_view(view_kwargs={'test_arg': True}) assert view.__name__ == views.GenericView.__name__ assert view.view_initkwargs == {'test_arg': True}
def test_get_get_data_method(): class TheCase(ViewTestCase, TestCase): def setup_get_data(self): return {'some': 'data'} case = TheCase() get_data = case._get_get_data() assert get_data == {'some': 'data'}
def test_get_get_data_attribute(): class TheCase(ViewTestCase, TestCase): get_data = {'some': 'data'} case = TheCase() get_data = case._get_get_data() assert get_data == {'some': 'data'}