def test__one_untagged_hadith_in_db__that_one_is_returned(self): # Add few hadiths and tag them all. cls = HadithRandomUntaggedApiTestCase c = Client() resp = c.post('/apis/hadiths?fb_token=%s' % cls.marie_accesstoken, {'text': 'test 1', 'tags': [cls.tag_id]}) assert resp.status_code == HTTP_201_CREATED hadith1_id = resp.data['id'] resp = c.post('/apis/hadiths?fb_token=%s' % cls.marie_accesstoken, {'text': 'test 2'}) assert resp.status_code == HTTP_201_CREATED hadith2_id = resp.data['id'] resp = c.post('/apis/hadiths?fb_token=%s' % cls.marie_accesstoken, {'text': 'test 3', 'tags': [cls.tag_id]}) assert resp.status_code == HTTP_201_CREATED hadith3_id = resp.data['id'] # Try to retrieve a random hadith and ensure no result is returned. resp = self.get('/apis/hadiths/randomuntagged') self.assertEqual(HTTP_200_OK, resp.status_code) self.assertIsNotNone(resp.data) self.assertEqual(hadith2_id, resp.data['id']) # Delete the hadiths we created. resp = c.delete('/apis/hadiths/%d?fb_token=%s' % (hadith1_id, cls.marie_accesstoken)) self.assertEqual(HTTP_204_NO_CONTENT, resp.status_code) resp = c.delete('/apis/hadiths/%d?fb_token=%s' % (hadith2_id, cls.marie_accesstoken)) self.assertEqual(HTTP_204_NO_CONTENT, resp.status_code) resp = c.delete('/apis/hadiths/%d?fb_token=%s' % (hadith3_id, cls.marie_accesstoken)) self.assertEqual(HTTP_204_NO_CONTENT, resp.status_code)
class SkipQuestionDeleteTest(BaseTest): def setUp(self): self.skip_rule = SkipQuestionRuleFactory() self.client = Client() user = self.create_user(group=self.GLOBAL_ADMIN, org="WHO") self.assign('can_edit_questionnaire', user) self.client.login(username=user.username, password='******') def test_should_delete_skip_rule_when_it_exists(self): #given url = '/questionnaire/subsection/skiprule/%d/' % self.skip_rule.id #when response = self.client.delete(url) #then self.assertEqual(200, response.status_code) self.assertEqual(SkipRule.objects.filter(id=self.skip_rule.id).count(), 0) def test_should_not_delete_skip_rule_when_it_doesnt_exists(self): #given url = '/questionnaire/subsection/skiprule/%d/' % (self.skip_rule.id + 1) #when response = self.client.delete(url) #then self.assertEqual(204, response.status_code) self.assertEqual(SkipRule.objects.filter(id=self.skip_rule.id).count(), 1)
def test_requires_get_or_post(self): client = Client(enforce_csrf_checks=True) with override_settings(DEBUG=False): self.assertEquals(client.get(self.str_uri).status_code, 403) self.assertEquals(client.post(self.str_uri).status_code, 403) self.assertEquals(client.head(self.str_uri).status_code, 405) self.assertEquals(client.options(self.str_uri).status_code, 405) self.assertEquals(client.put(self.str_uri).status_code, 405) self.assertEquals(client.delete(self.str_uri).status_code, 405) self.assertEquals(client.get(self.str_class_uri).status_code, 403) self.assertEquals(client.post(self.str_class_uri).status_code, 403) self.assertEquals(client.head(self.str_class_uri).status_code, 405) self.assertEquals(client.put(self.str_class_uri).status_code, 405) self.assertEquals(client.delete(self.str_class_uri).status_code, 405) with override_settings(DEBUG=True): self.assertEquals(client.get(self.str_uri).status_code, 200) self.assertEquals(client.post(self.str_uri).status_code, 200) self.assertEquals(client.head(self.str_uri).status_code, 200) self.assertEquals(client.options(self.str_uri).status_code, 200) self.assertEquals(client.put(self.str_uri).status_code, 200) self.assertEquals(client.delete(self.str_uri).status_code, 200) self.assertEquals(client.get(self.str_class_uri).status_code, 200) self.assertEquals(client.post(self.str_class_uri).status_code, 200) self.assertEquals(client.head(self.str_class_uri).status_code, 200)
class TestApiDummyRequisitionTracker(TestCase): def setUp(self): self.pending = Pending() self.client = Client() self.tracker = DummyRequisitionTracker() self.requisition_list = [Requisition(*req_info).as_dict() for req_info in read_file(settings.WMS_REQUISITION_DATA)] def test_pending_get(self): """Check correct response for get request.""" request = self.client.get('/api/v1/pending/') request_data = json.loads(request.content.decode("utf-8")) self.assertEquals(request_data['pending'], self.requisition_list) def test_pending_delete(self): """ Check correct response for delete request with correct candidate_id. """ request = self.client.delete('/api/v1/pending/00001/') self.assertEquals(request.status_code, 204) def test_pending_delete_wrong_id(self): """Check correct response for delete request with wrong candidate_id.""" request = self.client.delete('/api/v1/pending/abcd/') self.assertEquals(request.status_code, 404)
def test_view_delete(self): """ Test deleting a group Verifies: * group is deleted * all associated permissions are deleted """ group0 = self.test_save() group1 = self.test_save(name='test2') c = Client() url = '/group/%s/edit/' # anonymous user response = c.delete(url % group0.id, follow=True) self.assertEqual(200, response.status_code) self.assertTemplateUsed(response, 'registration/login.html') # unauthorized user self.assertTrue( c.login(username=self.user0.username, password='******')) response = c.delete(url % group0.id) self.assertEqual(403, response.status_code) # invalid group response = c.delete(url % "DoesNotExist") self.assertEqual(404, response.status_code) # get form - authorized (permission) grant(self.user0, 'admin', group0) response = c.delete(url % group0.id) self.assertEqual(200, response.status_code) self.assertEquals('application/json', response['content-type']) self.assertFalse(Group.objects.filter(id=group0.id).exists()) self.assertEqual('1', response.content) # setup signal self.signal_editor = self.signal_group = None def callback(sender, editor, **kwargs): self.signal_user = self.user0 self.signal_group = sender view_group_deleted.connect(callback) # get form - authorized (superuser) self.user0.is_superuser = True self.user0.save() response = c.delete(url % group1.id) self.assertEqual(200, response.status_code) self.assertEquals('application/json', response['content-type']) self.assertFalse(Group.objects.filter(id=group1.id).exists()) self.assertEqual('1', response.content) # check signal set properties self.assertEqual(group1.name, self.signal_group.name) self.assertEqual(self.user0, self.signal_user)
def test_signdown(self): # fine case c = Client(enforce_csrf_checks=True) r = c.post('/login', {'username': '******', 'password': '******'}) r = c.delete('/signdown') self.assertEqual(r.status_code, status.HTTP_200_OK) # not logged in c = Client(enforce_csrf_checks=True) r = c.delete('/signdown') self.assertEqual(r.status_code, status.HTTP_403_FORBIDDEN)
class TestViews(TestCase): def setUp(self): self.user = create_user("user1") self.user.set_password("password") self.user.save() create_profile(self.user, "some_key", 5) # create a piece of vocab with one reading. self.vocabulary = create_vocab("radioactive bat") self.cat_reading = create_reading(self.vocabulary, "ねこ", "猫", 5) # setup a review with two synonyms self.review = create_review(self.vocabulary, self.user) self.client = Client() self.client.login(username="******", password="******") def test_removing_synonym_removes_synonym(self): dummy_kana = "whatever" dummy_characters = "somechar" synonym, created = self.review.add_answer_synonym(dummy_kana, dummy_characters) self.client.delete(reverse("api:reading-synonym-detail", args=(synonym.id,))) self.review.refresh_from_db() self.assertListEqual(self.review.reading_synonyms_list(), []) def test_reviewing_that_does_not_need_to_be_reviewed_fails(self): self.review.needs_review = False self.review.save() response = self.client.post( reverse("api:review-correct", args=(self.review.id,)), data={"wrong_before": "false"}, ) self.assertEqual(response.status_code, 403) self.assertIsNotNone(response.data["detail"]) response = self.client.post( reverse("api:review-incorrect", args=(self.review.id,)) ) self.assertEqual(response.status_code, 403) self.assertIsNotNone(response.data["detail"]) def test_sending_contact_email_returns_json_response(self): self.client.force_login(self.user) response = self.client.post( reverse("api:contact-list"), data={"name": "test", "email": "*****@*****.**", "body": "test"}, ) json = response.content self.assertIsNotNone(json)
class TestesApiProduto(unittest.TestCase): def setUp(self): self.c = Client() call_command('flush', interactive=False, verbosity=0) call_command('loaddata', 'base.json', verbosity=0) def teste_obter_lista_produtos(self): response = self.c.get('/api/produto/') object_response = json.loads(response.content) assert response.status_code == 200 assert len(object_response) == 3 assert object_response[1]['fields']['nome'] == 'iPad Air 2' assert object_response[1]['fields']['valor'] == 3500.0 def teste_cadastrar_produto(self): self.c.post('/api/produto',{'nome':'Produto Teste','valor':'2500'}, content_type='application/json') response = self.c.get('/api/produto/') object_response = json.loads(response.content) assert response.status_code == 200 assert len(object_response) assert object_response[3]['fields']['nome'] == 'Produto Teste' assert object_response[3]['fields']['valor'] == 2500.0 def teste_remover_produto(self): self.c.delete('/api/produto',{'id':'3'}) response = self.c.get('/api/produto/') object_response = json.loads(response.content) assert response.status_code == 200 assert len(object_response) == 2 assert object_response[0]['pk'] == 1 assert object_response[0]['fields']['nome'] == 'Mac Book 256GB Intel Core M' assert object_response[0]['fields']['valor'] == 8499.0 def teste_atualizar_produto(self): self.c.post('/api/produto',{'id':'2','nome':'iPad Mini 2','valor':'2499'}, content_type='application/json') response = self.c.get('/api/produto/') object_response = json.loads(response.content) assert response.status_code == 200 assert object_response[1]['pk'] == 2 assert object_response[1]['fields']['nome'] == 'iPad Mini 2' assert object_response[1]['fields']['valor'] == 2499.0
class TestEnibarImport(TestCase): def setUp(self): self.client = Client() super().setUp() def test_note_import_404(self): response = self.client.options("/enibar/note/", "{}") self.assertEqual(response.status_code, 404) response = self.client.put("/enibar/note", "pouet") self.assertEqual(response.status_code, 404) def test_note_put_403(self): response = self.client.put("/enibar/note", '{"id": 1, "nickname": "coucou", "mail": "*****@*****.**", "note": 52.2}') self.assertEqual(response.status_code, 403) def test_note_delete_403(self): response = self.client.delete("/enibar/note", '{"id": 2}') self.assertEqual(response.status_code, 403) def test_import_note_put(self): response = self.client.put("/enibar/note", '{"token": "changeme", "id": 1, "nickname": "coucou", "mail": "*****@*****.**", "note": 52.2}') self.assertEqual(response.status_code, 200) note = Note.objects.get(foreign_id=1) self.assertEqual(note.foreign_id, 1) self.assertEqual(note.nickname, "coucou") self.assertEqual(note.mail, "*****@*****.**") self.assertEqual(note.note, Decimal("52.2")) response = self.client.put("/enibar/note", '{"token": "changeme", "id": 1, "nickname": "coucou", "mail": "*****@*****.**", "note": 50.2}') self.assertEqual(response.status_code, 200) note = Note.objects.get(foreign_id=1) self.assertEqual(note.foreign_id, 1) self.assertEqual(note.nickname, "coucou") self.assertEqual(note.mail, "*****@*****.**") self.assertEqual(note.note, Decimal("50.2")) def test_import_note_delete(self): Note.objects.create(foreign_id=2, nickname="toto", mail="*****@*****.**", note=Decimal("10")) response = self.client.delete("/enibar/note", '{"token": "changeme", "id": 2}') self.assertEqual(response.status_code, 200) with self.assertRaises(Note.DoesNotExist): Note.objects.get(foreign_id=2) def test_get_note(self): Note.objects.create(foreign_id=2, nickname="toto", mail="*****@*****.**", note=Decimal("10")) Note.objects.create(foreign_id=3, nickname="toto2", mail="*****@*****.**", note=Decimal("11")) response = self.client.get("/enibar/note") self.assertEqual(response.json(), [{'note': '10.00', 'nickname': 'toto', 'foreign_id': 2, 'mail': '*****@*****.**'}, {'note': '11.00', 'nickname': 'toto2', 'foreign_id': 3, 'mail': '*****@*****.**'}]) response = self.client.get("/enibar/note", {"foreign_id": 2}) self.assertEqual(response.json(), [{'mail': '*****@*****.**', 'note': '10.00', 'nickname': 'toto', 'foreign_id': 2}]) response = self.client.get("/enibar/note", {"pouet": 2}) self.assertEqual(response.status_code, 404)
def test_all_return_statuses_when_debug_true(self): c = Client(enforce_csrf_checks=True) with override_settings(DEBUG=True): for uri in self.uris: self._assertStatusCode(c.get(uri).status_code, 200, uri) self._assertStatusCode(c.post(uri).status_code, 200, uri) self._assertStatusCode(c.head(uri).status_code, 200, uri) self._assertStatusCode(c.options(uri).status_code, 200, uri) if uri.endswith('class_view/'): self._assertStatusCode(c.put(uri).status_code, 405, uri) self._assertStatusCode(c.delete(uri).status_code, 405, uri) else: self._assertStatusCode(c.put(uri).status_code, 200, uri) self._assertStatusCode(c.delete(uri).status_code, 200, uri)
class DeleteDayEntry(TestCase): def setUp(self): self.c = Client() carlos = User.objects.create(username='******') dateISO = '2016-02-09T23:48:14.297Z' date = getDatetimeFromISO(dateISO) setUpEntry = Day.objects.create(user=carlos, sleepingQuality='bad', tirednessFeeling='good', date=date ) self.setUpEntry = Day.objects.get(date=date) def test_delete_day_entry(self): data = {'user': 1, 'uuid': self.setUpEntry.uuid } dataJSON = json.dumps(data) request = HttpRequest() request.url = '/calendar' request.data = dataJSON response = self.c.delete('/calendar', content_type='application/json', data=dataJSON) self.assertEqual(len(Day.objects.all()), 0)
def test_remove_task(self): """ Test that the task is removed from list properly. """ task_id = self.create_task( { "task_info": { "repo_slug": self.repo.slug, # No ids to export, but task should still run. "ids": [], }, "task_type": EXPORT_TASK_TYPE } )['id'] self.assertEqual(self.get_task(task_id)['status'], 'success') # Other users can't stop tasks they don't own. client2 = Client() client2.login( username=self.user_norepo.username, password=self.PASSWORD ) resp = client2.delete("{base}tasks/{task_id}/".format( base=API_BASE, task_id=task_id )) self.assertEqual(resp.status_code, HTTP_404_NOT_FOUND) self.delete_task(task_id) self.get_task(task_id, expected_status=HTTP_404_NOT_FOUND) self.assertEqual(self.get_tasks()['count'], 0)
class ViewTestBase(TestCase): """ Shared helper functions for testing API views. """ def setUp(self): """ Set up a django test client, and verify that we have an _endpoint attribute defined. The _endpoint class variable should be defined as the base url (i.e. "/api/users/") which all POST/GET/PUT/DELETE HTTP requests should be directed. For requests that contain an item ID as part of the URL, this ID will be appended as needed. """ self._client = Client() if not hasattr(self, '_endpoint'): raise NotImplementedError("Please specify an _endpoint member for your view test class") def _get_url_with_params(self, *args): if args: return self._endpoint + "/".join(map(str, args)) + "/" else: return self._endpoint def _create(self, *args, **kwargs): return self._client.post(self._get_url_with_params(*args), data=dumps(kwargs), content_type='application/json') def _read(self, *args, **kwargs): return self._client.get(self._get_url_with_params(*args), data=kwargs) def _update(self, *args, **kwargs): return self._client.put(self._get_url_with_params(*args), data=dumps(kwargs), content_type='application/json') def _delete(self, *args): return self._client.delete(self._get_url_with_params(*args))
class TestRegisterUserView(TestCase): def setUp(self): self.client = Client() self.data = {'username': '******', 'first_name': 'first_name', 'email': '*****@*****.**', 'password': '******', } def test_put_method(self): response = self.client.put(reverse('register_user')) self.assertEquals(response.status_code, 405) def test_delete_methods(self): response = self.client.delete(reverse('register_user')) self.assertEquals(response.status_code, 405) def test_get(self): response = self.client.get(reverse('register_user')) self.assertEquals(response.status_code, 200) self.assertTemplateUsed(response, template_name='register.html') def test_post_valid_data(self): before = len(BusinemeUser.objects.all()) self.client.post(reverse('register_user'), data=self.data) after = len(BusinemeUser.objects.all()) self.assertGreater(after, before)
def test_user_api(self): u = User.objects.create(username='******', first_name='tester', last_name='mcgee') u.set_password('test') u.save() c = Client() response = c.get('/api/v1/current-user/') self.assertEqual(response.status_code, 401) c.login(username='******', password='******') response = c.get('/api/v1/current-user/') self.assertEqual(response.status_code, 200) js = json.loads(response.content) self.assertEqual(js['first_name'], 'tester') self.assertEqual(js['last_name'], 'mcgee') self.assertEqual(js['is_superuser'], False) self.assertEqual(js['username'], 'test') js['is_superuser'] = True response = c.post('/api/v1/current-user/', data=json.dumps(js), content_type='application/json') self.assertEqual(response.status_code, 405) response = c.put('/api/v1/current-user/', data=json.dumps(js), content_type='application/json') self.assertEqual(response.status_code, 405) response = c.delete('/api/v1/current-user/') self.assertEqual(response.status_code, 405)
class DepartmentTestCase(TestCase): fixtures = ['api.json'] def setUp(self): self.client = Client() def testGetAllDepartments(self): response = self.client.get(reverse('department-list')) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.data), 3) def testGetOneDepartments(self): response = self.client.get(reverse('department-detail', args=[2])) self.assertEqual(response.status_code, 200) self.assertEqual(response.data['name'], 'produce') def testCreateDepartment(self): data = {'name' : 'hba'} data_string = json.dumps(data) response = self.client.post( reverse('department-list'), content_type='application/json', data=data_string ) self.assertEqual(response.status_code, 201) self.assertEqual(response.data['id'], 5) def testDeleteDepartment(self): response = self.client.delete(reverse('department-detail', args=[2])) self.assertEqual(response.status_code, 204) response = self.client.get(reverse('department-detail', args=[2])) self.assertEqual(response.status_code, 404)
def test_upload_of_basic_packaged_widget(self): User.objects.create_user('test', '*****@*****.**', 'test') widget_path = wirecloud.catalogue.utils.wgt_deployer.get_base_dir('Morfeo', 'Test', '0.1') c = Client() f = open(os.path.join(os.path.dirname(__file__), 'test-data/basic_widget.wgt')) c.login(username='******', password='******') response = c.post(self.resource_collection_url, {'file': f}, HTTP_HOST='www.example.com') f.close() self.assertEqual(response.status_code, 200) self.assertTrue(os.path.isdir(widget_path)) self.assertTrue(os.path.exists(os.path.join(widget_path, 'images/catalogue.png'))) self.assertTrue(os.path.exists(os.path.join(widget_path, 'images/smartphone.png'))) self.assertTrue(os.path.exists(os.path.join(widget_path, 'documentation/images/image.png'))) self.assertTrue(os.path.exists(os.path.join(widget_path, 'documentation/index.html'))) self.assertFalse(os.path.exists(os.path.join(widget_path, 'test.html'))) widget = CatalogueResource.objects.get(vendor='Morfeo', short_name='Test', version='0.1') widget_info = json.loads(widget.json_description) self.assertEqual(widget.template_uri, 'Morfeo_Test_0.1.wgt') self.assertEqual(widget_info['image'], 'images/catalogue.png') resource_entry_url = reverse('wirecloud_catalogue.resource_entry', kwargs={ 'vendor': 'Morfeo', 'name': 'Test', 'version': '0.1', }) c.login(username='******', password='******') response = c.delete(resource_entry_url, HTTP_HOST='www.example.com') self.assertEqual(response.status_code, 200) self.assertFalse(os.path.exists(widget_path))
class LanguageTestCase(TestCase): def setUp(self): self.client = Client() self.user = User.objects.create_user('admin', '*****@*****.**', 'admin') self.user.is_staff = True self.user.is_superuser = True self.user.is_active = True self.user.save() auth = '%s:%s' % ('admin', 'admin') auth = 'Basic %s' % base64.encodestring(auth) auth = auth.strip() self.extra = { 'HTTP_AUTHORIZATION': auth, } self.dutch = Language.objects.create(code="Du", name="Dutch", lname="Dutch", charset="UTF-8") def language_get(self): response = self.client.get('/api/language', {}, **self.extra) self.assertEqual(response.status_code, 200) def language_put(self): response = self.client.put('/api/language/Du/', {'name': 'dutch'}, **self.extra) self.assertEqual(response.status_code, 200) def language_delete(self): response = self.client.delete('/api/language/Du/', {}, **self.extra) self.assertEqual(response.status_code, 204) def language_post(self): response = self.client.post('/api/language', { 'name':'Urdu' ,'code':'Ur','lname':'Urdu' ,'charset':'UTF-8'} , **self.extra) self.assertEqual(response.status_code, 200)
class CommentActionTest(TestCase): def setUp(self): self.client = Client() self.user = User.objects.create(username='******', password='******') self.user.set_password('shuaib') self.user.save() self.login = self.client.login(username='******', password='******') def create_resources( self, text='some more words', resource_file='resource_file'): return Resource.objects.create( id=100, text=text, author=self.user, resource_file=resource_file ) def test_user_can_post_new_comments(self): self.assertTrue(self.login) self.create_resources() response = self.client.post( '/comment/', {'content': 'test_content', 'resource_id': 100}, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(response.status_code, 200) self.assertContains(response, "success") def test_user_can_delete_comments(self): self.assertTrue(self.login) resource = self.create_resources() comment = Comment( id=200, author=self.user, resource=resource, content="Test comment" ) comment.save() response = self.client.delete( '/comment/200', HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(response.status_code, 200) self.assertContains(response, "success") def test_user_can_edit_comments(self): self.assertTrue(self.login) resource = self.create_resources() comment = Comment( id=200, author=self.user, resource=resource, content="Test comment" ) comment.save() json_data = json.dumps({'content': 'Another Content', }) response = self.client.put( '/comment/200', json_data, content_type='application/json', HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(response.status_code, 200) self.assertContains(response, "success")
def test_api_without_id_not_allowed(self): c = Client() response = c.put("/api/person/") self.assertEqual(response.status_code, 400) response = c.delete("/api/person/") self.assertEqual(response.status_code, 400)
def test_put(self): client = Client() url = reverse('api:deck_delete', args=(self.id,)) response = client.delete(url) self.assertEqual(response.status_code, 200) self.assertRaises(Exception, Deck.get, self.id)
class LicenseTest(TestCase): """ Tests for creating, reading and deleting license objects. """ def setUp(self): """ Sets tests up with User, Client and License fixtures. """ self.user = create_test_user() self.client = Client() login(self.client) self.license = License.objects.create( shortname='LGPL 2.1', text='Lorem ipsum dolor, sit amet qualitet.') def test_create_license(self): """ Creates a License object with POST. """ data = { 'shortname': 'LGPL 2.0', 'text': 'Lorem ipsum dolor, sit amet qualitet.', } login(self.client, username='******', password='******') url = synthesize_url('licenses/create/') response = self.client.post(url, data) self.assertEqual(response.status_code, 200) def test_read_licenses(self): """ Reads all License objects with GET. """ url = synthesize_url('licenses/') response = self.client.get(url) self.assertEqual(response.status_code, 200) def test_read_license(self): """ Reads a single License object with GET. """ url = synthesize_url('licenses/%d/' % self.license.id) response = self.client.get(url) self.assertEqual(response.status_code, 200) def test_delete_license(self): """ Deletes a single License object with DELETE. """ login(self.client, username='******', password='******') url = synthesize_url('licenses/%d/delete/' % self.license.id) response = self.client.delete(url) self.assertEqual(response.status_code, 200)
def test_unused_image_methods(self): """ Tests that the following methods are correctly rejected by the image endpoint """ """ These fail as disallowed methods, so should return 405 status codes """ c = Client() response = c.get("/api/image") self.assertEqual(response.status_code, 405) c = Client() response = c.put("/api/image", {}) self.assertEqual(response.status_code, 405) c = Client() response = c.delete("/api/image") self.assertEqual(response.status_code, 405) c = Client() response = c.options("/api/image") self.assertEqual(response.status_code, 405) """ This has bad post syntax, so should return 400 """ c = Client() response = c.post("/api/image", {}) self.assertEqual(response.status_code, 400) """
def test_delete_not_implemented(self): """ Garante que não há endpoint para deletar chamado. """ c = Client() response = c.delete('/api/contacts/1') self.assertEquals(response.status_code, 404)
def test_upload_of_packaged_operators(self): User.objects.create_user('test', '*****@*****.**', 'test') operator_path = wirecloud.catalogue.utils.wgt_deployer.get_base_dir('Wirecloud', 'basic-operator', '0.1') c = Client() c.login(username='******', password='******') with open(os.path.join(os.path.dirname(__file__), 'test-data/basic_operator.zip'), 'rb') as f: response = c.post(self.resource_collection_url, {'file': f}, HTTP_HOST='www.example.com') self.assertEqual(response.status_code, 200) self.assertTrue(os.path.isdir(operator_path)) self.assertTrue(os.path.exists(os.path.join(operator_path, 'images/catalogue.png'))) self.assertTrue(os.path.exists(os.path.join(operator_path, 'doc/images/image.png'))) self.assertTrue(os.path.exists(os.path.join(operator_path, 'doc/index.html'))) operator = CatalogueResource.objects.get(vendor='Wirecloud', short_name='basic-operator', version='0.1') operator_info = json.loads(operator.json_description) self.assertEqual(operator.template_uri, 'Wirecloud_basic-operator_0.1.wgt') self.assertEqual(operator_info['image'], 'images/catalogue.png') resource_entry_url = reverse('wirecloud_catalogue.resource_entry', kwargs={ 'vendor': 'Wirecloud', 'name': 'basic-operator', 'version': '0.1', }) c.login(username='******', password='******') response = c.delete(resource_entry_url, HTTP_HOST='www.example.com') self.assertEqual(response.status_code, 200) self.assertEqual(os.path.exists(operator_path), False)
class ProductTest(TestCase): """ Tests for creating, reading and deleting Product objects. """ def setUp(self): """ Sets tests up with User, Client and Product fixtures. """ self.user = create_test_user() self.client = Client() login(self.client) self.product = Product.objects.create(name='Tizen Common', description='Foo, Bar, Biz, Bah') def test_create_product(self): """ Creates a Product object with POST. """ data = { 'name': 'Tizen IVI', 'description': 'Tizen IVI', } login(self.client, username='******', password='******') url = synthesize_url('products/create/') response = self.client.post(url, data) self.assertEqual(response.status_code, 200) def test_read_products(self): """ Reads all Product objects with GET. """ url = synthesize_url('products/') response = self.client.get(url) self.assertEqual(response.status_code, 200) def test_read_product(self): """ Reads a single Product object with GET. """ url = synthesize_url('products/%d/' % self.product.id) response = self.client.get(url) self.assertEqual(response.status_code, 200) def test_delete_product(self): """ Deletes a single Product object with DELETE. """ login(self.client, username='******', password='******') url = synthesize_url('products/%d/delete/' % self.product.id) response = self.client.delete(url) self.assertEqual(response.status_code, 200)
class PackageTest(TestCase): """ Tests for creating, reading and deleting Package objects. """ def setUp(self): """ Sets tests up with User, Client, Domain, GitTree and Package fixtures. """ self.user = create_test_user() self.client = Client() login(self.client) self.domain = Domain.objects.create(name='Multimedia') self.subdomain = SubDomain.objects.create( name='SubMultimedia', domain=self.domain) self.gittree = GitTree.objects.create( gitpath='/pulseaudio/libpulseaudio', subdomain=self.subdomain) self.package = Package.objects.create(name='Pulseaudio') self.package.gittree_set.add(self.gittree) def test_create_package(self): """ Creates a Package object with POST. """ data = { 'name': '/alsa/libalsa', } login(self.client, username='******', password='******') url = synthesize_url('packages/create/') response = self.client.post(url, data) self.assertEqual(response.status_code, 200) def test_read_packages(self): """ Reads all Package objects with GET. """ url = synthesize_url('packages/') response = self.client.get(url) self.assertEqual(response.status_code, 200) def test_read_package(self): """ Reads a single Package object with GET. """ url = synthesize_url('packages/%d/' % self.package.id) response = self.client.get(url) self.assertEqual(response.status_code, 200) def test_delete_package(self): """ Deletes a single Package object with DELETE. """ login(self.client, username='******', password='******') url = synthesize_url('packages/%d/delete/' % self.package.id) response = self.client.delete(url) self.assertEqual(response.status_code, 200)
class ImageTest(TestCase): """ Tests for creating, reading and deleting Image objects. """ def setUp(self): """ Sets tests up with User, Client and Product and Image fixtures. """ self.user = create_test_user() self.client = Client() login(self.client) self.product = Product.objects.create( name='Tizen Common', description='Foo, Bar, Biz, Bah') self.image = Image.objects.create( name='Tizen IVI', target='Tizen IVI', arch='x86', product=self.product) def test_create_image(self): """ Creates a Image object with POST. """ data = { 'name': 'Tizen PC', 'target': 'Tizen PC', 'arch': 'x86', 'product': '%d' % self.product.id } login(self.client, username='******', password='******') url = synthesize_url('images/create/') response = self.client.post(url, data) self.assertEqual(response.status_code, 200) def test_read_images(self): """ Reads all Image objects with GET. """ url = synthesize_url('images/') response = self.client.get(url) self.assertEqual(response.status_code, 200) def test_read_image(self): """ Reads a single Image object with GET. """ url = synthesize_url('images/%d/' % self.image.id) response = self.client.get(url) self.assertEqual(response.status_code, 200) def test_delete_image(self): """ Deletes a single Image object with DELETE. """ login(self.client, username='******', password='******') url = synthesize_url('images/%d/delete/' % self.image.id) response = self.client.delete(url) self.assertEqual(response.status_code, 200)
def test_wrong_people_orgs(self): request = Client() response = request.post("/api/people/1/organizations") self.assertEqual(response.status_code,405) response = request.put("/api/people/1/organizations") self.assertEqual(response.status_code,405) response = request.delete("/api/people/1/organizations") self.assertEqual(response.status_code,405)
class VideoAPITestCase(TestCase): def setUp(self): self.client = Client() v = Video() v.url = "retrieve" v.save() def test_retrieve(self): v = Video.objects.get(url="retrieve") def test_post_success(self): url = "5nD-8euqNN4" data = '{{"url": "{}"}}'.format(url) response = self.client.post('/videos/', {'data': data}) message = json.loads(response.content) self.assertEqual(message['status'], 0) def test_post_save(self): url = "5nD-8euqNN4" data = '{{"url": "{}"}}'.format(url) response = self.client.post('/videos/', {'data': data}) message = json.loads(response.content) Video.objects.get(url=url) def test_post_save_fail(self): self.assertRaises(Video.DoesNotExist, Video.objects.get, url="none") def test_post_error(self): response = self.client.post('/videos/') message = json.loads(response.content) self.assertEqual(message['status'], 1) def test_parse_error(self): response = self.client.post('/videos/', {'data': '{"test"}'}) message = json.loads(response.content) self.assertEqual(message['status'], 2) def test_no_url(self): response = self.client.post('/videos/', {'data': '{"description": "test"}'}) message = json.loads(response.content) self.assertEqual(message['status'], 3) def test_get(self): response = self.client.get('/videos/') self.assertEqual(response.status_code, 200) def test_delete(self): v2 = Video() v2.url = "delete" v2.save() response = self.client.delete('/videos/{}/'.format(v2.id)) message = json.loads(response.content) self.assertEqual(message['status'], 0) self.assertRaises(Video.DoesNotExist, Video.objects.get, url="delete")
def test_api_root_webanno_grade_ok( lti_path, lti_launch_url, course_user_lti_launch_params_with_grade, assignment_target_factory, webannotation_annotation_factory, catchpy_search_result_shell, make_lti_replaceResultResponse, ): """webannotation api, configured from client search request. sends lis_outcome_service_url, lis_result_sourcedid to signal that lti consumer expects a grade """ # 1. create course, assignment, target_object, user course, user, launch_params = course_user_lti_launch_params_with_grade assignment_target = assignment_target_factory(course) target_object = assignment_target.target_object assignment = assignment_target.assignment assignment.annotation_database_url = "http://funky.com" assignment.annotation_database_apikey = "funky_key" assignment.annotation_database_secret_token = "funky_secret" assignment.save() # get outcome_resource_url lis_outcome_service_url = launch_params["lis_outcome_service_url"] # 2. set starting resource resource_link_id = launch_params["resource_link_id"] resource_config = LTIResourceLinkConfig.objects.create( resource_link_id=resource_link_id, assignment_target=assignment_target, ) # 3. lti launch client = Client(enforce_csrf_checks=False) response = client.post( lti_path, data=launch_params, ) assert response.status_code == 302 assert response.cookies.get("sessionid") expected_url = (reverse( "hx_lti_initializer:access_annotation_target", args=[course.course_id, assignment.assignment_id, target_object.pk], ) + f"?resource_link_id={resource_link_id}" + f"&utm_source={client.session.session_key}") assert response.url == expected_url # 4. access target object to be able to create annotations on it # this is required after live-updates implementation! response = client.get(expected_url) assert (response.status_code) == 200 # set responses to assert # TODO: if using webannotation api, should send webannotation format catcha = webannotation_annotation_factory(user) catcha_id = uuid.uuid4().hex catcha["platform"]["collection_id"] = "{}".format( assignment.assignment_id) # convert uuid to str search_result = catchpy_search_result_shell search_result["total"] = 1 search_result["size"] = 1 search_result["rows"].append(catcha) annotation_store_urls = {} for op in ["search"]: # search preserve params request to hxat annotation_store_urls[ op] = "{}/?version=catchpy&collectionId={}&resource_link_id={}&userid={}".format( assignment.annotation_database_url, assignment.assignment_id, resource_link_id, user.anon_id, ) for op in ["create", "update", "delete"]: annotation_store_urls[op] = "{}/{}".format( assignment.annotation_database_url, catcha_id, ) responses.add( responses.POST, annotation_store_urls["create"], json=catcha, status=200, ) responses.add( responses.PUT, annotation_store_urls["update"], json=catcha, status=200, ) responses.add( responses.DELETE, annotation_store_urls["delete"], json=catcha, status=200, ) responses.add( responses.GET, annotation_store_urls["search"], json=search_result, status=200, ) replace_result_response = make_lti_replaceResultResponse responses.add( responses.POST, lis_outcome_service_url, body=replace_result_response, content_type="application/xml", status=200, ) path = reverse("annotation_store:api_root_prefix") # create request response = client.post( "{}/{}?version=catchpy&resource_link_id={}".format( path, catcha_id, resource_link_id), data=catcha, content_type="application/json", HTTP_X_ANNOTATOR_AUTH_TOKEN="hahaha", ) assert response.status_code == 200 content = json.loads(response.content.decode()) assert len(responses.calls) == 2 assert content == catcha # update request path_with_id = "{}/{}?version=catchpy&resource_link_id={}".format( path, catcha_id, resource_link_id) response = client.put( path_with_id, data=catcha, content_type="application/json", HTTP_X_ANNOTATOR_AUTH_TOKEN="hehehe", ) assert response.status_code == 200 content = json.loads(response.content.decode()) assert len(responses.calls) == 3 assert content == catcha # delete request path_delete = "{}/{}?version=catchpy&collectionId={}&resource_link_id={}".format( path, catcha_id, assignment.assignment_id, resource_link_id) response = client.delete( path_delete, HTTP_X_ANNOTATOR_AUTH_TOKEN="hihihi", ) assert response.status_code == 200 content = json.loads(response.content.decode()) assert len(responses.calls) == 4 assert content == catcha # search request # needs resource_link_id to access LTI params for pass_grade response = client.get( "{}?version=catchpy&collectionId={}&resource_link_id={}&userid={}". format(path, assignment.assignment_id, resource_link_id, user.anon_id), HTTP_X_ANNOTATOR_AUTH_TOKEN="hohoho", ) assert response.status_code == 200 content = json.loads(response.content.decode()) assert len(responses.calls) == 6 assert content == search_result
def test_valid_delete_employee(self): client = Client() response = client.delete(reverse('delete', kwargs={'id': self.emp5.id})) self.assertEqual(response.status_code, 302)
def test_HTTPResponse_405(self): client = Client(enforce_csrf_checks=True) response = client.get('/api/token/') csrftoken = response.cookies[ 'csrftoken'].value # Get csrf token from cookie client.post('/api/signup/', json.dumps({ 'username': '******', 'password': '******' }), content_type='application/json', HTTP_X_CSRFTOKEN=csrftoken) response = client.post('/api/signin/', json.dumps({ 'username': '******', 'password': '******' }), content_type='application/json', HTTP_X_CSRFTOKEN=csrftoken) csrftoken = response.cookies[ 'csrftoken'].value # Get csrf token from cookie #starts here response = client.post('/api/token/', json.dumps({ 'username': '******', 'password': '******' }), content_type='application/json', HTTP_X_CSRFTOKEN=csrftoken) self.assertEqual(response.status_code, 405) response = client.get('/api/signup/', HTTP_X_CSRFTOKEN=csrftoken) self.assertEqual(response.status_code, 405) response = client.get('/api/signin/', HTTP_X_CSRFTOKEN=csrftoken) self.assertEqual(response.status_code, 405) response = client.post('/api/signout/', json.dumps({ 'username': '******', 'password': '******' }), content_type='application/json', HTTP_X_CSRFTOKEN=csrftoken) self.assertEqual(response.status_code, 405) response = client.delete('/api/article/', HTTP_X_CSRFTOKEN=csrftoken) self.assertEqual(response.status_code, 405) response = client.post('/api/article/3/', json.dumps({ 'username': '******', 'password': '******' }), content_type='application/json', HTTP_X_CSRFTOKEN=csrftoken) self.assertEqual(response.status_code, 405) response = client.delete('/api/article/1/comment/', HTTP_X_CSRFTOKEN=csrftoken) self.assertEqual(response.status_code, 405) response = client.post('/api/comment/2/', json.dumps({ 'username': '******', 'password': '******' }), content_type='application/json', HTTP_X_CSRFTOKEN=csrftoken) self.assertEqual(response.status_code, 405)
class TestApi(TestCase): """Test the various api app endpoints""" def setUp(self): self.client = Client() models.Adverb(word='test').save() models.Adjective(word='test').save() models.Noun(word='test').save() models.Verb(word='test').save() models.Quotes(phrase='testing is great', author='kevin', pk=500).save() models.Quotes(phrase='I should be updated.', author='kevin', pk=501).save() models.Quotes(phrase='Delete me.', author='kevin', pk=502).save() def test_confucius(self): """Test /confucius returns value from list""" response = self.client.get('/api/confucius') self.assertIn(response.json().get('msg'), settings.CONFUCIUS_QUOTES) def test_bs(self): """Test /bs returns string compiled from models""" response = self.client.get('/api/bs') self.assertEqual(response.status_code, 200) def test_weather_pass(self): data = {'state': 'CA', 'city': 'Redding'} response = self.client.get('/api/weather', data=data) self.assertEqual(response.status_code, 200) def test_weather_state_fails(self): data = {'state': 'CB', 'city': 'Redding'} response = self.client.get('/api/weather', data=data) self.assertEqual(response.status_code, 400) @mock.patch( 'requests.get', autospec=True, side_effect=[_FakeResponse(data=_MOCKED_API_WEATHER_RESPONSE_DATA)]) def test_weather_city_fails(self, mock_request): data = {'state': 'CA', 'city': 'fakecity'} response = self.client.get('/api/weather', data=data) self.assertEqual(mock_request.call_count, 1) expected = _MOCKED_API_WEATHER_RESPONSE_DATA.get('response').get('error')\ .get('description') self.assertEqual(response.json().get('city'), [expected]) def test_quotes_post_passes(self): data = {'phrase': 'do or do not, there is no try', 'author': 'yoda'} response = self.client.post('/api/quotes', data=data) self.assertEqual(response.status_code, 201) def test_quotes_post_fails(self): data = {'phrase': 'testing is great', 'author': 'a plagiariser'} response = self.client.post('/api/quotes', data=data) self.assertEqual(response.status_code, 400) self.assertEqual(response.json().get('phrase'), ["quotes with this phrase already exists."]) def test_quotes_get(self): response = self.client.get('/api/quotes') self.assertEqual(response.status_code, 200) self.assertEqual(len(response.json().get('results')), 3) def test_quotes_put(self): response = self.client.put('/api/quotes/501', data={ 'phrase': 'I have been updated.', 'author': 'kevin' }, content_type='application/json') self.assertEqual(response.status_code, 200) self.assertEqual(response.json().get('phrase'), 'I have been updated.') def test_quotes_detail_get(self): response = self.client.get('/api/quotes/500') self.assertEqual(response.status_code, 200) def test_quotes_delete(self): response = self.client.delete('/api/quotes/502') self.assertEqual(response.status_code, 204) def test_quotes_random(self): response = self.client.get('/api/quotes/random') self.assertEqual(response.status_code, 200) pk = response.json().get('id') phrase = response.json().get('phrase') expected = models.Quotes.objects.get(pk=pk) self.assertEqual(phrase, expected.phrase) def test_reversed(self): response = self.client.get('/api/reversed', data={'string': 'reverse this text'}) self.assertEqual('txet siht esrever', response.json().get('msg'))
def make_request(data): client = Client() url = reverse(revoke_refresh_token) return client.delete(url, data, content_type="application/json")
class ReviewViewTest(TestCase): def setUp(self): self.normal_user = CustomUser.objects.create( name_surname="name", country="AM", date_of_birth="2000-07-02", email="*****@*****.**", username='******', password="******") self.fanfic = Fanfic.objects.create(name="Testek fanfic", author="michaelRuiz", web="http://web-fanfic.com", genre1="adv", complete=True) self.review = Review.objects.create(score=3, fanfic=self.fanfic, user=self.normal_user) self.client = Client() self.client.force_login(user=self.normal_user) def test_review_edit_page_status_code(self): """ Test get edit page for review """ response = self.client.get( reverse('reviews:review', kwargs={'review_id': self.review.id})) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'review.html') def test_update_review(self): """ Test update review """ text = "test text" response = self.client.post(reverse( 'reviews:review', kwargs={'review_id': self.review.id}), { '_method': 'put', 'text': text, 'stars': 3 }, follow=True) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'review.html') updated_review = Review.objects.get(id=self.review.id) self.assertEqual(updated_review.text, text) self.assertEqual(updated_review.score, 3) def test_update_review_stars_error(self): """ Test update review """ text = "test text" response = self.client.post( reverse('reviews:review', kwargs={'review_id': self.review.id}), { '_method': 'put', 'text': text, 'stars': 30 }) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'review.html') updated_review = Review.objects.get(id=self.review.id) self.assertNotEqual(updated_review.score, 30) def test_update_review_text_empty(self): """ Test update review """ text = "" response = self.client.post( reverse('reviews:review', kwargs={'review_id': self.review.id}), { '_method': 'put', 'text': text, 'stars': 3 }) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'review.html') updated_review = Review.objects.get(id=self.review.id) self.assertNotEqual(updated_review.text, text) def test_see_review_status_code(self): """ Test see a review """ response = self.client.get( reverse('reviews:reviews', kwargs={'review_id': self.review.id})) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'review.html') def test_create_review_when_already_exists(self): """ Test Create new review """ text = "test text2" response = self.client.post(reverse('reviews:reviews'), { 'fanfic_id': self.fanfic.id, 'text': text, 'stars': 3 }) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'review.html') updated_review = Review.objects.get(id=self.review.id) self.assertNotEqual(updated_review.text, text) def test_create_review(self): """ Test Create new review """ text = "test text2" self.review.delete() response = self.client.post(reverse('reviews:reviews'), { 'fanfic_id': self.fanfic.id, 'text': text, 'stars': 3 }, follow=True) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'fanfic.html') updated_review = Review.objects.get(fanfic=self.fanfic, user=self.normal_user) self.assertEqual(updated_review.text, text) def test_delete_review(self): """ Test Delete a review """ response = self.client.delete(reverse( 'reviews:reviews', kwargs={'review_id': self.review.id}), follow=True) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'fanfic.html') exists = Review.objects.filter(fanfic=self.fanfic, user=self.normal_user).exists() self.assertFalse(exists)
class CustomerDetailTestCase(TestCase): def setUp(self): self.client = Client() self.customer_name = 'Teste' self.customer_email = '*****@*****.**' self.customer = Customer(name=self.customer_name, email=self.customer_email) self.customer.save() token_payload = {"id": self.customer.id} self.token = jwt.encode(token_payload, settings.JWT_SECRET, algorithm='HS256') def test_get_customer_detail_without_headers(self): response = self.client.get(f'/customers/{self.customer.id}/') self.assertEqual(response.status_code, 400) def test_get_customer_detail_valid_token(self): response = self.client.get(f'/customers/{self.customer.id}/', HTTP_AUTHORIZATION=self.token) response_data = json.loads(response.content) self.assertEqual(response.status_code, 200) self.assertEqual(self.customer.name, response_data['name']) self.assertEqual(self.customer.email, response_data['email']) def test_get_customer_detail_invalid_token(self): invalid_token = 'ayJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NH0.-aLaOKeSHBU2cul6JzhHn1mmXANz1QGL2KYIhOBHpQc' response = self.client.get(f'/customers/{self.customer.id}/', HTTP_AUTHORIZATION=invalid_token) self.assertEqual(response.status_code, 401) def test_get_customer_detail_token_from_another_user(self): new_customer = Customer(name='a', email='*****@*****.**') new_customer.save() response = self.client.get(f'/customers/{new_customer.id}/', HTTP_AUTHORIZATION=self.token) self.assertEqual(response.status_code, 401) def test_update_customer(self): data = {"name": "New test name"} response = self.client.put(f'/customers/{self.customer.id}/', data, content_type="application/json", HTTP_AUTHORIZATION=self.token) response_data = json.loads(response.content) self.assertEqual(response.status_code, 200) self.assertEqual(response_data['name'], data['name']) self.assertEqual(response_data['email'], self.customer.email) def test_update_email_existing_email(self): new_customer = Customer(name='a', email='*****@*****.**') new_customer.save() data = {"email": new_customer.email} response = self.client.put(f'/customers/{self.customer.id}/', data, content_type="application/json", HTTP_AUTHORIZATION=self.token) response_data = json.loads(response.content) self.assertEqual(response.status_code, 400) self.assertEqual( response_data, {'email': ['customer with this Email already exists.']}) def test_delete_customer(self): response = self.client.delete(f'/customers/{self.customer.id}/', HTTP_AUTHORIZATION=self.token) self.assertEqual(response.status_code, 204) with self.assertRaises(Customer.DoesNotExist): Customer.objects.get(name=self.customer_name, email=self.customer_email)
class ApiViewTest(TestCase): """Test for API Views.""" def setUp(self): self.client = Client() self.user_test_credentials = ('user1', '*****@*****.**', 'qwerty123') self.admin_test_credentials = ('admin', '*****@*****.**', 'qwerty123') self.create_user_account() self.create_admin_account() self.api_key = self.create_api_key() self.api_key_issuance_endpoint = '/api/api_key' self.api_key_revocation_endpoint = '{}/{}'.format( self.api_key_issuance_endpoint, self.api_key) @classmethod def b64encode_credentials(cls, username, password): credentials = '{}:{}'.format(username, password) b64_encoded_credentials = b64encode(credentials.encode('utf-8')) return b64_encoded_credentials.decode('utf-8') def create_user_account(self): User.objects.create_user(*self.user_test_credentials) def create_admin_account(self): User.objects.create_superuser(*self.admin_test_credentials) def create_api_key(self): uname, email, passwd = self.admin_test_credentials admin = User.objects.get(username=uname) return ApiKey.objects.create(owner=admin, revoked=False).token.hashid def test_api_key_issuance_handler_without_authorization_header(self): response = self.client.post(self.api_key_issuance_endpoint).json() self.assertEqual( 'Use Basic Auth and supply your username and password.', response['message']) def test_api_key_issuance_handler_with_invalid_authorization_header(self): response = self.client.post( self.api_key_issuance_endpoint, **{ 'HTTP_AUTHORIZATION': 'YWRtaW46a25pZ2h0MTg=' }).json() self.assertEqual( 'Use Basic Auth and supply your username and password.', response['message']) def test_api_key_issuance_handler_with_invalid_credentials(self): response = self.client.post( self.api_key_issuance_endpoint, **{ 'HTTP_AUTHORIZATION': 'Basic {}'.format( self.b64encode_credentials('support', 'qwerty')) }).json() self.assertEqual('Invalid Credentials.', response['message']) def test_api_key_issuance_handler_with_normal_user_credentials(self): uname, email, passwd = self.user_test_credentials response = self.client.post( self.api_key_issuance_endpoint, **{ 'HTTP_AUTHORIZATION': 'Basic {}'.format(self.b64encode_credentials(uname, passwd)) }).json() self.assertEqual('Unauthorized.', response['message']) def test_api_key_issuance_handler_with_admin_user_credentials(self): uname, email, passwd = self.admin_test_credentials response = self.client.post( self.api_key_issuance_endpoint, **{ 'HTTP_AUTHORIZATION': 'Basic {}'.format(self.b64encode_credentials(uname, passwd)) }).json() issued_api_key = ApiKey.objects.get(owner__username=uname, revoked=False) self.assertEqual(issued_api_key.token.hashid, response['api_key']) def test_api_key_issuance_handler_with_url_ending_with_api_key(self): uname, email, passwd = self.admin_test_credentials response = self.client.post( self.api_key_revocation_endpoint, **{ 'HTTP_AUTHORIZATION': 'Basic {}'.format(self.b64encode_credentials(uname, passwd)) }).json() self.assertEqual('Bad Request.', response['message']) def test_api_key_revocation_handler_without_authorization_header(self): response = self.client.delete(self.api_key_revocation_endpoint).json() self.assertEqual( 'Use Basic Auth and supply your username and password.', response['message']) def test_api_key_revocation_handler_with_invalid_authorization_header( self): response = self.client.delete( self.api_key_revocation_endpoint, **{ 'HTTP_AUTHORIZATION': 'YWRtaW46a25pZ2h0MTg=' }).json() self.assertEqual( 'Use Basic Auth and supply your username and password.', response['message']) def test_api_key_revocation_handler_with_invalid_credentials(self): response = self.client.delete( self.api_key_revocation_endpoint, **{ 'HTTP_AUTHORIZATION': 'Basic {}'.format( self.b64encode_credentials('support', 'qwerty')) }).json() self.assertEqual('Invalid Credentials.', response['message']) def test_api_key_revocation_handler_with_admin_user_credentials(self): uname, email, passwd = self.admin_test_credentials response = self.client.delete( self.api_key_revocation_endpoint, **{ 'HTTP_AUTHORIZATION': 'Basic {}'.format(self.b64encode_credentials(uname, passwd)) }).json() self.assertEqual('%s was revoked.' % self.api_key, response['message']) def test_api_key_revocation_handler_with_invalid_api_key(self): uname, email, passwd = self.admin_test_credentials response = self.client.delete( '%s/%s' % (self.api_key_issuance_endpoint, 'a49d7536849be9da859a67bae2d7256e'), **{ 'HTTP_AUTHORIZATION': 'Basic {}'.format(self.b64encode_credentials(uname, passwd)) }).json() self.assertEqual('Bad Request.', response['message']) def test_api_key_revocation_handler_with_url_without_api_key(self): uname, email, passwd = self.admin_test_credentials response = self.client.delete( self.api_key_issuance_endpoint, **{ 'HTTP_AUTHORIZATION': 'Basic {}'.format(self.b64encode_credentials(uname, passwd)) }).json() self.assertEqual('Bad Request.', response['message'])
class TestApiAnnotationSegmentations(TestCase): def setUp(self): self.client = Client() self.project = Project.objects.create(name='Project 1') self.dataset = Dataset.objects.create(name='Test 1', project=self.project) self.category = Category.objects.create(name='Test Category 1', project=self.project) self.image = Image.objects.create(name='Name', url='http://images.com/img1.jpg', dataset=self.dataset) self.segmentation = Annotation.objects.create( image=self.image, category=self.category, width=800, height=600, segmentation=[[10, 10, 20, 10, 20, 20, 10, 20]]) def create_multi(self): return None def test_index(self): response = self.client.get('/api/annotation-segmentations/') self.assertEqual(response.status_code, 200) self.assertEqual(len(response.data), 1) def test_creation(self): response = self.client.post( '/api/annotation-segmentations/', { 'image': self.image.id, 'category': self.category.id, 'width': 800, 'height': 600, 'segmentation': [[10, 10, 20, 10, 20, 20, 10, 20]] }) self.assertEqual(response.status_code, 201) self.assertEqual(response.data['image'], self.image.id) def test_show(self): response = self.client.get('/api/annotation-segmentations/' + str(self.segmentation.id) + '/') self.assertEqual(response.status_code, 200) self.assertEqual(response.data['id'], self.segmentation.id) def test_edit(self): self.create_multi() response1 = self.client.post( '/api/annotation-segmentations/', { 'image': self.image.id, 'category': self.category.id, 'segmentation': [[10, 10, 20, 10, 20, 20, 10, 20]] }) created_id = response1.data['id'] self.assertEqual(response1.status_code, 201) new_data = { 'image': self.image.id, 'category': self.category.id, 'width': 1000, 'height': 2000, 'segmentation': [[10, 10, 20, 10, 20, 20, 10, 20]] } content = encode_multipart('BoUnDaRyStRiNg', new_data) content_type = 'multipart/form-data; boundary=BoUnDaRyStRiNg' response2 = self.client.put('/api/annotation-segmentations/' + str(created_id) + '/', content, content_type=content_type) self.assertEqual(response2.status_code, 200) response3 = self.client.get('/api/annotation-segmentations/' + str(created_id) + '/') self.assertEqual(response3.status_code, 200) self.assertEqual(response3.data['width'], 10) self.assertEqual(response3.data['height'], 10) def test_delete(self): response = self.client.delete('/api/annotation-segmentations/' + str(self.segmentation.id) + '/') self.assertEqual(response.status_code, 204)
def test_edit_delete_true(self): client = Client() response = client.delete('/api/todo/1') self.assertEqual(response.status_code, 200)
def test_edit_delete_false(self): client = Client() response = client.delete('/api/todo/2') self.assertEqual(response.status_code, 404)
def test_todo_delete(self): client = Client() response = client.delete('/api/todo') self.assertEqual(response.status_code, 405)
class ProjectUrlsTest(TestCase): def setUp(self): User.objects.create(username='******', password=make_password('user1')) User.objects.create(username='******', password=make_password('user2')) User.objects.create(username='******', password=make_password('user3')) Project.objects.create(title='title1', description='description1', type='projet') Project.objects.create(title='title2', description='a description 2', type='projet') Issue.objects.create( title='title1', desc='description1', tag='bug', priority='moyenne', project=Project.objects.get(pk=1), status='a faire', author=User.objects.get(pk=1), assignee=User.objects.get(pk=2), created_time=0, ) Issue.objects.create( title='title2', desc='description2', tag='bug', priority='moyenne', project=Project.objects.get(pk=1), status='a faire', author=User.objects.get(pk=1), assignee=User.objects.get(pk=2), created_time=0, ) Issue.objects.create( title='title4', desc='description4', tag='bug', priority='moyenne', project=Project.objects.get(pk=2), status='a faire', author=User.objects.get(pk=1), assignee=User.objects.get(pk=2), created_time=0, ) Comment.objects.create( description='description1', author=User.objects.get(pk=1), issue=Issue.objects.get(pk=1), created_time=0, ) Comment.objects.create( description='description2', author=User.objects.get(pk=2), issue=Issue.objects.get(pk=1), created_time=0, ) Comment.objects.create( description='description3', author=User.objects.get(pk=1), issue=Issue.objects.get(pk=3), created_time=0, ) Contributor.objects.create( user=User.objects.get(pk=1), project=Project.objects.get(pk=1), permission='manager', role='manager', ) Contributor.objects.create( user=User.objects.get(pk=2), project=Project.objects.get(pk=1), permission='contributeur', role='contributeur', ) Contributor.objects.create( user=User.objects.get(pk=3), project=Project.objects.get(pk=2), permission='manager', role='manager', ) self.create_read_good_url = '/api/projects/' self.create_read_wrong_url = '/api/project/' self.read_update_delete_good_url = '/api/projects/1/' self.read_update_delete_wrong_url = '/api/projects/5/' self.auth_url = reverse('token_obtain') self.client_user1 = Client(HTTP_AUTHORIZATION='Bearer ' + self.get_token('user1', 'user1')) self.client_user2 = Client(HTTP_AUTHORIZATION='Bearer ' + self.get_token('user2', 'user2')) self.client_user3 = Client(HTTP_AUTHORIZATION='Bearer ' + self.get_token('user3', 'user3')) def get_token(self, username, password): post = {'username': username, 'password': password} response = self.client.post(self.auth_url, post) data = json.loads(response.content) return data['access'] def test_list_good_url(self): response = self.client_user1.get(self.create_read_good_url) self.assertEquals(response.status_code, 200) def test_list_wrong_url(self): response = self.client_user1.get(self.create_read_wrong_url) self.assertEquals(response.status_code, 404) def test_create_good_url(self): post = { 'title': 'title3', 'description': 'description3', 'type': 'projet' } response = self.client_user1.post(self.create_read_good_url, post) self.assertEquals(response.status_code, 201) def test_create_wrong_url(self): post = { 'title': 'title3', 'description': 'description3', 'type': 'projet' } response = self.client_user1.post(self.create_read_wrong_url, post) self.assertEquals(response.status_code, 404) def test_update_good_url(self): post = { 'title': 'title_update', 'description': 'description1', 'type': 'projet' } response = self.client_user1.put(self.read_update_delete_good_url, post, content_type='application/json') self.assertEquals(response.status_code, 200) def test_update_wrong_url(self): post = { 'title': 'title_update', 'description': 'description1', 'type': 'projet' } response = self.client_user1.put(self.read_update_delete_wrong_url, post, content_type='application/json') self.assertEquals(response.status_code, 404) def test_detail_good_url(self): response = self.client_user2.get(self.read_update_delete_good_url) self.assertEquals(response.status_code, 200) def test_detail_wrong_url(self): response = self.client_user2.get(self.read_update_delete_wrong_url) self.assertEquals(response.status_code, 404) def test_delete_good_url(self): response = self.client_user1.delete(self.read_update_delete_good_url) self.assertEquals(response.status_code, 204) def test_delete_wrong_url(self): response = self.client_user1.delete(self.read_update_delete_wrong_url) self.assertEquals(response.status_code, 404)
class TestVlDetailViews(TestCase): def setUp(self): self.client = Client() self.vl_inst_id = str(uuid.uuid4()) self.vl_name = str(uuid.uuid4()) self.ns_inst_id = str(uuid.uuid4()) VLInstModel(vlinstanceid=self.vl_inst_id, vldid="", vlinstancename=self.vl_name, ownertype=1, ownerid=self.ns_inst_id, relatednetworkid="network1", relatedsubnetworkid="subnet1,subnet2", vimid="", tenant="").save() VNFFGInstModel(vnffgdid="", vnffginstid="", nsinstid=self.ns_inst_id, vllist="test1," + self.vl_inst_id + ",test2,test3", endpointnumber=0, cplist="", vnflist="", fplist="", status="").save() def tearDown(self): VLInstModel.objects.all().delete() VNFFGInstModel.objects.all().delete() @mock.patch.object(restcall, "call_req") @mock.patch.object(vimadaptor.VimAdaptor, "delete_network") @mock.patch.object(vimadaptor.VimAdaptor, "delete_subnet") def test_delete_vl(self, mock_delete_subnet, mock_delete_network, mock_req_by_rest): mock_req_by_rest.return_value = [ 0, '{"test":"test_name","name":"vim_name","type":"type_name","url":"url_add"' ',"userName":"******","password":"******","tenant":"tenant"}' ] response = self.client.delete("/openoapi/nslcm/v1/ns/vls/%s" % self.vl_inst_id) self.assertEqual(status.HTTP_202_ACCEPTED, response.status_code) expect_resp_data = {"result": 0, "detail": "delete vl success"} self.assertEqual(expect_resp_data, response.data) for vnffg_info in VNFFGInstModel.objects.filter( nsinstid=self.ns_inst_id): self.assertEqual(vnffg_info.vllist, "test1,test2,test3") if VLInstModel.objects.filter(vlinstanceid=self.vl_inst_id): self.fail() response = self.client.delete("/openoapi/nslcm/v1/ns/vls/%s" % "notExist") self.assertEqual(status.HTTP_202_ACCEPTED, response.status_code) expect_resp_data = { "result": 0, "detail": "vl is not exist or has been already deleted" } self.assertEqual(expect_resp_data, response.data) def test_query_vl(self): response = self.client.get("/openoapi/nslcm/v1/ns/vls/%s" % self.vl_inst_id) self.assertEqual(status.HTTP_200_OK, response.status_code) expect_resp_data = { 'vlId': self.vl_inst_id, 'vlName': self.vl_name, 'vlStatus': "active" } self.assertEqual(expect_resp_data, response.data) response = self.client.get("/openoapi/nslcm/v1/ns/vls/%s" % "notExist") self.assertEqual(status.HTTP_404_NOT_FOUND, response.status_code)
class ProjectTestCase(TestCase): def setUp(self): self.c = Client() self.UserModel = get_user_model() self.c.post('/auth/create', { 'username': '******', 'password': '******', 'email': 'email' }, content_type="application/json") response = self.c.post('/auth/', { 'username': '******', 'password': '******' }, content_type="application/json") access_token = json.loads(response.content.decode())['access_token'] self.c.defaults['HTTP_AUTHORIZATION'] = 'Bearer ' + access_token self.user = User.objects.get(username='******') def test_create_project(self): response = self.c.post('/ocr/project', { 'name': 'project1', 'comment': 'comment1' }, content_type="application/json") data = json.loads(response.content.decode()) project_id = data.get("id") project = Project.objects.filter(id=project_id).first() self.assertEqual(project.name, 'project1') self.assertEqual(project.comment, 'comment1') def test_update_project(self): # create project self.c.post('/ocr/project', { 'name': 'project1', 'comment': 'comment1' }, content_type="application/json") project_id = Project.objects.first().id self.c.put('/ocr/project/' + str(project_id), { 'name': 'project2', 'comment': 'comment2' }, content_type="application/json") project = Project.objects.filter(id=project_id).first() self.assertEqual(project.name, 'project2') self.assertEqual(project.comment, 'comment2') def test_list_projects(self): # create project self.c.post('/ocr/project', { 'name': 'project1', 'comment': 'comment1' }, content_type="application/json") response = self.c.get('/ocr/project', {}, content_type="application/json") data = json.loads(response.content.decode()) project = Project.objects.get(belong_to=self.user) res = data.get('projects')[0] self.assertEqual(res['id'], project.id) self.assertEqual(res['name'], project.name) self.assertEqual(res['comment'], project.comment) self.assertEqual(res['results_num'], project.recognitionresult_set.count()) self.assertEqual(data.get('project_num'), 1) def test_retrieve_project_detail(self): # create project self.c.post('/ocr/project', { 'name': 'project1', 'comment': 'comment1' }, content_type="application/json") project = Project.objects.first() project.recognitionresult_set.create(name='testresult', comment='resultcomment', result={}) result = project.recognitionresult_set.first() response = self.c.get('/ocr/project/' + str(project.id), {}, content_type="application/json") data = json.loads(response.content.decode()) self.assertEqual(data.get('name'), project.name) self.assertEqual(data.get('comment'), project.comment) self.assertEqual(data.get('result_num'), project.recognitionresult_set.count()) res = data.get('results')[0] self.assertEqual(res['id'], result.id) self.assertEqual(res['name'], result.name) self.assertEqual(res['comment'], result.comment) def test_remove_project(self): # create project self.c.post('/ocr/project', { 'name': 'project1', 'comment': 'comment1' }, content_type="application/json") self.assertEqual(Project.objects.count(), 1) project_id = Project.objects.first().id self.c.delete('/ocr/project/' + str(project_id), {}, content_type="application/json") self.assertEqual(Project.objects.count(), 0)
class UserActionsTest(TestCase): """ Тесты поведения пользователя """ @classmethod def setUpClass(cls): super().setUpClass() cls.user = UserFactory() cls.author = UserFactory() cls.recipe = RecipeWithIngredientFactory() def setUp(self): self.guest_client = Client() self.authorized_client = Client() self.authorized_client.force_login(UserActionsTest.user) def test_unathorized_client(self): urls = ["/feed/", "/new_recipe/", "/favorite/", "/get_purchases/"] for url in urls: with self.subTest(): response = self.guest_client.get(url) self.assertRedirects(response, f"/auth/login/?next={url}") def test_profile_page(self): response = self.authorized_client.get( reverse("profile_page", args={UserActionsTest.user.username})) self.assertEqual(response.status_code, 200) self.assertContains(response, f"{UserActionsTest.user.username}") def test_follow(self): data = {"id": f"{UserActionsTest.author.id}"} response = self.authorized_client.post(reverse("add_subscription"), data=data, content_type="application/json") self.assertEqual(response.status_code, 200) self.assertTrue( Follow.objects.filter(user=UserActionsTest.user, author=UserActionsTest.author).exists()) def test_follow_delete(self): data = {"id": f"{UserActionsTest.author.id}"} self.authorized_client.post(reverse("add_subscription"), data=data, content_type='application/json') response = self.authorized_client.delete( reverse("remove_subscription", args=[UserActionsTest.author.id]), content_type="application/json") self.assertEqual(response.status_code, 200) self.assertFalse( Follow.objects.filter(user=UserActionsTest.user, author=UserActionsTest.author).exists()) def test_favorite(self): data = {"id": f"{UserActionsTest.recipe.id}"} response = self.authorized_client.post(reverse("add_favorite"), data=data, content_type="application/json") self.assertEqual(response.status_code, 200) self.assertTrue( Favorite.objects.filter(user=UserActionsTest.user, recipe=UserActionsTest.recipe).exists()) def test_favorite_delete(self): data = {"id": f"{UserActionsTest.recipe.id}"} self.authorized_client.post(reverse("add_favorite"), data=data, content_type="application/json") response = self.authorized_client.delete( reverse("remove_favorite", args=[UserActionsTest.recipe.id]), content_type="application/json") self.assertEqual(response.status_code, 200) self.assertFalse( Favorite.objects.filter(user=UserActionsTest.user, recipe=UserActionsTest.recipe).exists())
class ConditionalTest(TestCase): def setUp(self): self.client = Client(enforce_csrf_checks=False) self.user = factories.UserFactory() self.element = factories.ElementFactory() self.token = Token.objects.get(user=self.user) self.conditional_url = '/api/conditionals' grant_permissions() def test_conditional_works(self): self.data = { 'page': self.element.page.pk, 'conditions': { 'node_type': 'NOT', 'children': [{ 'node_type': 'AND', 'children': [{ 'criteria_element': self.element.pk, 'node_type': 'EQUALS', 'value': 'foo' }, { 'criteria_element': self.element.pk, 'node_type': 'LESS', 'value': 'bar' }] }] } } response = self.get_response() assert_equals(response.status_code, status.HTTP_201_CREATED) body = json.loads(response.content) assert_equals(body['page'], self.data['page']) assert_true('conditions' in self.data) assert_equals(body['conditions'], self.data['conditions']) assert_equals(ShowIf.objects.count(), 1) def test_update(self): show_if = factories.ShowIfFactory() self.data = { 'page': show_if.page.pk, 'conditions': { 'criteria_element': self.element.pk, 'node_type': 'EQUALS', 'value': 'foo' } } response = self.client.put( path=self.conditional_url + '/{id}'.format(id=show_if.pk), data=json.dumps(self.data), content_type='application/json', HTTP_AUTHORIZATION=add_token_to_header(self.user, self.token)) assert_equals(response.status_code, status.HTTP_200_OK) body = json.loads(response.content) assert_equals(body['page'], self.data['page']) assert_true('conditions' in self.data) assert_equals(body['conditions'], self.data['conditions']) def test_delete(self): show_if = factories.ShowIfFactory() response = self.client.delete( path=self.conditional_url + '/{id}'.format(id=show_if.pk), content_type='application/json', HTTP_AUTHORIZATION=add_token_to_header(self.user, self.token)) assert_equals(response.status_code, status.HTTP_204_NO_CONTENT) assert_equals(ShowIf.objects.count(), 0) def test_invalid_node_type(self): self.data = { 'page': self.element.page.pk, 'conditions': { 'criteria_element': self.element.pk, 'node_type': 'FOO', 'value': 'foo' } } assert_equals(self.get_conditions(), ['Invalid node type "FOO"']) self.data = { 'page': self.element.page.pk, 'conditions': { 'criteria_element': self.element.pk, 'value': 'foo' } } assert_equals(self.get_conditions(), ['Missing or invalid node type']) def test_bad_criteria_node(self): self.data = { 'page': self.element.page.pk, 'conditions': { 'node_type': 'GREATER', 'value': 'foo', 'criteria_element': '' } } assert_equals(self.get_conditions(), ['CRITERIA criteria_element must be an integer']) self.data['conditions'] = { 'criteria_element': self.element.pk, 'node_type': 'EQUALS', 'value': [] } assert_equals(self.get_conditions(), ['CRITERIA value must be a string']) self.data['conditions'] = { 'criteria_element': self.element.pk, 'node_type': 'LESS', 'value': 'foo', 'children': [] } assert_equals(self.get_conditions(), ['CRITERIA node must have no children']) def test_bad_non_criteria_node(self): self.data = { 'page': self.element.page.pk, 'conditions': { 'node_type': 'AND', 'value': 'foo', 'children': [] } } assert_equals(self.get_conditions(), ['Only "CRITERIA" should have a value']) self.data = { 'page': self.element.page.pk, 'conditions': { 'node_type': 'AND', 'criteria_element': self.element.pk, 'children': [] } } assert_equals(self.get_conditions(), ['Only "CRITERIA" should have an element']) self.data = { 'page': self.element.page.pk, 'conditions': { 'node_type': 'AND' } } assert_equals(self.get_conditions(), ['Logical nodes must have children']) def test_number_of_children_for_not(self): self.data = { 'page': self.element.page.pk, 'conditions': { 'node_type': 'NOT', 'children': [{ 'criteria_element': self.element.pk, 'node_type': 'EQUALS', 'value': 'foo' }, { 'criteria_element': self.element.pk, 'node_type': 'LESS', 'value': 'bar' }] } } assert_equals(self.get_conditions(), ['NOT nodes must have exactly 1 child']) self.data = { 'page': self.element.page.pk, 'conditions': { 'node_type': 'NOT', 'children': [] } } assert_equals(self.get_conditions(), ['NOT nodes must have exactly 1 child']) def test_number_of_children_for_and_or(self): self.data = { 'page': self.element.page.pk, 'conditions': { 'node_type': 'OR', 'children': [] } } assert_equals(self.get_conditions(), ['AND and OR nodes must have at least 1 child']) def get_conditions(self): response = self.get_response() assert_equals(response.status_code, status.HTTP_400_BAD_REQUEST) body = json.loads(response.content) assert_true('conditions' in body) return body['conditions'] def get_response(self): return self.client.post(path=self.conditional_url, data=json.dumps(self.data), content_type='application/json', HTTP_AUTHORIZATION=add_token_to_header( self.user, self.token))
class TestView(TestCase): def setUp(self) -> None: self.client = Client() self.list_url = reverse('list') self.detail_url = reverse('detail', args=['project1']) self.project1 = Project.objects.create(name='project1', budget=10000) def test_project_list_GET(self): response = self.client.get(self.list_url) self.assertEquals(response.status_code, 200) self.assertTemplateUsed(response, 'budget/project-list.html') def test_project_detail_GET(self): response = self.client.get(self.detail_url) self.assertEquals(response.status_code, 200) self.assertTemplateUsed(response, 'budget/project-detail.html') def test_project_detail_POST_adds_new_expense(self): Category.objects.create(project=self.project1, name='development') response = self.client.post(self.detail_url, { 'title': 'expense1', 'amount': 1000, 'category': 'development' }) self.assertEquals(response.status_code, 302) self.assertEquals(self.project1.expenses.first().title, 'expense1') def test_project_detail_POST_no_data(self): Category.objects.create(project=self.project1, name='development') response = self.client.post(self.detail_url) self.assertEquals(response.status_code, 302) self.assertEquals(self.project1.expenses.count(), 0) def test_project_detail_DELETE_deletes_expense(self): category1 = Category.objects.create(project=self.project1, name='development') Expense.objects.create(project=self.project1, title='expense1', amount=1000, category=category1) response = self.client.delete(self.detail_url, json.dumps({'id': 1})) self.assertEquals(response.status_code, 204) self.assertEquals(self.project1.expenses.count(), 0) def test_project_detail_DELETE_no_id(self): category1 = Category.objects.create(project=self.project1, name='development') Expense.objects.create(project=self.project1, title='expense1', amount=1000, category=category1) response = self.client.delete(self.detail_url) self.assertEquals(response.status_code, 404) self.assertEquals(self.project1.expenses.count(), 1) def test_project_create_POST(self): url = reverse('add') response = self.client.post( url, { 'name': 'project2', 'budget': 5000, 'categoriesString': 'design, development' }) project2 = Project.objects.get(id=2) self.assertEquals(project2.name, 'project2')
def test_contact_localization(self): """ Contact Localization API """ req = Client() user = ContextUnitTest.create_user() user2 = ContextUnitTest.create_user(username='******', is_staff=True) contact_localization = ContactUnitTest.create_contact_localization() contact = contact_localization.contact # test if contact is locable by user contact_localization.is_lockable_by(user) # contact list url = reverse('unicms_api:contact-localizations', kwargs={'contact_id': contact.pk}) # accessible to staff users only res = req.get(url) assert res.status_code == 403 user.is_staff = True user.is_superuser = True user.save() req.force_login(user) res = req.get(url) assert isinstance(res.json(), dict) # POST data = { 'contact': contact.pk, 'language': 'en', 'name': 'posted name', 'is_active': 0 } # user hasn't permission req.force_login(user2) res = req.post(url, data=data, follow=1) assert res.status_code == 403 # user has permission req.force_login(user) # wrong contact contact_2 = ContactUnitTest.create_contact() data['contact'] = contact_2.pk res = req.post(url, data=data, follow=1) assert res.status_code == 400 # wrong contact data['contact'] = 11121 res = req.post(url, data=data, follow=1) assert res.status_code == 400 data['contact'] = contact.pk # wrong parent contact url = reverse('unicms_api:contact-localizations', kwargs={'contact_id': 12321321}) res = req.post(url, data=data, follow=1) assert res.status_code == 400 url = reverse('unicms_api:contact-localizations', kwargs={'contact_id': contact.pk}) res = req.post(url, data=data, follow=1) assert ContactLocalization.objects.filter(name='posted name').first() # GET LOGS url = reverse('unicms_api:contact-localization-logs', kwargs={ 'contact_id': contact.pk, 'pk': contact_localization.pk }) res = req.get( url, content_type='application/json', ) assert isinstance(res.json(), dict) # redis lock set ct = ContentType.objects.get_for_model(contact_localization) data = {'content_type_id': ct.pk, 'object_id': contact_localization.pk} res = req.post(url, data, content_type='application/json', follow=1) assert isinstance(res.json(), dict) # GET, patch, put, delete url = reverse('unicms_api:contact-localization', kwargs={ 'contact_id': contact.pk, 'pk': contact_localization.pk }) # GET res = req.get( url, content_type='application/json', ) assert isinstance(res.json(), dict) # PATCH # wrong parent contact data = {'contact': 11121} res = req.patch(url, data=data, content_type='application/json', follow=1) assert res.status_code == 400 # correct data data = {'name': 'patched'} # user hasn't permission req.force_login(user2) res = req.patch(url, data, content_type='application/json', follow=1) assert res.status_code == 403 # user has permission contact.created_by = user2 contact.save() content_type = ContentType.objects.get_for_model(Contact) edit_perm = Permission.objects.get(content_type=content_type, codename='change_contact') user2.user_permissions.add(edit_perm) user2.refresh_from_db() req.force_login(user2) res = req.patch(url, data, content_type='application/json', follow=1) contact_localization.refresh_from_db() assert contact_localization.name == 'patched' # PUT contact.created_by = None contact.save() data = { 'contact': contact.pk, 'language': 'en', 'name': 'putted name', 'is_active': 0 } # user hasn't permission req.force_login(user2) res = req.put(url, data, content_type='application/json') assert res.status_code == 403 # user has permission req.force_login(user) res = req.put(url, data, content_type='application/json') contact_localization.refresh_from_db() assert contact_localization.name == 'putted name' assert not contact_localization.is_active # DELETE # user hasn't permission req.force_login(user2) res = req.delete(url) assert res.status_code == 403 # user has permission req.force_login(user) res = req.delete(url) try: contact_localization.refresh_from_db() except ObjectDoesNotExist: assert True # form url = reverse('unicms_api:contact-localization-form', kwargs={'contact_id': contact.pk}) res = req.get(url) assert isinstance(res.json(), list)
class BlogTestCase(TestCase): def setUp(self): self.client = Client() # sign up self.client.post("/api/signup", json.dumps({ "username": "******", "password": "******" }), content_type="application/json") self.client.post("/api/signup", json.dumps({ "username": "******", "password": "******" }), content_type="application/json") def test_signup(self): # should reject non-post request response = self.client.get("/api/signup") self.assertEqual(response.status_code, 405) # should make new user response = self.client.post("/api/signup", json.dumps({ "username": "******", "password": "******" }), content_type="application/json") self.assertEqual(response.status_code, 201) def test_signin(self): # should reject non-post request response = self.client.get("/api/signin") self.assertEqual(response.status_code, 405) # should not be signed in with wrong information response = self.client.post("/api/signin", json.dumps({ "username": "******", "password": "******" }), content_type="application/json") self.assertEqual(response.status_code, 401) # should be signed in with proper information response = self.client.post("/api/signin", json.dumps({ "username": "******", "password": "******" }), content_type="application/json") self.assertEqual(response.status_code, 200) def test_signout(self): # should reject non-get request response = self.client.put("/api/signout") self.assertEqual(response.status_code, 405) # should be signed out at every case response = self.client.get("/api/signout") self.assertEqual(response.status_code, 200) def test_articles(self): # should reject non-logged in person response = self.client.get("/api/article") self.assertEqual(response.status_code, 401) # sign in self.client.post("/api/signin", json.dumps({ "username": "******", "password": "******" }), content_type="application/json") # should reject non-implemented methods response = self.client.put("/api/article") self.assertEqual(response.status_code, 405) # should post new article response = self.client.post("/api/article", json.dumps({ "title": "a1t", "content": "a1c", "author_id": 1 }), content_type="application/json") self.assertEqual(response.status_code, 201) # should get response response = self.client.get('/api/article') data = json.loads(response.content.decode())[0] self.assertEqual(data['title'], "a1t") self.assertEqual(data['content'], "a1c") self.assertEqual(data['author_id'], 1) def test_articles_id(self): # should reject non-logged in person response = self.client.get("/api/article/1") self.assertEqual(response.status_code, 401) # sign in self.client.post("/api/signin", json.dumps({ "username": "******", "password": "******" }), content_type="application/json") self.client.post("/api/article", json.dumps({ "title": "a1t", "content": "a1c", "author_id": 1 }), content_type="application/json") # should reject non-implemented methods response = self.client.post("/api/article/1") self.assertEqual(response.status_code, 405) # should get article response = self.client.get('/api/article/1') data = json.loads(response.content.decode()) self.assertEqual(data['title'], "a1t") self.assertEqual(data['content'], "a1c") self.assertEqual(data['author_id'], 1) # should not found non-existing article response = self.client.get('/api/article/2') self.assertEqual(response.status_code, 404) # can put article response = self.client.put("/api/article/1", json.dumps({ "title": "a1tc", "content": "a1cc", "author_id": 1 }), content_type="application/json") self.assertEqual(response.status_code, 200) response = self.client.get('/api/article/1') data = json.loads(response.content.decode()) self.assertEqual(data['title'], "a1tc") self.assertEqual(data['content'], "a1cc") self.assertEqual(data['author_id'], 1) # cannot put non-existing article response = self.client.put("/api/article/2", json.dumps({ "title": "a1tc", "content": "a1cc", "author_id": 1 }), content_type="application/json") self.assertEqual(response.status_code, 404) # cannot delete non-existing article response = self.client.delete("/api/article/2") self.assertEqual(response.status_code, 404) # can delete article response = self.client.delete("/api/article/1") self.assertEqual(response.status_code, 200) # cannot put when non-author self.client.post("/api/article", json.dumps({ "title": "a1ta", "content": "a1ca", "author_id": 1 }), content_type="application/json") self.client.get("/api/signout") self.client.post("/api/signin", json.dumps({ "username": "******", "password": "******" }), content_type="application/json") response = self.client.put("/api/article/2", json.dumps({ "title": "a1tc", "content": "a1cc", "author_id": 2 }), content_type="application/json") self.assertEqual(response.status_code, 403) # cannot remove when non-author response = self.client.delete("/api/article/2") self.assertEqual(response.status_code, 403) def test_articles_id_comment(self): # sign in self.client.post("/api/signin", json.dumps({ "username": "******", "password": "******" }), content_type="application/json") self.client.post("/api/article", json.dumps({ "title": "a1t", "content": "a1c", "author_id": 1 }), content_type="application/json") self.client.get("/api/signout") # should reject non-logged in person response = self.client.get("/api/article/1/comment") self.assertEqual(response.status_code, 401) # sign in self.client.post("/api/signin", json.dumps({ "username": "******", "password": "******" }), content_type="application/json") # should reject non-implemented methods response = self.client.put("/api/article/1/comment") self.assertEqual(response.status_code, 405) # cannot post if article doesn't exist response = self.client.post("/api/article/3/comment", json.dumps({ "article_id": 1, "content": "comment1", "author_id": 1 }), content_type="application/json") self.assertEqual(response.status_code, 404) # should post new comments response = self.client.post("/api/article/1/comment", json.dumps({ "article_id": 1, "content": "comment1", "author_id": 1 }), content_type="application/json") self.assertEqual(response.status_code, 201) # get comments response = self.client.get("/api/article/1/comment") data = json.loads(response.content.decode())[0] self.assertEqual(data["article_id"], 1) self.assertEqual(data["content"], "comment1") self.assertEqual(data["author_id"], 1) # get comments which doesn't exist response = self.client.get("/api/article/3/comment") self.assertEqual(response.status_code, 404) def test_comments_id(self): # should reject non-logged in person response = self.client.get("/api/comment/1") self.assertEqual(response.status_code, 401) # sign in self.client.post("/api/signin", json.dumps({ "username": "******", "password": "******" }), content_type="application/json") self.client.post("/api/article", json.dumps({ "title": "a1t", "content": "a1c", "author_id": 1 }), content_type="application/json") self.client.post("/api/article/1/comment", json.dumps({ "article_id": 1, "content": "comment1", "author_id": 1 }), content_type="application/json") # should reject non-implemented methods response = self.client.post("/api/comment/3") self.assertEqual(response.status_code, 405) # should get comment response = self.client.get('/api/comment/1') data = json.loads(response.content.decode()) self.assertEqual(data['article_id'], 1) self.assertEqual(data['content'], "comment1") self.assertEqual(data['author_id'], 1) # should not found non-existing comment response = self.client.get('/api/comment/2') self.assertEqual(response.status_code, 404) # can put comment response = self.client.put("/api/comment/1", json.dumps({ "article_id": 1, "content": "comment1c", "author_id": 1 }), content_type="application/json") self.assertEqual(response.status_code, 200) response = self.client.get('/api/comment/1') data = json.loads(response.content.decode()) self.assertEqual(data['article_id'], 1) self.assertEqual(data['content'], "comment1c") self.assertEqual(data['author_id'], 1) # cannot put non-existing comment response = self.client.put("/api/comment/3", json.dumps({ "article_id": 1, "content": "comment1c", "author_id": 1 }), content_type="application/json") self.assertEqual(response.status_code, 404) # cannot delete non-existing comment response = self.client.delete("/api/comment/3") self.assertEqual(response.status_code, 404) # can delete comment response = self.client.delete("/api/comment/1") self.assertEqual(response.status_code, 200) # cannot put when non-author self.client.post("/api/article", json.dumps({ "title": "a1ta", "content": "a1ca", "author_id": 1 }), content_type="application/json") self.client.post("/api/article/2/comment", json.dumps({ "article_id": 2, "content": "comment1a", "author_id": 1 }), content_type="application/json") self.client.get("/api/signout") self.client.post("/api/signin", json.dumps({ "username": "******", "password": "******" }), content_type="application/json") response = self.client.put("/api/comment/2", json.dumps({ "article_id": 2, "content": "comment1a", "author_id": 2 }), content_type="application/json") self.assertEqual(response.status_code, 403) # cannot remove when non-author response = self.client.delete("/api/comment/2") self.assertEqual(response.status_code, 403) def test_csrf(self): # should reject non-get request response = self.client.post("/api/token") self.assertEqual(response.status_code, 405) # By default, csrf checks are disabled in test client # To test csrf protection we enforce csrf checks here client = Client(enforce_csrf_checks=True) response = client.post('/api/signup', json.dumps({ 'username': '******', 'password': '******' }), content_type='application/json') self.assertEqual( response.status_code, 403) # Request without csrf token returns 403 response response = client.get('/api/token') csrftoken = response.cookies[ 'csrftoken'].value # Get csrf token from cookie response = client.post('/api/signup', json.dumps({ 'username': '******', 'password': '******' }), content_type='application/json', HTTP_X_CSRFTOKEN=csrftoken) self.assertEqual(response.status_code, 201) # Pass csrf protection
class AllocationTestCase(TestCase): """ test for Allocation """ def setUp(self): self.client = Client() self.user = User.objects.create(username="******", is_active=True, email="*****@*****.**") self.user.set_password('supersercret') for permission in Permission.objects.all(): self.user.user_permissions.add(permission) self.user.save() self.client.login(username="******", password="******") # create 用户类型 user_type = { "name": "医生", "description": "人机对战中AI对手,医生", } response = self.client.post('/api/v1/usertypes/', json.dumps(user_type), content_type='application/json') if response.status_code == 201: self.user_type = response.json() else: print(response.json()) model = { "profile": self.user.id, "type": self.user_type['id'], } response = self.client.post('/api/v1/profiles/', json.dumps(model), content_type='application/json') if response.status_code == 201: self.profile = response.json() else: print(response.json()) # create IMAGE image = { "name": "001.kfb", "path": "xx/xx/kfb", } response = self.client.post('/api/v1/images/', json.dumps(image), content_type='application/json') if response.status_code == 201: self.tiff = response.json() else: print(response.json()) model = { "profile": self.profile['id'], "tiff": self.tiff['id'], } response = self.client.post('/api/v1/missions/', json.dumps(model), content_type='application/json') if response.status_code == 201: self.model_id = response.json()['id'] else: print(response.json()) def test_model_get(self): response = self.client.get("/api/v1/missions/", ) self.assertEqual(response.status_code, 200, (response.json())) response = self.client.get( '/api/v1/missions/{}/'.format(self.model_id), ) self.assertEqual(response.status_code, 200, (response.json())) def test_model_post(self): model = { "profile": self.user.id, "tiff": self.tiff['id'], } response = self.client.post('/api/v1/missions/', json.dumps(model), content_type='application/json') self.assertEqual(response.status_code, 400, (response.json())) def test_model_patch(self): # create IMAGE image = { "name": "002.kfb", "path": "xx/xx/kfb", } response = self.client.post('/api/v1/images/', json.dumps(image), content_type='application/json') if response.status_code == 201: tiff = response.json() else: print(response.json()) response = self.client.patch('/api/v1/missions/{}/'.format( self.model_id), json.dumps({'tiff': tiff['id']}), content_type='application/json') self.assertEqual(response.status_code, 200, (response.json())) def test_model_delete(self): response = self.client.delete( '/api/v1/missions/{}/'.format(self.model_id), ) self.assertEqual(response.status_code, 204, response.content)
class TestViews(TestCase): def setUp(self): self.client = Client() self.user = User.objects.create_user(username='******', password='******') self.user_no_owner = User.objects.create_user(username='******', password='******') self.client.login(username='******', password='******') self.random_url = reverse('random') self.word_list_url = reverse('words-list') self.word_detail_url = reverse('words-detail', args={1}) self.list_attempts_url = reverse('attempts-list') self.detail_attempts_url = reverse('attempts-detail', args={1}) self.detail_attempts_no_owner_url = reverse('attempts-detail', args={2}) self.word = Word.objects.create(id=1, name='flatter') self.word_auxiliary = Word.objects.create(id=2, name='lurking') self.attempt_owner = Attempts.objects.create(user=self.user, word=self.word) self.attempt_no_owner = Attempts.objects.create( user=self.user_no_owner, word=self.word) self.content_type = 'application/json' def test_view_word_list_ok(self): response = self.client.get(self.word_list_url) self.assertEqual(response.status_code, 200) def test_view_word_detail_ok(self): response = self.client.get(self.word_detail_url) self.assertEqual(response.status_code, 200) def test_view_attempt_list_ok(self): response = self.client.get(self.list_attempts_url) self.assertEqual(response.status_code, 200) def test_view_attempt_detail_ok(self): response = self.client.get(self.detail_attempts_url) self.assertEqual(response.status_code, 200) self.assertEqual(response.data.__getitem__('word'), self.word.id) def test_view_attempt_detail_not_owner(self): response = self.client.get(self.detail_attempts_no_owner_url) self.assertEqual(response.status_code, 404) def test_view_attempt_successful_update(self): data = json.dumps({ 'word': 1, 'attempts': 0, 'hits': 0, 'success': True }) response = self.client.put(self.detail_attempts_url, data=data, content_type=self.content_type) self.assertEqual(response.status_code, 200) self.assertEqual(response.data.__getitem__('attempts'), 1) self.assertEqual(response.data.__getitem__('hits'), 1) def test_view_attempt_update_not_owner(self): data = json.dumps({ 'word': 1, 'attempts': 0, 'hits': 0, 'success': True }) response = self.client.put(self.detail_attempts_no_owner_url, data=data, content_type=self.content_type) self.assertEqual(response.status_code, 404) self.assertEqual(self.attempt_no_owner.attempts, 0) self.assertEqual(self.attempt_no_owner.hits, 0) def test_view_attempt_not_successful_update(self): data = json.dumps({ 'word': 1, 'attempts': 0, 'hits': 0, 'success': False }) response = self.client.put(self.detail_attempts_url, data=data, content_type=self.content_type) self.assertEqual(response.status_code, 200) self.assertEqual(response.data.__getitem__('attempts'), 1) self.assertEqual(response.data.__getitem__('hits'), 0) def test_view_attempt_bad_request(self): data = json.dumps({'word': 1, 'attempts': 0, 'hits': 0}) response = self.client.put(self.detail_attempts_url, data=data, content_type=self.content_type) self.assertEqual(response.status_code, 400) def test_view_attempt_post_not_allowed(self): data = json.dumps({'word': 1, 'user': 1, 'attempts': 0, 'hits': 0}) response = self.client.post(self.detail_attempts_url, data=data, content_type=self.content_type) self.assertEqual(response.status_code, 405) def test_view_attempt_delete_not_allowed(self): response = self.client.delete(self.detail_attempts_url) self.assertEqual(response.status_code, 405) def test_view_word_update_not_allowed(self): data = json.dumps({'id': self.word.id, 'name': self.word.name}) response = self.client.put(self.word_detail_url, data=data, content_type=self.content_type) self.assertEqual(response.status_code, 405) def test_view_word_delete_not_allowed(self): response = self.client.delete(self.word_detail_url) self.assertEqual(response.status_code, 405) def test_view_word_does_not_exists(self): data = json.dumps({'name': 'new word'}) response = self.client.post(self.word_list_url, data=data, content_type=self.content_type) self.assertEqual(response.data.__getitem__('name'), 'new word') self.assertEqual(response.status_code, 201) def test_view_word_create_exist_and_is_associated(self): data = json.dumps({'name': self.word.name}) response = self.client.post(self.word_list_url, data=data, content_type=self.content_type) self.assertEqual(response.data.__getitem__('name'), self.word.name) self.assertEqual(response.status_code, 201) def test_view_word_exist_attempt_does_not_exist(self): data = json.dumps({'name': self.word_auxiliary.name}) response = self.client.post(self.word_list_url, data=data, content_type=self.content_type) self.assertEqual(response.data.__getitem__('name'), self.word_auxiliary.name) self.assertEqual(response.status_code, 201) def test_word_creation_no_params(self): data = json.dumps({}) with self.assertRaises(KeyError): self.client.post(self.word_list_url, data=data, content_type=self.content_type) def test_get_random_word_no_login(self): self.client.logout() response = self.client.get(self.random_url) self.assertEqual(response.status_code, 403) def test_get_random_word_success(self): response = self.client.get(self.random_url) self.assertEqual(response.status_code, 200) def test_get_random_no_words(self): self.word.delete() response = self.client.get(self.random_url) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.data), 0)
def test_stock_report_views(self): ''' test_stock_report_views ''' client = Client(enforce_csrf_checks=True) stock_list = [] enddate = timezone.now().date() - timedelta(days=1) startdate = enddate - timedelta(days=30) duration = int(np.busday_count(startdate, enddate + timedelta(days=1))) # set first, second stock to failing stock_list.append( Stock.objects.create( title='foo_title', code='foo_code', sector='foo_sector', tradeVolume=1, score=30, )) stock_list.append( Stock.objects.create( title='foo_title', code='foo_code', sector='foo_sector', tradeVolume=1, score=70, )) # Create 100 stocks for i in range(100): stock_list.append( Stock.objects.create( title='foo_title', code='foo_code', sector='foo_sector', tradeVolume=1, score=50, )) # Create news objects for i in range(100): News.objects.create( stock=stock_list[i], date='2020-12-07', title='foo_title', press='foo_press', link='foo_link', ) testdate = timezone.now().date() - timedelta(days=2) # set first, second stock to failing StockHistory.objects.create( stock=stock_list[0], date=testdate, tradeVolume=1, endPrice=100, ) StockHistory.objects.create( stock=stock_list[1], date=testdate, tradeVolume=1, endPrice=100, ) # Create stockhistory objects for i in range(2, 102): for _ in range(duration): StockHistory.objects.create( stock=stock_list[i], date=testdate, tradeVolume=1, endPrice=100, ) # stock_top100_stockinfo response = client.get('/api/stocks/report/up/stockinfo/') self.assertEqual(response.status_code, 200) response = client.get('/api/users/token/') csrftoken = response.cookies['csrftoken'].value response = client.delete('/api/stocks/report/up/stockinfo/', HTTP_X_CSRFTOKEN=csrftoken) self.assertEqual(response.status_code, 405) # stock_top100_news response = client.get('/api/stocks/report/up/news/') self.assertEqual(response.status_code, 200) response = client.get('/api/users/token/') csrftoken = response.cookies['csrftoken'].value response = client.delete('/api/stocks/report/up/news/', HTTP_X_CSRFTOKEN=csrftoken) self.assertEqual(response.status_code, 405) # stock_top100_stockhistory response = client.get('/api/stocks/report/up/stockhistory/') self.assertEqual(response.status_code, 200) response = client.get('/api/users/token/') csrftoken = response.cookies['csrftoken'].value response = client.delete('/api/stocks/report/up/stockhistory/', HTTP_X_CSRFTOKEN=csrftoken) self.assertEqual(response.status_code, 405) # stock_bottom100_stockinfo response = client.get('/api/stocks/report/down/stockinfo/') self.assertEqual(response.status_code, 200) response = client.get('/api/users/token/') csrftoken = response.cookies['csrftoken'].value response = client.delete('/api/stocks/report/down/stockinfo/', HTTP_X_CSRFTOKEN=csrftoken) self.assertEqual(response.status_code, 405) # stock_bottom100_news response = client.get('/api/stocks/report/down/news/') self.assertEqual(response.status_code, 200) response = client.get('/api/users/token/') csrftoken = response.cookies['csrftoken'].value response = client.delete('/api/stocks/report/down/news/', HTTP_X_CSRFTOKEN=csrftoken) self.assertEqual(response.status_code, 405) # stock_bottom100_stockhistory response = client.get('/api/stocks/report/down/stockhistory/') self.assertEqual(response.status_code, 200) response = client.get('/api/users/token/') csrftoken = response.cookies['csrftoken'].value response = client.delete('/api/stocks/report/down/stockhistory/', HTTP_X_CSRFTOKEN=csrftoken) self.assertEqual(response.status_code, 405)
class MobileSurveyTests(ArchesTestCase): def setUp(self): mobile_survey = MobileSurvey() mobile_survey.name = "TEST MOBILE SURVEY" mobile_survey.description = "FOR TESTING" mobile_survey.active = True mobile_survey.createdby = User.objects.get(id=1) mobile_survey.lasteditedby = User.objects.get(id=1) mobile_survey.iconclass = "fa fa-building" mobile_survey.nodegroups = [] mobile_survey.datadownloadconfig = '{"download":false, "count":10, "resources":[], "custom":' '}' mobile_survey.id = '08960fb5-385b-11e8-add6-c4b301baab9f' mobile_survey.save() mobile_survey = MobileSurvey.objects.get(pk=mobile_survey.id) mobile_survey.save() self.mobile_survey = mobile_survey self.client = Client() with open( os.path.join( 'tests/fixtures/resource_graphs/Mobile Survey Test.json'), 'rU') as f: archesfile = JSONDeserializer().deserialize(f) ResourceGraphImporter(archesfile['graph']) BusinessDataImporter('tests/fixtures/data/mobile_survey_test_data.json' ).import_business_data() def tearDown(self): couch = couchdb.Server(settings.COUCHDB_URL) if 'project_08960fb5-385b-11e8-add6-c4b301baab9f' in couch: del couch['project_08960fb5-385b-11e8-add6-c4b301baab9f'] def post_mobile_survey(self, post_data): self.client.login(username='******', password='******') url = reverse('mobile_survey_manager') post_data = JSONSerializer().serialize(post_data) content_type = 'application/x-www-form-urlencoded' response = self.client.post(url, post_data, content_type) return json.loads(response.content) def test_create_mobile_survey(self): """ Test that creation of a mobile survey creates a corresponding couch database. """ post_data = { "datadownloadconfig": { "count": 1000, "download": True, "resources": [], "custom": "" }, "startdate": "2018-01-29", "tilecache": "", "enddate": "2018-03-30", "createdby_id": 1, "bounds": { "type": "FeatureCollection", "features": [] }, "cards": [], "lasteditedby_id": 1, "groups": [], "active": False, "users": [], "id": str(self.mobile_survey.id), "name": "test survey", "description": "a description" } response_json = self.post_mobile_survey(post_data) couch = couchdb.Server(settings.COUCHDB_URL) self.assertTrue(response_json['success']) self.assertTrue('project_' + str(self.mobile_survey.id) in couch) def test_load_couchdb(self): """ Test that resource instances and tiles load into a mobile survey's couchdb """ post_data = { "datadownloadconfig": { "count": 1000, "download": True, "resources": ['d84a098c-368b-11e8-bafc-c4b301baab9f'], "custom": "" }, "startdate": "2018-01-29", "tilecache": "", "enddate": "2018-03-30", "createdby_id": 1, "bounds": { "type": "FeatureCollection", "features": [] }, "cards": [ 'fe035187-368b-11e8-bf56-c4b301baab9f', '4215f135-369c-11e8-9544-c4b301baab9f' ], "lasteditedby_id": 1, "groups": [], "active": False, "users": [], "id": str(self.mobile_survey.id), "name": "test survey", "description": "a description" } response_json = self.post_mobile_survey(post_data) couch = couchdb.Server(settings.COUCHDB_URL) resources = 0 tiles = 0 if 'project_' + str(self.mobile_survey.id) in couch: db = couch['project_' + str(self.mobile_survey.id)] view = ViewDefinition('tests', 'all', '''function(doc) {emit(doc._id, null);}''') view.get_doc(db) view.sync(db) for item in db.view('_design/tests/_view/all', include_docs=True): if item.doc['type'] == 'tile': tiles += 1 if item.doc['type'] == 'resource': resources += 1 # tile_count = len(db.find({'selector': {'type': 'tile'}})) # resource_count = len(db.find({'selector': {'type': 'resource'}})) else: print '{0} is not in couch'.format('project_' + str(self.mobile_survey.id)) self.assertTrue(tiles == 2) self.assertTrue(resources == 1) def test_delete_mobile_survey(self): """ Test that deletion of a mobile survey deletes its couchdb """ self.client.login(username='******', password='******') url = reverse('mobile_survey_manager') post_data = {"id": str(self.mobile_survey.id)} post_data = JSONSerializer().serialize(post_data) content_type = 'application/x-www-form-urlencoded' response = self.client.delete(url, post_data, content_type) response_json = json.loads(response.content) couch = couchdb.Server(settings.COUCHDB_URL) self.assertFalse( MobileSurvey.objects.filter(pk=self.mobile_survey.id).exists()) self.assertTrue('project_' + str(self.mobile_survey.id) not in couch)
def test_invalid_delete_employee(self): client = Client() response = client.delete('delete', kwargs={'id': 4}) self.assertEqual(response.status_code, 404)
class TestViews(TestCase): def setUp(self): self.client = Client() self.posts_url = reverse('posts_add') self.postdel_url = reverse('posts_delete', args=[1]) self.posts1 = Posts.objects.create( name="Name", short_txt="Short txt", body_txt="Long txt", date=1, time=1, img="Image", imgurl="Img Url", author="Author", catname="Category", catid=1, ocatid=1, views=1, tag='Tag', act=1, rand=1 ) def test_postadd_POST(self): response = self.client.post(self.posts_url, { 'name': "Name", 'short_txt': "Short txt", 'body_txt': "Long txt", 'date': 1, 'time': 1, 'img': "Image", 'imgurl': "Img Url", 'author': "Author", 'catname': "Category", 'catid': 1, 'ocatid': 1, 'views': 1, 'tag': 'Tag', 'act': 1, 'rand':1 }) self.assertEquals(response.status_code, 302) self.assertEquals(self.posts1.name, 'Name') def test_postdel_DELETE(self): Posts.objects.create( name="Name", short_txt="Short txt", body_txt="Long txt", date=1, time=1, img="Image", imgurl="Img Url", author="Author", catname="Category", catid=1, ocatid=1, views=1, tag='Tag', act=1, rand=1 ) response = self.client.delete(self.postdel_url, json.dumps({ 'name': "Name", 'short_txt': "Short txt", 'body_txt': "Long txt", 'date': 1, 'time': 1, 'img': "Image", 'imgurl': "Img Url", 'author': "Author", 'catname': "Category", 'catid': 1, 'ocatid': 1, 'views': 1, 'tag': 'Tag', 'act': 1, 'rand':1 })) self.assertEquals(response.status_code, 302) self.assertEquals(self.posts1.name, 'Name')
def test_delete_subject(self): client = Client() client.login(username='******', password='******') response = client.delete('/subject/1') self.assertEqual(response.status_code, 200)
class TestControllerPerson(TransactionTestCase): reset_sequences = True maxDiff = None def setUp(self): self.client = Client() self.model_person_root = ModelPerson( parent_id=None, name='William Borba', cpf='00000000000', cnpj='00000000000', email='*****@*****.**', phone1='99123456789', phone2=None, ) self.model_person_root.save() token = str(uuid.uuid4()) self.model_login_root = ModelLogin( person=self.model_person_root, profile_id=ModelLogin.PROFILE_ROOT, username=self.model_person_root.email, password=123456, verified=True, token=token, ip='127.0.0.1', date_expired=datetime.datetime(3000, 1, 1), ) self.model_login_root.save() self.model_person_director = ModelPerson( parent=self.model_person_root, name='Director test', cpf='00000000002', cnpj='00000000000', email='*****@*****.**', phone1='99123456785', phone2=None, ) self.model_person_director.save() token = str(uuid.uuid4()) director_date_expired = datetime.datetime.now() + datetime.timedelta( days=30) self.model_login_director = ModelLogin( person=self.model_person_director, profile_id=ModelLogin.PROFILE_DIRECTOR, username=self.model_person_director.email, password=123456, verified=True, token=token, ip='127.0.0.8', date_expired=director_date_expired, ) self.model_login_director.save() self.model_person_client = ModelPerson( parent=self.model_person_director, name='Client de teste', cpf='00000000001', cnpj='00000000000', email='*****@*****.**', phone1='99123456782', phone2=None, ) self.model_person_client.save() token = str(uuid.uuid4()) self.model_login_client = ModelLogin( person=self.model_person_client, profile_id=ModelLogin.PROFILE_CLIENT, username=self.model_person_client.email, password=123456, verified=True, token=token, ip='127.0.0.9', date_expired=datetime.datetime.now() + datetime.timedelta(hours=24), ) self.model_login_client.save() def test_person_address_get_error(self): data_get = { 'address_id': '1234567890', 'person_id': '', 'state': '', 'city': '', 'number': '', 'complement': '', 'invoice': '', 'delivery': '', } response = self.client.get( '/api/v1/person/address/', data_get, REMOTE_ADDR='127.0.0.8', HTTP_API_KEY=self.model_login_director.token, ) self.assertEqual(response.status_code, 400) self.assertIsNotNone(response.json()) self.assertIsInstance(response.json(), dict) self.assertEqual( { 'message': 'Registro de endereço não encontrado![78]', }, response.json()) def test_person_address_get_ok(self): model_address = ModelAddress( person_id=self.model_person_client.person_id, state='RS', city='Porto Alegre', number=123, complement='Casa', invoice=True, delivery=True, ) model_address.save() data_get = { 'address_id': model_address.address_id, 'person_id': '', 'state': '', 'city': '', 'number': '', 'complement': '', 'invoice': '', 'delivery': '', } response = self.client.get( '/api/v1/person/address/', data_get, REMOTE_ADDR='127.0.0.8', HTTP_API_KEY=self.model_login_director.token, ) self.assertEqual(response.status_code, 200) self.assertIsNotNone(response.json()) self.assertIsInstance(response.json(), dict) self.assertEqual( { 'person_id': model_address.person_id, 'complement': model_address.complement, 'number': model_address.number, 'delivery': model_address.delivery, 'invoice': model_address.invoice, 'address_id': model_address.address_id, 'state': model_address.state, 'city': model_address.city }, response.json()) def test_person_address_filter_param_invoice_and_deliver_error(self): data_get = { 'address_id': '', 'person_id': '', 'state': '', 'city': '', 'number': '', 'complement': '', 'invoice': 'a', 'delivery': 'b', } response = self.client.get( '/api/v1/person/address/', data_get, REMOTE_ADDR='127.0.0.8', HTTP_API_KEY=self.model_login_director.token, ) self.assertEqual(response.status_code, 400) self.assertIsNotNone(response.json()) self.assertIsInstance(response.json(), dict) self.assertEqual({ 'message': 'Valor incorreto![55]', }, response.json()) def test_person_address_filter_empty_result(self): data_get = { 'address_id': '', 'person_id': '1', 'state': '1', 'city': '1', 'number': '1', 'complement': '1', 'invoice': '1', 'delivery': '1', } response = self.client.get( '/api/v1/person/address/', data_get, REMOTE_ADDR='127.0.0.8', HTTP_API_KEY=self.model_login_director.token, ) self.assertEqual(response.status_code, 200) self.assertIsNotNone(response.json()) self.assertIsInstance(response.json(), dict) self.assertEqual( { 'total': 0, 'has_next': False, 'count': 0, 'has_previous': False, 'limit': 20, 'data': [], 'num_pages': 1 }, response.json()) def test_person_address_filter_with_result(self): model_address_1 = ModelAddress( person_id=self.model_person_client.person_id, state='SP', city='São Paulo', number=321, complement='Apartamento', invoice=False, delivery=False, ) model_address_1.save() model_address_2 = ModelAddress( person_id=self.model_person_client.person_id, state='RS', city='Porto Alegre', number=123, complement='Casa', invoice=True, delivery=True, ) model_address_2.save() data_get = { 'address_id': '', 'person_id': self.model_person_client.person_id, 'state': '', 'city': '', 'number': '', 'complement': '', 'invoice': '', 'delivery': '', } response = self.client.get( '/api/v1/person/address/', data_get, REMOTE_ADDR='127.0.0.8', HTTP_API_KEY=self.model_login_director.token, ) self.assertEqual(response.status_code, 200) self.assertIsNotNone(response.json()) self.assertIsInstance(response.json(), dict) self.assertEqual( { 'total': 2, 'has_next': False, 'count': 2, 'has_previous': False, 'limit': 20, 'data': [{ 'address_id': model_address_2.address_id, 'person_id': model_address_2.person_id, 'number': model_address_2.number, 'state': model_address_2.state, 'complement': model_address_2.complement, 'city': model_address_2.city, 'delivery': model_address_2.delivery, 'invoice': model_address_2.invoice }, { 'address_id': model_address_1.address_id, 'person_id': model_address_1.person_id, 'number': model_address_1.number, 'state': model_address_1.state, 'complement': model_address_1.complement, 'city': model_address_1.city, 'delivery': model_address_1.delivery, 'invoice': model_address_1.invoice }], 'num_pages': 1 }, response.json()) def test_person_address_filter_with_pagination_error(self): model_address_1 = ModelAddress( person_id=self.model_person_client.person_id, state='SP', city='São Paulo', number=321, complement='Apartamento', invoice=False, delivery=False, ) model_address_1.save() model_address_2 = ModelAddress( person_id=self.model_person_client.person_id, state='RS', city='Porto Alegre', number=123, complement='Casa', invoice=True, delivery=True, ) model_address_2.save() data_get = { 'page': '3', 'limit': '1', 'address_id': '', 'person_id': self.model_person_client.person_id, 'state': '', 'city': '', 'number': '', 'complement': '', 'invoice': '', 'delivery': '', } response = self.client.get( '/api/v1/person/address/', data_get, REMOTE_ADDR='127.0.0.8', HTTP_API_KEY=self.model_login_director.token, ) self.assertEqual(response.status_code, 400) self.assertIsNotNone(response.json()) self.assertIsInstance(response.json(), dict) self.assertEqual({'message': 'Nenhum registro encontrado![80]'}, response.json()) def test_person_address_filter_with_pagination_ok(self): model_address_1 = ModelAddress( person_id=self.model_person_client.person_id, state='SP', city='São Paulo', number=321, complement='Apartamento', invoice=False, delivery=False, ) model_address_1.save() model_address_2 = ModelAddress( person_id=self.model_person_client.person_id, state='RS', city='Porto Alegre', number=123, complement='Casa', invoice=True, delivery=True, ) model_address_2.save() data_get = { 'page': '1', 'limit': '1', 'address_id': '', 'person_id': self.model_person_client.person_id, 'state': '', 'city': '', 'number': '', 'complement': '', 'invoice': '', 'delivery': '', } response = self.client.get( '/api/v1/person/address/', data_get, REMOTE_ADDR='127.0.0.8', HTTP_API_KEY=self.model_login_director.token, ) self.assertEqual(response.status_code, 200) self.assertIsNotNone(response.json()) self.assertIsInstance(response.json(), dict) self.assertEqual( { 'total': 2, 'has_next': True, 'count': 2, 'has_previous': False, 'limit': 1, 'data': [ { 'address_id': model_address_2.address_id, 'person_id': model_address_2.person_id, 'number': model_address_2.number, 'state': model_address_2.state, 'complement': model_address_2.complement, 'city': model_address_2.city, 'delivery': model_address_2.delivery, 'invoice': model_address_2.invoice }, ], 'num_pages': 2 }, response.json()) def test_person_address_add_person_id_error(self): data_post = { 'person_id': '', 'state': '', 'city': '', 'number': '', 'complement': '', 'invoice': '', 'delivery': '', } response = self.client.post( '/api/v1/person/address/', json.dumps(data_post), content_type='application/json', REMOTE_ADDR='127.0.0.8', HTTP_API_KEY=self.model_login_director.token, ) self.assertEqual(response.status_code, 400) self.assertIsNotNone(response.json()) self.assertIsInstance(response.json(), dict) self.assertEqual({'message': 'ID de pessoa não encontrado![78]'}, response.json()) def test_person_address_add_person_not_found(self): data_post = { 'person_id': '1234567890', 'state': '', 'city': '', 'number': '', 'complement': '', 'invoice': '', 'delivery': '', } response = self.client.post( '/api/v1/person/address/', json.dumps(data_post), content_type='application/json', REMOTE_ADDR='127.0.0.8', HTTP_API_KEY=self.model_login_director.token, ) self.assertEqual(response.status_code, 400) self.assertIsNotNone(response.json()) self.assertIsInstance(response.json(), dict) self.assertEqual({'message': 'Registro de pessoa não encontrado![68]'}, response.json()) def test_person_address_add_param_missing(self): data_post = { 'person_id': self.model_person_client.person_id, 'state': '', 'city': '', 'number': '', 'complement': '', 'invoice': '', 'delivery': '', } response = self.client.post( '/api/v1/person/address/', json.dumps(data_post), content_type='application/json', REMOTE_ADDR='127.0.0.8', HTTP_API_KEY=self.model_login_director.token, ) self.assertEqual(response.status_code, 400) self.assertIsNotNone(response.json()) self.assertIsInstance(response.json(), dict) self.assertEqual( {'message': 'Dados insuficientes para criação de endereço![43]'}, response.json()) def test_person_address_add_estate_error(self): data_post = { 'person_id': self.model_person_client.person_id, 'state': 'KK', 'city': 'Porto Alegre', 'number': '123', 'complement': '', 'invoice': 'qwert', 'delivery': 'gfdsa', } response = self.client.post( '/api/v1/person/address/', json.dumps(data_post), content_type='application/json', REMOTE_ADDR='127.0.0.8', HTTP_API_KEY=self.model_login_director.token, ) self.assertEqual(response.status_code, 400) self.assertIsNotNone(response.json()) self.assertIsInstance(response.json(), dict) self.assertEqual({'message': 'Sigla de estado incorreto![85]'}, response.json()) def test_person_address_add_invoice_and_delivery_error(self): data_post = { 'person_id': self.model_person_client.person_id, 'state': 'RS', 'city': 'Porto Alegre', 'number': '123', 'complement': '', 'invoice': '', 'delivery': '', } response = self.client.post( '/api/v1/person/address/', json.dumps(data_post), content_type='application/json', REMOTE_ADDR='127.0.0.8', HTTP_API_KEY=self.model_login_director.token, ) self.assertEqual(response.status_code, 400) self.assertIsNotNone(response.json()) self.assertIsInstance(response.json(), dict) self.assertEqual({'message': 'Valor incorreto![45]'}, response.json()) def test_person_address_add_invoice_and_delivery_error_2(self): data_post = { 'person_id': self.model_person_client.person_id, 'state': 'RS', 'city': 'Porto Alegre', 'number': '123', 'complement': '', 'invoice': 'qwert', 'delivery': 'gfdsa', } response = self.client.post( '/api/v1/person/address/', json.dumps(data_post), content_type='application/json', REMOTE_ADDR='127.0.0.8', HTTP_API_KEY=self.model_login_director.token, ) self.assertEqual(response.status_code, 400) self.assertIsNotNone(response.json()) self.assertIsInstance(response.json(), dict) self.assertEqual({'message': 'Valor incorreto![45]'}, response.json()) def test_person_address_add_error(self): model_address_1 = ModelAddress( person_id=self.model_person_client.person_id, state='SP', city='São Paulo', number=321, complement='Apartamento', invoice=False, delivery=False, ) model_address_1.save() model_address_2 = ModelAddress( person_id=self.model_person_client.person_id, state='RS', city='Porto Alegre', number=123, complement='Casa', invoice=True, delivery=True, ) model_address_2.save() data_post = { 'person_id': self.model_person_client.person_id, 'state': 'RS', 'city': 'Porto Alegre', 'number': '123', 'complement': 'Casa', 'invoice': '0', 'delivery': '0', } response = self.client.post( '/api/v1/person/address/', json.dumps(data_post), content_type='application/json', REMOTE_ADDR='127.0.0.8', HTTP_API_KEY=self.model_login_director.token, ) self.assertEqual(response.status_code, 400) self.assertIsNotNone(response.json()) self.assertIsInstance(response.json(), dict) self.assertEqual({'message': 'Endereço duplicado![46]'}, response.json()) def test_person_address_add_ok(self): model_address_1 = ModelAddress( person_id=self.model_person_client.person_id, state='SP', city='São Paulo', number=321, complement='Apartamento', invoice=False, delivery=False, ) model_address_1.save() model_address_2 = ModelAddress( person_id=self.model_person_client.person_id, state='RS', city='Porto Alegre', number=123, complement='Casa', invoice=True, delivery=True, ) model_address_2.save() data_post = { 'person_id': self.model_person_client.person_id, 'state': 'SC', 'city': 'Florianópolis', 'number': '123456', 'complement': 'Pousada', 'invoice': '1', 'delivery': '1', } response = self.client.post( '/api/v1/person/address/', json.dumps(data_post), content_type='application/json', REMOTE_ADDR='127.0.0.8', HTTP_API_KEY=self.model_login_director.token) self.assertEqual(response.status_code, 200) self.assertIsNotNone(response.json()) self.assertIsInstance(response.json(), dict) self.assertEqual( { 'complement': data_post['complement'], 'state': data_post['state'], 'invoice': True, 'person_id': response.json()['person_id'], 'delivery': True, 'city': data_post['city'], 'address_id': response.json()['address_id'], 'number': data_post['number'] }, response.json()) self.assertEqual( ModelAddress.objects.filter(address_id=model_address_1.address_id, invoice=False, delivery=False).count(), 1) self.assertEqual( ModelAddress.objects.filter(address_id=model_address_2.address_id, invoice=False, delivery=False).count(), 1) def test_person_address_update_address_id_missing(self): data_post = { 'address_id': '', 'state': '', 'city': '', 'number': '', 'complement': '', 'invoice': '', 'delivery': '', } response = self.client.put( '/api/v1/person/address/', json.dumps(data_post), content_type='application/json', REMOTE_ADDR='127.0.0.8', HTTP_API_KEY=self.model_login_director.token) self.assertEqual(response.status_code, 400) self.assertIsNotNone(response.json()) self.assertIsInstance(response.json(), dict) self.assertEqual({'message': 'ID de endereço não encontrado![82]'}, response.json()) def test_person_address_update_address_not_find(self): data_post = { 'address_id': '1234567890', 'state': '', 'city': '', 'number': '', 'complement': '', 'invoice': '', 'delivery': '', } response = self.client.put( '/api/v1/person/address/', json.dumps(data_post), content_type='application/json', REMOTE_ADDR='127.0.0.8', HTTP_API_KEY=self.model_login_director.token) self.assertEqual(response.status_code, 400) self.assertIsNotNone(response.json()) self.assertIsInstance(response.json(), dict) self.assertEqual({'message': 'Endereço não encontrado![50]'}, response.json()) def test_person_address_update_param_missing(self): model_address_1 = ModelAddress( person_id=self.model_person_client.person_id, state='SP', city='São Paulo', number=321, complement='Apartamento', invoice=False, delivery=False, ) model_address_1.save() data_post = { 'address_id': model_address_1.address_id, 'state': '', 'city': '', 'number': '', 'complement': '', 'invoice': '', 'delivery': '', } response = self.client.put( '/api/v1/person/address/', json.dumps(data_post), content_type='application/json', REMOTE_ADDR='127.0.0.8', HTTP_API_KEY=self.model_login_director.token) self.assertEqual(response.status_code, 400) self.assertIsNotNone(response.json()) self.assertIsInstance(response.json(), dict) self.assertEqual({'message': 'Nenhum dado para alterar![47]'}, response.json()) def test_person_address_update_param_estate_error(self): model_address_1 = ModelAddress( person_id=self.model_person_client.person_id, state='SP', city='São Paulo', number=321, complement='Apartamento', invoice=False, delivery=False, ) model_address_1.save() data_post = { 'address_id': model_address_1.address_id, 'state': 'KK', 'city': 'Porto Alegre', 'number': '134567890', 'complement': 'Apartamento', 'invoice': 'error', 'delivery': '1', } response = self.client.put( '/api/v1/person/address/', json.dumps(data_post), content_type='application/json', REMOTE_ADDR='127.0.0.8', HTTP_API_KEY=self.model_login_director.token) self.assertEqual(response.status_code, 400) self.assertIsNotNone(response.json()) self.assertIsInstance(response.json(), dict) self.assertEqual({'message': 'Sigla de estado incorreto![84]'}, response.json()) def test_person_address_update_param_invoice_or_delivery_error(self): model_address_1 = ModelAddress( person_id=self.model_person_client.person_id, state='SP', city='São Paulo', number=321, complement='Apartamento', invoice=False, delivery=False, ) model_address_1.save() data_post = { 'address_id': model_address_1.address_id, 'state': 'RS', 'city': 'Porto Alegre', 'number': '134567890', 'complement': 'Apartamento', 'invoice': 'error', 'delivery': '1', } response = self.client.put( '/api/v1/person/address/', json.dumps(data_post), content_type='application/json', REMOTE_ADDR='127.0.0.8', HTTP_API_KEY=self.model_login_director.token) self.assertEqual(response.status_code, 400) self.assertIsNotNone(response.json()) self.assertIsInstance(response.json(), dict) self.assertEqual({'message': 'Valor incorreto![48]'}, response.json()) def test_person_address_update_ok(self): model_address_1 = ModelAddress( person_id=self.model_person_client.person_id, state='SP', city='São Paulo', number=321, complement='Apartamento', invoice=False, delivery=False, ) model_address_1.save() data_post = { 'address_id': model_address_1.address_id, 'state': 'RS', 'city': 'Porto Alegre', 'number': '134567890', 'complement': 'Apartamento', 'invoice': '1', 'delivery': '1', } response = self.client.put( '/api/v1/person/address/', json.dumps(data_post), content_type='application/json', REMOTE_ADDR='127.0.0.8', HTTP_API_KEY=self.model_login_director.token) self.assertEqual(response.status_code, 200) self.assertIsNotNone(response.json()) self.assertIsInstance(response.json(), dict) self.assertEqual( { 'complement': data_post['complement'], 'address_id': data_post['address_id'], 'city': data_post['city'], 'state': data_post['state'], 'delivery': True, 'number': data_post['number'], 'person_id': model_address_1.person_id, 'invoice': True }, response.json()) self.assertEqual( ModelAddress.objects.filter(address_id=model_address_1.address_id, invoice=True, delivery=True).count(), 1) def test_person_address_delete_address_id_missing(self): data_delete = { 'address_id': '', } response = self.client.delete( '/api/v1/person/address/', json.dumps(data_delete), content_type='application/json', REMOTE_ADDR='127.0.0.8', HTTP_API_KEY=self.model_login_director.token) self.assertEqual(response.status_code, 400) self.assertIsNotNone(response.json()) self.assertIsInstance(response.json(), dict) self.assertEqual({'message': 'ID de endereço não encontrado![86]'}, response.json()) def test_person_address_delete_address_not_found(self): data_delete = { 'address_id': '1234567890', } response = self.client.delete( '/api/v1/person/address/', json.dumps(data_delete), content_type='application/json', REMOTE_ADDR='127.0.0.8', HTTP_API_KEY=self.model_login_director.token) self.assertEqual(response.status_code, 400) self.assertIsNotNone(response.json()) self.assertIsInstance(response.json(), dict) self.assertEqual({'message': 'Endereço não encontrado![51]'}, response.json()) def test_person_address_delete_invoice_error(self): model_address_1 = ModelAddress( person_id=self.model_person_client.person_id, state='SP', city='São Paulo', number=321, complement='Apartamento', invoice=True, delivery=False, ) model_address_1.save() data_delete = { 'address_id': model_address_1.address_id, } response = self.client.delete( '/api/v1/person/address/', json.dumps(data_delete), content_type='application/json', REMOTE_ADDR='127.0.0.8', HTTP_API_KEY=self.model_login_director.token) self.assertEqual(response.status_code, 400) self.assertIsNotNone(response.json()) self.assertIsInstance(response.json(), dict) self.assertEqual( { 'message': 'Não é possível remover endereço de cobrança ou entrega![52]' }, response.json()) def test_person_address_delete_delivery_error(self): model_address_1 = ModelAddress( person_id=self.model_person_client.person_id, state='SP', city='São Paulo', number=321, complement='Apartamento', invoice=False, delivery=False, ) model_address_1.save() model_address_2 = ModelAddress( person_id=self.model_person_client.person_id, state='RS', city='Porto Alegre', number=123, complement='Casa', invoice=False, delivery=True, ) model_address_2.save() data_delete = { 'address_id': model_address_2.address_id, } response = self.client.delete( '/api/v1/person/address/', json.dumps(data_delete), content_type='application/json', REMOTE_ADDR='127.0.0.8', HTTP_API_KEY=self.model_login_director.token) self.assertEqual(response.status_code, 400) self.assertIsNotNone(response.json()) self.assertIsInstance(response.json(), dict) self.assertEqual( { 'message': 'Não é possível remover endereço de entrega ou cobrança![53]' }, response.json()) def test_person_address_delete_ok(self): model_address_1 = ModelAddress( person_id=self.model_person_client.person_id, state='SP', city='São Paulo', number=321, complement='Apartamento', invoice=False, delivery=False, ) model_address_1.save() model_address_2 = ModelAddress( person_id=self.model_person_client.person_id, state='RS', city='Porto Alegre', number=123, complement='Casa', invoice=False, delivery=False, ) model_address_2.save() data_delete = { 'address_id': model_address_2.address_id, } response = self.client.delete( '/api/v1/person/address/', json.dumps(data_delete), content_type='application/json', REMOTE_ADDR='127.0.0.8', HTTP_API_KEY=self.model_login_director.token) self.assertEqual(response.status_code, 200) self.assertIsNotNone(response.json()) self.assertIsInstance(response.json(), dict) self.assertEqual({'result': True}, response.json()) self.assertEqual(ModelAddress.objects.filter().count(), 1)
def test_api_root_default_ok( lti_path, lti_launch_url, course_user_lti_launch_params, assignment_target_factory, annotatorjs_annotation_factory, catchpy_search_result_shell, ): """webannotation api, redirected to the default annotatorjs api.""" # 1. create course, assignment, target_object, user course, user, launch_params = course_user_lti_launch_params assignment_target = assignment_target_factory(course) target_object = assignment_target.target_object assignment = assignment_target.assignment assignment.save() # 2. set starting resource resource_link_id = launch_params["resource_link_id"] resource_config = LTIResourceLinkConfig.objects.create( resource_link_id=resource_link_id, assignment_target=assignment_target, ) # 3. lti launch client = Client(enforce_csrf_checks=False) response = client.post( lti_path, data=launch_params, ) assert response.status_code == 302 # set responses to assert annojs = annotatorjs_annotation_factory(user) annojs_id = uuid.uuid4().int search_result = catchpy_search_result_shell search_result["total"] = 1 search_result["size"] = 1 search_result["rows"].append(annojs) annotation_store_urls = {} for op in ["create", "search"]: annotation_store_urls[op] = "{}/{}".format( assignment.annotation_database_url, op) for op in ["update", "delete"]: annotation_store_urls[op] = "{}/{}/{}".format( assignment.annotation_database_url, op, annojs_id) responses.add( responses.POST, annotation_store_urls["create"], json=annojs, status=200, ) responses.add( responses.POST, annotation_store_urls["update"], json=annojs, status=200, ) responses.add( responses.DELETE, annotation_store_urls["delete"], json=annojs, status=200, ) responses.add( responses.GET, annotation_store_urls["search"], json=search_result, status=200, ) path = reverse("annotation_store:api_root_prefix") # search request response = client.get( "{}?resource_link_id={}".format(path, resource_link_id), HTTP_X_ANNOTATOR_AUTH_TOKEN="hahaha", ) assert response.status_code == 200 content = json.loads(response.content.decode()) assert len(responses.calls) == 1 assert content == search_result # create request response = client.post( "{}/{}?resource_link_id={}".format(path, annojs_id, resource_link_id), data=annojs, content_type="application/json", HTTP_X_ANNOTATOR_AUTH_TOKEN="hohoho", ) assert response.status_code == 200 content = json.loads(response.content.decode()) assert len(responses.calls) == 2 assert content == annojs # update request path_with_id = "{}/{}".format(path, annojs_id) response = client.put( path_with_id, data=annojs, content_type="application/json", HTTP_X_ANNOTATOR_AUTH_TOKEN="hihihi", ) assert response.status_code == 200 content = json.loads(response.content.decode()) assert len(responses.calls) == 3 assert content == annojs # delete request response = client.delete( path_with_id, HTTP_X_ANNOTATOR_AUTH_TOKEN="hehehe", ) assert response.status_code == 200 content = json.loads(response.content.decode()) assert len(responses.calls) == 4 assert content == annojs
def test_api_root_backend_from_request_ok( lti_path, lti_launch_url, course_user_lti_launch_params, assignment_target_factory, annotatorjs_annotation_factory, catchpy_search_result_shell, ): """webannotation api, configured from client search request.""" # 1. create course, assignment, target_object, user course, user, launch_params = course_user_lti_launch_params assignment_target = assignment_target_factory(course) target_object = assignment_target.target_object assignment = assignment_target.assignment # assignment.annotation_database_url = 'http://funky.com' # assignment.annotation_database_apikey = 'funky_key' # assignment.annotation_database_secret_token = 'funky_secret' assignment.save() # 2. set starting resource resource_link_id = launch_params["resource_link_id"] resource_config = LTIResourceLinkConfig.objects.create( resource_link_id=resource_link_id, assignment_target=assignment_target, ) # 3. lti launch client = Client(enforce_csrf_checks=False) response = client.post( lti_path, data=launch_params, ) assert response.status_code == 302 assert response.cookies.get("sessionid") expected_url = (reverse( "hx_lti_initializer:access_annotation_target", args=[course.course_id, assignment.assignment_id, target_object.pk], ) + f"?resource_link_id={resource_link_id}" + f"&utm_source={client.session.session_key}") assert response.url == expected_url # 4. access target object to be able to create annotations on it # this is required after live-updates implementation! response = client.get(expected_url) assert (response.status_code) == 200 # set responses to assert # TODO: if using webannotation api, should send webannotation format annojs = annotatorjs_annotation_factory(user) annojs_id = uuid.uuid4().int search_result = catchpy_search_result_shell search_result["total"] = 1 search_result["size"] = 1 search_result["rows"].append(annojs) annotation_store_urls = {} for op in ["search"]: annotation_store_urls[op] = "{}".format( assignment.annotation_database_url, ) for op in ["create", "update", "delete"]: annotation_store_urls[op] = "{}/{}".format( assignment.annotation_database_url, annojs_id) responses.add( responses.POST, annotation_store_urls["create"], json=annojs, status=200, ) responses.add( responses.PUT, annotation_store_urls["update"], json=annojs, status=200, ) responses.add( responses.DELETE, annotation_store_urls["delete"], json=annojs, status=200, ) responses.add( responses.GET, annotation_store_urls["search"], json=search_result, status=200, ) path = reverse("annotation_store:api_root_prefix") # search request response = client.get( "{}?version=catchpy&resource_link_id={}".format( path, resource_link_id), HTTP_X_ANNOTATOR_AUTH_TOKEN="hahaha", ) assert response.status_code == 200 content = json.loads(response.content.decode()) assert len(responses.calls) == 1 assert content == search_result # create request response = client.post( "{}/{}?version=catchpy&resource_link_id={}".format( path, annojs_id, resource_link_id), data=annojs, content_type="application/json", HTTP_X_ANNOTATOR_AUTH_TOKEN="hehehe", ) assert response.status_code == 200 content = json.loads(response.content.decode()) assert len(responses.calls) == 2 assert content == annojs # update request path_with_id = "{}/{}?version=catchpy&resource_link_id={}".format( path, annojs_id, resource_link_id) response = client.put( path_with_id, data=annojs, content_type="application/json", HTTP_X_ANNOTATOR_AUTH_TOKEN="hihihi", ) assert response.status_code == 200 content = json.loads(response.content.decode()) assert len(responses.calls) == 3 assert content == annojs # delete request response = client.delete( path_with_id, HTTP_X_ANNOTATOR_AUTH_TOKEN="hohoho", ) assert response.status_code == 200 content = json.loads(response.content.decode()) assert len(responses.calls) == 4 assert content == annojs