def test_minimal(self): data = {"verbosity": "minimal"} response = self.forced_auth_req('get', self.url, data=data) self.assertEqual(response.status_code, status.HTTP_200_OK) first_response = sorted(response.data, key=itemgetter("id"))[0] keys = sorted(first_response.keys()) six.assertCountEqual(self, keys, ['id', 'name'])
def test_intervention_attachment(self): code = "partners_intervention_attachment" file_type = AttachmentFileTypeFactory(code=code) AttachmentFactory( file_type=file_type, code=code, file="sample1.pdf", content_object=self.intervention_attachment, uploaded_by=self.user ) response = self.forced_auth_req( "get", self.url, user=self.unicef_staff, ) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data), 3) self.assert_keys(response) self.assert_values(response, self.default_partner_response + [{ "partner": self.partner.name, "partner_type": self.partner.partner_type, "vendor_number": self.partner.vendor_number, "pd_ssfa_number": self.intervention.number, }]) six.assertCountEqual(self, [x["file_type"] for x in response.data], [ self.file_type_1.label, self.file_type_2.label, self.intervention_attachment.type.name ])
def test_model_field_history_attribute_returns_all_histories(self): person = Person.objects.create(name='Initial Name') histories = FieldHistory.objects.get_for_model_and_field( person, 'name') six.assertCountEqual(self, list(person.field_history), list(histories))
def test_called_with_preview_content_and_article_have_current_revision( self): article = Article.objects.create() ArticleRevision.objects.create(article=article, title="Test title", content="Some beauty test text") content = ("""This is a normal paragraph\n""" """\n""" """Headline\n""" """========\n""") expected_markdown = ("""<p>This is a normal paragraph</p>\n""" """<h1 id="wiki-toc-headline">Headline</h1>""") # monkey patch from wiki.core.plugins import registry registry._cache = {'spam': 'eggs'} output = wiki_render({}, article, preview_content=content) assertCountEqual(self, self.keys, output) self.assertEqual(output['article'], article) self.assertMultiLineEqual(output['content'], expected_markdown) self.assertIs(output['preview'], True) self.assertEqual(output['plugins'], {'spam': 'eggs'}) self.assertEqual(output['STATIC_URL'], django_settings.STATIC_URL) self.assertEqual(output['CACHE_TIMEOUT'], settings.CACHE_TIMEOUT) output = self.render({'article': article, 'pc': content}) self.assertIn(expected_markdown, output)
def test_model_has_get_field_history_method(self): person = Person.objects.create(name='Initial Name') history = FieldHistory.objects.get() # Or using the {field_name}_history property added to your model six.assertCountEqual(self, list(person.get_name_history()), [history])
def test_update_team(self): """ Update an existing team's name and description """ tag1 = TagFactory() tag2 = TagFactory() team = TeamFactory(tags=[tag1, tag2]) tag3 = TagFactory() newtags = [tag1.id, tag3.id] url = reverse('team-detail', args=[team.id]) data = { "id": team.id, "name": team.name + " updated", "short_desc": team.name + " updated", "tags": newtags } response = self.client.put(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data['id'], data['id']) self.assertEqual(response.data['name'], data['name']) self.assertEqual(response.data['short_desc'], data['short_desc']) self.assertEqual(len(response.data['tags']), 2) six.assertCountEqual(self, response.data['tags'], [tag1.id, tag3.id])
def test_called_with_preview_content_and_article_dont_have_current_revision( self): article = Article.objects.create() content = ("""This is a normal paragraph\n""" """\n""" """Headline\n""" """========\n""") # monkey patch from wiki.core.plugins import registry registry._cache = {'spam': 'eggs'} output = wiki_render({}, article, preview_content=content) assertCountEqual(self, self.keys, output) self.assertEqual(output['article'], article) self.assertMultiLineEqual(output['content'], '') self.assertIs(output['preview'], True) self.assertEqual(output['plugins'], {'spam': 'eggs'}) self.assertEqual(output['STATIC_URL'], django_settings.STATIC_URL) self.assertEqual(output['CACHE_TIMEOUT'], settings.CACHE_TIMEOUT) self.render({'article': article, 'pc': content})
def assert_values(self, response, expected): received = [{ "partner": x["partner"], "partner_type": x["partner_type"], "vendor_number": x["vendor_number"], "pd_ssfa_number": x["pd_ssfa_number"], } for x in response.data] six.assertCountEqual(self, received, expected)
def test_delete_is_soft_by_default_model(self): Schema.objects.mass_create('a', 'b', 'c') Schema.objects.get(schema='b').delete() six.assertCountEqual(self, ['a', 'b', 'c'], Schema.objects.values_list('pk', flat=True)) six.assertCountEqual(self, ['a', 'c'], Schema.objects.active().values_list('schema', flat=True))
def test_send_notification(self): old_email_count = Email.objects.count() valid_notification = NotificationFactory() valid_notification.send_notification() six.assertCountEqual(self, valid_notification.recipients, valid_notification.sent_recipients) self.assertEqual(Email.objects.count(), old_email_count + 1)
def _test_transition(self, user, action, expected_response, errors=None, data=None): response = self.forced_auth_req( 'post', self.engagement_url(action), user=user, data=data ) self.assertEqual(response.status_code, expected_response) if errors: six.assertCountEqual(self, response.data.keys(), errors or [])
def _test_allowed_actions(self, user, actions): response = self.forced_auth_req( 'options', self.engagement_url(), user=user ) self.assertEqual(response.status_code, status.HTTP_200_OK) action_codes = [action['code'] for action in response.data['actions']['allowed_FSM_transitions']] self.assertItemsEqual(action_codes, actions) six.assertCountEqual(self, action_codes, actions)
def test_list_of_contributors_contains_all_live_contributors(self): contributor_list = models.ContributorListPage.objects.all().first() all_live_contributors = models.ContributorPage.objects.live() six.assertCountEqual( self, all_live_contributors, contributor_list.nonfeatured_contributors[0] )
def _test_list_view(self, user, expected_firms): response = self.forced_auth_req('get', '/api/audit/audit-firms/', user=user) self.assertEqual(response.status_code, status.HTTP_200_OK) six.assertCountEqual(self, map(lambda x: x['id'], response.data['results']), map(lambda x: x.id, expected_firms))
def _test_list(self, user, engagements, params=""): response = self.forced_auth_req('get', '/api/audit/engagements/', data={"status": params}, user=user) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertIn('results', response.data) self.assertIsInstance(response.data['results'], list) six.assertCountEqual(self, map(lambda x: x['id'], response.data['results']), map(lambda x: x.id, engagements))
def test_topics_in_alphabetical_order(self): topics_page = TopicListPage.objects.get(slug='topics') topic_1 = Topic.objects.get(slug="topic-1") topic_2 = Topic.objects.get(slug="topic-2") topic_3 = Topic.objects.get(slug="topic-3") topic_4 = Topic.objects.get(slug="topic-4") six.assertCountEqual( self, topics_page.topics, [topic_1, topic_2, topic_3, topic_4] )
def _test_list_view(self, user, expected_visits): response = self.forced_auth_req( 'get', reverse('tpm:visits-list'), user=user ) self.assertEquals(response.status_code, status.HTTP_200_OK) six.assertCountEqual( self, map(lambda x: x['id'], response.data['results']), map(lambda x: x.id, expected_visits) )
def assert_keys(self, response): expected_keys = [ "id", "partner", "partner_type", "vendor_number", "pd_ssfa_number", "filename", "file_type", "file_link", "uploaded_by", "created", ] for row in response.data: six.assertCountEqual(self, list(row.keys()), expected_keys)
def test_queries(self): """ Test the documented API of connection.queries. """ with connection.cursor() as cursor: reset_queries() cursor.execute("SELECT 1" + connection.features.bare_select_suffix) self.assertEqual(1, len(connection.queries)) self.assertIsInstance(connection.queries, list) self.assertIsInstance(connection.queries[0], dict) six.assertCountEqual(self, connection.queries[0].keys(), ['sql', 'time']) reset_queries() self.assertEqual(0, len(connection.queries))
def test_stringified_translations_validation(self): translations = { 'en': { 'name': "France", 'url': "http://en.wikipedia.org/wiki/France" }, 'es': { 'name': "Francia", 'url': "http://es.wikipedia.org/wiki/Francia" } } data = {'country_code': 'FR', 'translations': json.dumps(translations)} serializer = CountryTranslatedSerializer(data=data) self.assertTrue(serializer.is_valid(), serializer.errors) six.assertCountEqual(self, serializer.validated_data['translations'], translations)
def test_create_request(self): from django.core.handlers.wsgi import WSGIRequest from med_djutils.test import create_request req = create_request('my-path', 'get') self.assertIsInstance(req, WSGIRequest) self.assertEqual(req.META['PATH_INFO'], 'my-path') self.assertEqual(req.META['REQUEST_METHOD'], 'GET') data = {'x': 'y', 'a': 1} req = create_request('something', 'post', data=data) self.assertIsInstance(req, WSGIRequest) self.assertEqual(req.META['PATH_INFO'], 'something') self.assertEqual(req.META['REQUEST_METHOD'], 'POST') six.assertCountEqual( # in Python2 = assertItemsEqual self, req.POST.items(), [('x', 'y'), ('a', '1')])
def test_partner_changed_with_pd(self): partner = PartnerWithAgreementsFactory( partner_type=PartnerType.CIVIL_SOCIETY_ORGANIZATION) response = self._do_update( self.unicef_focal_point, { 'partner': partner.id, 'active_pd': partner.agreements.first().interventions.values_list('id', flat=True) }) self.assertEqual(response.status_code, status.HTTP_200_OK) six.assertCountEqual( self, map(lambda pd: pd['id'], response.data['active_pd']), map(lambda i: i.id, partner.agreements.first().interventions.all()))
def test_translations_validation(self): data = { 'country_code': 'FR', 'translations': { 'en': { 'name': "France", 'url': "http://en.wikipedia.org/wiki/France" }, 'es': { 'name': "Francia", 'url': "http://es.wikipedia.org/wiki/Francia" }, } } serializer = CountryTranslatedSerializer(data=data) self.assertTrue(serializer.is_valid(), serializer.errors) six.assertCountEqual(self, serializer.validated_data['translations'], data['translations'])
def test_translations_serialization(self): expected = { 'pk': self.instance.pk, 'country_code': 'ES', 'translations': { 'en': { 'name': "Spain", 'url': "http://en.wikipedia.org/wiki/Spain" }, 'es': { 'name': "España", 'url': "http://es.wikipedia.org/wiki/España" }, } } serializer = CountryTranslatedSerializer(self.instance) six.assertCountEqual(self, serializer.data, expected)
def _test_list_options(self, user, can_create=True, writable_fields=None): response = self.forced_auth_req( 'options', reverse('tpm:partners-list'), user=user ) self.assertEquals(response.status_code, status.HTTP_200_OK) if can_create: self.assertIn('POST', response.data['actions']) six.assertCountEqual( self, writable_fields or [], response.data['actions']['POST'].keys() ) else: self.assertNotIn('POST', response.data['actions'])
def test_project_features(self): user = get(User, is_staff=True) project = get(Project, main_language_project=None) # One explicit, one implicit feature feature1 = get(Feature, projects=[project]) feature2 = get(Feature, projects=[], default_true=True) feature3 = get(Feature, projects=[], default_true=False) # noqa client = APIClient() client.force_authenticate(user=user) resp = client.get('/api/v2/project/%s/' % (project.pk)) self.assertEqual(resp.status_code, 200) self.assertIn('features', resp.data) six.assertCountEqual( self, resp.data['features'], [feature1.feature_id, feature2.feature_id], )
def _test_detail_options(self, user, can_update=True, writable_fields=None): response = self.forced_auth_req( 'options', reverse('tpm:partners-detail', args=(self.tpm_partner.id,)), user=user ) self.assertEquals(response.status_code, status.HTTP_200_OK) if can_update: self.assertIn('PUT', response.data['actions']) six.assertCountEqual( self, writable_fields or [], response.data['actions']['PUT'].keys() ) else: self.assertNotIn('PUT', response.data['actions'])
def test_csv_flat_export_api(self): response = self.forced_auth_req( 'get', reverse('funds:funds-donor'), user=self.unicef_staff, data={"format": "csv_flat"}, ) self.assertEqual(response.status_code, status.HTTP_200_OK) dataset = Dataset().load(response.content.decode('utf-8'), 'csv') self.assertEqual(dataset.height, 1) six.assertCountEqual(self, dataset._get_headers(), [ "Grant", "ID", "Name", "created", "modified", ]) self.assertEqual(len(dataset[0]), 5)
def test_translated_fields_validation(self): data = { 'country_code': 'FR', 'translations': { 'en': { 'url': "http://en.wikipedia.org/wiki/France" }, 'es': { 'name': "Francia", 'url': "es.wikipedia.org/wiki/Francia" }, } } serializer = CountryTranslatedSerializer(data=data) self.assertFalse(serializer.is_valid()) self.assertIn('translations', serializer.errors) six.assertCountEqual(self, serializer.errors['translations'], ('en', 'es')) self.assertIn('name', serializer.errors['translations']['en']) self.assertIn('url', serializer.errors['translations']['es'])
def test_default_scopes(self): application1 = Application( name='application1', description='testapp', client_type=Application.CLIENT_CONFIDENTIAL, authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE, redirect_uris='http://localhost:7000/', is_anonymous=True, required_scopes='send_mail picture', ) six.assertCountEqual(self, ['send_mail', 'picture'], get_default_scopes(application1)) application2 = Application( name='application2', description='testapp', client_type=Application.CLIENT_CONFIDENTIAL, authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE, redirect_uris='http://localhost:7000/', required_scopes='send_mail picture', ) six.assertCountEqual(self, settings.OAUTH2_DEFAULT_SCOPES, get_default_scopes(application2))
def test_update_tags(self): """ Ensure you can update the tags """ tag1 = TagFactory() tag2 = TagFactory() assessment = AssessmentFactory(tags=[tag1, tag2]) tag3 = TagFactory() url = reverse('assessment-detail', args=(assessment.id, )) data = { "id": assessment.id, "template": assessment.template.id, "status": assessment.status, "tags": [tag1.id, tag3.id] } response = self.client.put(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data['id'], data['id']) self.assertEqual(len(response.data['tags']), 2) six.assertCountEqual(self, response.data['tags'], [tag1.id, tag3.id])
def test_if_preview_content_is_none(self): # monkey patch from wiki.core.plugins import registry registry._cache = {'ham': 'spam'} article = Article.objects.create() output = wiki_render({}, article) assertCountEqual(self, self.keys, output) self.assertEqual(output['article'], article) self.assertIsNone(output['content']) self.assertIs(output['preview'], False) self.assertEqual(output['plugins'], {'ham': 'spam'}) self.assertEqual(output['STATIC_URL'], django_settings.STATIC_URL) self.assertEqual(output['CACHE_TIMEOUT'], settings.CACHE_TIMEOUT) # Additional check self.render({'article': article, 'pc': None})
def test_nested_translated_serializer(self): data = { "continent": "Europe", "countries": [{ 'country_code': 'FR', 'translations': { 'en': { 'name': "France", 'url': "http://en.wikipedia.org/wiki/France" }, 'es': { 'name': "Francia", 'url': "http://es.wikipedia.org/wiki/Francia" }, } }] } serializer = ContinentCountriesTranslatedSerializer(data=data) self.assertTrue(serializer.is_valid(), serializer.errors) nested_data = serializer.validated_data['countries'][0] expected = data['countries'][0] six.assertCountEqual(self, nested_data, expected)
def test_translations_serialization_only_some_languages(self): self.instance.set_current_language('fr') self.instance.name = "Espagne" self.instance.url = "https://fr.wikipedia.org/wiki/Espagne" self.instance.save_translations() # So we got: en, es, fr: Let's drop the english expected = { 'pk': self.instance.pk, 'country_code': 'ES', 'translations': { 'es': { 'name': "Spain", 'url': "http://en.wikipedia.org/wiki/Spain" }, 'fr': { 'name': "Espagne", 'url': "https://fr.wikipedia.org/wiki/Espagne" }, } } context = {'languages': ['es', 'fr']} serializer = CountryTranslatedSerializer(self.instance, context=context) six.assertCountEqual(self, serializer.data, expected)
def test_model_field_history_attribute_returns_all_histories(self): person = Person.objects.create(name='Initial Name') histories = FieldHistory.objects.get_for_model_and_field(person, 'name') six.assertCountEqual(self, list(person.field_history), list(histories))
def test_delete_is_soft_by_default_model(self): Schema.objects.mass_create("a", "b", "c") Schema.objects.get(schema="b").delete() six.assertCountEqual(self, ["a", "b", "c"], Schema.objects.values_list("pk", flat=True)) six.assertCountEqual(self, ["a", "c"], Schema.objects.active().values_list("schema", flat=True))
def test_dropping_schema_queryset(self): Schema.objects.mass_create("a", "b", "c") Schema.objects.filter(schema__in=["b", "c"]).delete(drop=True) six.assertCountEqual(self, ["a"], Schema.objects.values_list("pk", flat=True))
def test_constraint_name_method(self): from ..models import AwareModel, NaiveModel, SelfReferentialModel with connection.schema_editor() as editor: self.assertEqual(3, len(editor._constraint_names(AwareModel, index=True))) six.assertCountEqual( self, ['tests_awaremodel_pkey'], editor._constraint_names(AwareModel, primary_key=True) ) six.assertCountEqual(self, [ 'tests_awaremodel_pkey', 'tests_awaremodel_name_key' ], editor._constraint_names(AwareModel, unique=True)) six.assertCountEqual(self, [ 'tests_awaremodel_name_key' ], editor._constraint_names(AwareModel, unique=True, primary_key=False)) six.assertCountEqual(self, ['tests_awaremodel_pkey'], editor._constraint_names(AwareModel, primary_key=True, unique=True)) six.assertCountEqual(self, [], editor._constraint_names(AwareModel, foreign_key=True)) six.assertCountEqual(self, [], editor._constraint_names(AwareModel, foreign_key=True, primary_key=True)) six.assertCountEqual(self, ['tests_awaremodel_factor_check'], editor._constraint_names(AwareModel, check=True)) with connection.schema_editor() as editor: six.assertCountEqual(self, ['tests_naivemodel_pkey'], editor._constraint_names(NaiveModel, primary_key=True)) six.assertCountEqual(self, ['tests_naivemodel_name_key'], editor._constraint_names(NaiveModel, unique=True, primary_key=False)) with connection.schema_editor() as editor: # These constraint names appear to change between different versions of django or python? self.assertEqual(1, len(editor._constraint_names(SelfReferentialModel, foreign_key=True)))