def create_asset( *, item=None, title="Test Asset", slug="test-asset", media_type=MediaType.IMAGE, media_url="1.jpg", published=True, do_save=True, **kwargs, ): if item is None: item = create_item() asset = Asset( item=item, title=title, slug=slug, media_type=media_type, published=published, media_url=media_url, **kwargs, ) asset.full_clean() if do_save: asset.save() return asset
class ViewTest_Concordia(TestCase): """ This class contains the unit tests for the view in the concordia app. Make sure the postgresql db is available. Run docker-compose up db """ def setUp(self): """ setUp is called before the execution of each test below :return: """ self.client = Client() def login_user(self): """ Create a user and log the user in :return: """ # create user and login self.user = User.objects.create(username="******", email="*****@*****.**") self.user.set_password("top_secret") self.user.save() login = self.client.login(username="******", password="******") def test_concordia_api(self): """ Test the tracribr_api. Provide a mock of requests :return: """ # Arrange relative_path = Mock() with patch("views.requests") as mock_requests: mock_requests.get.return_value = mock_response = Mock() mock_response.status_code = 200 mock_response.json.return_value = {"concordia_data": "abc123456"} # Act results = views.concordia_api("relative_path") # Assert self.assertEqual(results["concordia_data"], "abc123456") def test_AccountProfileView_get(self): """ Test the http GET on route account/profile :return: """ # Arrange self.login_user() # create a collection self.collection = Collection( title="TextCollection", slug="www.foo.com/slug2", description="Collection Description", metadata={"key": "val1"}, status=Status.PCT_0, ) self.collection.save() # create an Asset self.asset = Asset( title="TestAsset", slug="www.foo.com/slug1", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, collection=self.collection, metadata={"key": "val2"}, status=Status.PCT_0, ) self.asset.save() # add a Transcription object self.transcription = Transcription( asset=self.asset, user_id=self.user.id, status=Status.PCT_0 ) self.transcription.save() # Act response = self.client.get("/account/profile/") # Assert # validate the web page has the "tester" and "*****@*****.**" as values self.assertTrue('value="tester"' in str(response.content)) self.assertTrue('value="*****@*****.**"' in str(response.content)) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, template_name="profile.html") def test_AccountProfileView_post(self): """ This unit test tests the post entry for the route account/profile :param self: :return: """ # Arrange self.login_user() # Act response = self.client.post( "/account/profile/", { "first_name": "Jimmy", "email": "*****@*****.**", "username": "******", "password1": "", "password2": "", }, ) # Assert self.assertEqual(response.status_code, 302) self.assertEqual(response.url, "/account/profile/") # Verify the User was correctly updated updated_user = User.objects.get(id=self.user.id) self.assertEqual(updated_user.first_name, "Jimmy") def test_AccountProfileView_post_invalid_form(self): """ This unit test tests the post entry for the route account/profile but submits an invalid form :param self: :return: """ # Arrange self.login_user() # Act response = self.client.post("/account/profile/", {"first_name": "Jimmy"}) # Assert self.assertEqual(response.status_code, 302) self.assertEqual(response.url, "/account/profile/") # Verify the User was not changed updated_user = User.objects.get(id=self.user.id) self.assertEqual(updated_user.first_name, "") def test_AccountProfileView_post_new_password(self): """ This unit test test the post entry for the route account/profile with new password :param self: :return: """ # Arrange self.login_user() # Act response = self.client.post( "/account/profile/", { "first_name": "Jimmy", "email": "*****@*****.**", "username": "******", "password1": "abc", "password2": "abc", }, ) # Assert self.assertEqual(response.status_code, 302) self.assertEqual(response.url, "/account/profile/") # Verify the User was correctly updated updated_user = User.objects.get(id=self.user.id) self.assertEqual(updated_user.first_name, "Jimmy") # logout and login with new password logout = self.client.logout() login2 = self.client.login(username="******", password="******") self.assertTrue(login2) def test_AccountProfileView_post_with_image(self): """ This unit test tests the post entry for the route account/profile with new image file :param self: :return: """ # Arrange self.login_user() existing_userprofile_count = UserProfile.objects.all().count() # Act image = Image.new("RGBA", size=(50, 50), color=(155, 0, 0)) file = tempfile.NamedTemporaryFile(suffix=".png") image.save(file) with open(file.name, encoding="ISO-8859-1") as fp: response = self.client.post( "/account/profile/", { "myfile": fp, "first_name": "Jimmy", "email": "*****@*****.**", "username": "******", "password1": "", "password2": "", }, ) # Assert self.assertEqual(response.status_code, 302) self.assertEqual(response.url, "/account/profile/") # Verify the UserProfile was correctly updated, a new entry in db exists profile = UserProfile.objects.all() self.assertEqual(len(profile), existing_userprofile_count + 1) @patch("concordia.views.requests") def test_concordiaView(self, mock_requests): """ Test the GET method for route /transcribe :return: """ # Arrange mock_requests.get.return_value.status_code = 200 mock_requests.get.return_value.json.return_value = { "concordia_data": "abc123456" } # Act response = self.client.get("/transcribe/") # Assert self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, template_name="transcriptions/home.html") def test_concordiaCollectionView_get(self): """ Test GET on route /transcribe/<slug-value> (collection) :return: """ # Arrange # add an item to Collection self.collection = Collection( title="TextCollection", slug="test-slug2", description="Collection Description", metadata={"key": "val1"}, status=Status.PCT_0, ) self.collection.save() # Act response = self.client.get("/transcribe/test-slug2/") # Assert self.assertEqual(response.status_code, 200) self.assertTemplateUsed( response, template_name="transcriptions/collection.html" ) def test_concordiaCollectionView_get_page2(self): """ Test GET on route /transcribe/<slug-value>/ (collection) on page 2 :return: """ # Arrange # add an item to Collection self.collection = Collection( title="TextCollection", slug="test-slug2", description="Collection Description", metadata={"key": "val1"}, status=Status.PCT_0, ) self.collection.save() # Act response = self.client.get("/transcribe/test-slug2/", {"page": 2}) # Assert self.assertEqual(response.status_code, 200) self.assertTemplateUsed( response, template_name="transcriptions/collection.html" ) def test_ExportCollectionView_get(self): """ Test GET route /transcribe/export/<slug-value>/ (collection) :return: """ # Arrange self.collection = Collection( title="TextCollection", slug="slug2", description="Collection Description", metadata={"key": "val1"}, status=Status.PCT_0, ) self.collection.save() self.asset = Asset( title="TestAsset", slug="test-slug2", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, collection=self.collection, metadata={"key": "val2"}, status=Status.PCT_0, ) self.asset.save() # Act response = self.client.get("/transcribe/export/slug2/") # Assert self.assertEqual(response.status_code, 200) self.assertEqual( str(response.content), "b'Collection,Title,Description,MediaUrl,Transcription,Tags\\r\\nTextCollection,TestAsset,Asset Description,http://www.foo.com/1/2/3,,\\r\\n'", ) def test_DeleteCollection_get(self): """ Test GET route /transcribe/delete/<slug-value>/ (collection) :return: """ # Arrange # add an item to Collection self.collection = Collection( title="TextCollection", slug="test-slug2", description="Collection Description", metadata={"key": "val1"}, status=Status.PCT_0, ) self.collection.save() self.asset = Asset( title="TestAsset", slug="test-slug2", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, collection=self.collection, metadata={"key": "val2"}, status=Status.PCT_0, ) self.asset.save() # Act response = self.client.get("/transcribe/delete/test-slug2", follow=True) # Assert self.assertEqual(response.status_code, 200) # verify the collection is not in db collection2 = Collection.objects.all() self.assertEqual(len(collection2), 0)
class ViewTest_Concordia(TestCase): """ This class contains the unit tests for the view in the concordia app. Make sure the postgresql db is available. Run docker-compose up db """ def setUp(self): """ setUp is called before the execution of each test below :return: """ self.client = Client() def login_user(self): """ Create a user and log the user in :return: """ # create user and login self.user = User.objects.create(username="******", email="*****@*****.**") self.user.set_password("top_secret") self.user.save() self.client.login(username="******", password="******") def test_get_anonymous_user(self): """ Test getting the anonymous user. Test the naonymous user does exist, the call get_anonymous_user, make anonymous is created :return: """ # Arrange anon_user1 = User.objects.filter(username="******").first() # Act anon_user_id = views.get_anonymous_user() anon_user_from_db = User.objects.filter(username="******").first() # Assert self.assertEqual(anon_user1, None) self.assertEqual(anon_user_id, anon_user_from_db.id) def test_get_anonymous_user_already_exists(self): """ Test getting the anonymous user when it already exists. :return: """ # Arrange anon_user = User.objects.create_user( username="******", email="*****@*****.**", password="******", ) # Act anon_user_id = views.get_anonymous_user() # Assert self.assertEqual(anon_user_id, anon_user.id) def test_concordia_api(self): """ Test the tracribr_api. Provide a mock of requests :return: """ # Arrange with patch("views.requests") as mock_requests: mock_requests.get.return_value = mock_response = Mock() mock_response.status_code = 200 mock_response.json.return_value = {"concordia_data": "abc123456"} # Act results = views.concordia_api("relative_path") # Assert self.assertEqual(results["concordia_data"], "abc123456") def test_login_with_email(self): """ Test the login is successful with email :return: """ # Arrange user = User.objects.create(username="******", email="*****@*****.**") user.set_password("top_secret") user.save() # Act user = self.client.login(username="******", password="******") # Assert self.assertTrue(user) def test_AccountProfileView_get(self): """ Test the http GET on route account/profile :return: """ # Arrange self.login_user() # create a collection self.collection = Collection( title="TextCollection", slug="www.foo.com/slug2", description="Collection Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.collection.save() # create an Asset self.asset = Asset( title="TestAsset", slug="www.foo.com/slug1", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, collection=self.collection, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset.save() # add a Transcription object self.transcription = Transcription(asset=self.asset, user_id=self.user.id, status=Status.EDIT) self.transcription.save() # Act response = self.client.get("/account/profile/") # Assert # validate the web page has the "tester" and "*****@*****.**" as values self.assertTrue('value="tester"' in str(response.content)) self.assertTrue('value="*****@*****.**"' in str(response.content)) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, template_name="profile.html") def test_AccountProfileView_post(self): """ This unit test tests the post entry for the route account/profile :param self: :return: """ test_email = "*****@*****.**" # Arrange self.login_user() # Act response = self.client.post( "/account/profile/", { "email": test_email, "username": "******", "password1": "!Abc12345", "password2": "!Abc12345", }, ) # Assert self.assertEqual(response.status_code, 302) self.assertEqual(response.url, "/account/profile/") # Verify the User was correctly updated updated_user = User.objects.get(email=test_email) self.assertEqual(updated_user.email, test_email) def test_AccountProfileView_post_invalid_form(self): """ This unit test tests the post entry for the route account/profile but submits an invalid form :param self: :return: """ # Arrange self.login_user() # Act response = self.client.post("/account/profile/", {"first_name": "Jimmy"}) # Assert self.assertEqual(response.status_code, 302) # Verify the User was not changed updated_user = User.objects.get(id=self.user.id) self.assertEqual(updated_user.first_name, "") def test_AccountProfileView_post_new_password(self): """ This unit test tests the post entry for the route account/profile with new password :param self: :return: """ # Arrange self.login_user() test_email = "*****@*****.**" # Act response = self.client.post( "/account/profile/", { "email": test_email, "username": "******", "password1": "aBc12345!", "password2": "aBc12345!", }, ) # Assert self.assertEqual(response.status_code, 302) self.assertEqual(response.url, "/account/profile/") # Verify the User was correctly updated updated_user = User.objects.get(email=test_email) self.assertEqual(updated_user.email, test_email) # logout and login with new password self.client.logout() login2 = self.client.login(username="******", password="******") self.assertTrue(login2) def test_AccountProfileView_post_with_image(self): """ This unit test tests the post entry for the route account/profile with new image file :param self: :return: """ # Arrange self.login_user() pw = "!Abc12345" existing_userprofile_count = UserProfile.objects.all().count() # Act image = Image.new("RGBA", size=(50, 50), color=(155, 0, 0)) file = tempfile.NamedTemporaryFile(suffix=".png") image.save(file) with open(file.name, encoding="ISO-8859-1") as fp: response = self.client.post( "/account/profile/", { "myfile": fp, "email": "*****@*****.**", "username": "******", "password1": pw, "password2": pw, }, ) # Assert self.assertEqual(response.status_code, 302) self.assertEqual(response.url, "/account/profile/") # Verify the UserProfile was correctly updated, a new entry in db exists profile = UserProfile.objects.all() self.assertEqual(len(profile), existing_userprofile_count + 1) @patch("concordia.views.requests") def test_concordiaView(self, mock_requests): """ Test the GET method for route /transcribe :return: """ # Arrange mock_requests.get.return_value.status_code = 200 mock_requests.get.return_value.json.return_value = { "concordia_data": "abc123456" } # Act response = self.client.get("/transcribe/") # Assert self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, template_name="transcriptions/home.html") def test_concordiaCollectionView_get(self): """ Test GET on route /transcribe/<slug-value> (collection) :return: """ # Arrange # add an item to Collection self.collection = Collection( title="TextCollection", slug="test-slug2", description="Collection Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.collection.save() # Act response = self.client.get("/transcribe/test-slug2/") # Assert self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, template_name="transcriptions/collection.html") def test_concordiaCollectionView_get_page2(self): """ Test GET on route /transcribe/<slug-value>/ (collection) on page 2 :return: """ # Arrange # add an item to Collection self.collection = Collection( title="TextCollection", slug="test-slug2", description="Collection Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.collection.save() # Act response = self.client.get("/transcribe/test-slug2/", {"page": 2}) # Assert self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, template_name="transcriptions/collection.html") def test_ExportCollectionView_get(self): """ Test GET route /transcribe/export/<slug-value>/ (collection) :return: """ # Arrange self.collection = Collection( title="TextCollection", slug="slug2", description="Collection Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.collection.save() self.asset = Asset( title="TestAsset", slug="test-slug2", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, collection=self.collection, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset.save() # Act response = self.client.get("/transcribe/exportCSV/slug2/") # Assert self.assertEqual(response.status_code, 200) self.assertEqual( str(response.content), "b'Collection,Title,Description,MediaUrl,Transcription,Tags\\r\\n" "TextCollection,TestAsset,Asset Description," "http://www.foo.com/1/2/3,,\\r\\n'", ) @patch("concordia.views.requests") def test_DeleteCollection_get(self, mock_requests): """ Test GET route /transcribe/delete/<slug-value>/ (collection) :return: """ # Arrange mock_requests.get.return_value.status_code = 200 mock_requests.get.return_value.json.return_value = { "concordia_data": "abc123456" } # add an item to Collection self.collection = Collection( title="TextCollection", slug="test-slug2", description="Collection Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.collection.save() self.asset = Asset( title="TestAsset", slug="test-slug2", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, collection=self.collection, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset.save() # Act response = self.client.get("/transcribe/delete/test-slug2", follow=True) # Assert self.assertEqual(response.status_code, 200) # verify the collection is not in db collection2 = Collection.objects.all() self.assertEqual(len(collection2), 0) @patch("concordia.views.requests") def test_DeleteAsset_get(self, mock_requests): """ Test GET route /transcribe/delete/asset/<slug-value>/ (asset) :return: """ # Arrange mock_requests.get.return_value.status_code = 200 mock_requests.get.return_value.json.return_value = { "concordia_data": "abc123456" } # add an item to Collection self.collection = Collection( title="TextCollection", slug="test-collection-slug", description="Collection Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.collection.save() self.asset = Asset( title="TestAsset", slug="test-asset-slug", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, collection=self.collection, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset.save() self.asset = Asset( title="TestAsset1", slug="test-asset-slug1", description="Asset Description1", media_url="http://www.foo1.com/1/2/3", media_type=MediaType.IMAGE, collection=self.collection, metadata={"key": "val1"}, status=Status.EDIT, ) self.asset.save() # Act response = self.client.get( "/transcribe/test-collection-slug/delete/asset/test-asset-slug1/", follow=True) # Assert self.assertEqual(response.status_code, 200) collection2 = Collection.objects.get(slug="test-collection-slug") all_assets = Asset.objects.filter(collection=collection2) hided_assets = Asset.objects.filter(collection=collection2, status=Status.INACTIVE) self.assertEqual(len(all_assets), 2) self.assertEqual(len(hided_assets), 1) def test_ConcordiaAssetView_post(self): """ This unit test test the POST route /transcribe/<collection>/asset/<Asset_name>/ :return: """ # Arrange self.login_user() # create a collection self.collection = Collection( title="TestCollection", slug="Collection1", description="Collection Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.collection.save() # create an Asset self.asset = Asset( title="TestAsset", slug="Asset1", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, collection=self.collection, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset.save() # add a Transcription object self.transcription = Transcription( asset=self.asset, user_id=self.user.id, text="Test transcription 1", status=Status.EDIT, ) self.transcription.save() tag_name = "Test tag 1" # Act response = self.client.post( "/transcribe/Collection1/asset/Asset1/", { "tx": "First Test Transcription", "tags": tag_name, "action": "Save" }, ) # Assert self.assertEqual(response.status_code, 302) self.assertEqual(response.url, "/transcribe/Collection1/asset/Asset1/") # Verify the new transcription and tag are in the db transcription = Transcription.objects.filter( text="First Test Transcription", asset=self.asset) self.assertEqual(len(transcription), 1) tags = UserAssetTagCollection.objects.filter(asset=self.asset, user_id=self.user.id) if tags: separate_tags = tags[0].tags.all() self.assertEqual(len(tags), 1) self.assertEqual(separate_tags[0].name, tag_name) def test_ConcordiaAssetView_post_contact_community_manager(self): """ This unit test test the POST route /transcribe/<collection>/asset/<Asset_name>/ for an anonymous user. Clicking the contact community manager button should redirect to the contact us page. :return: """ # Arrange # create a collection self.collection = Collection( title="TestCollection", slug="Collection1", description="Collection Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.collection.save() # create an Asset self.asset = Asset( title="TestAsset", slug="Asset1", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, collection=self.collection, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset.save() # create anonymous user anon_user = User.objects.create(username="******", email="*****@*****.**") anon_user.set_password("blah_anonymous!") anon_user.save() # add a Transcription object self.transcription = Transcription( asset=self.asset, user_id=anon_user.id, text="Test transcription 1", status=Status.EDIT, ) self.transcription.save() tag_name = "Test tag 1" # Act response = self.client.get("/transcribe/Collection1/asset/Asset1/") self.assertEqual(response.status_code, 200) response = self.client.post( "/transcribe/Collection1/asset/Asset1/", { "tx": "", "tags": "", "action": "Contact Manager" }, ) # Assert self.assertEqual(response.status_code, 302) self.assertEqual(response.url, "/contact/?pre_populate=true") def test_ConcordiaAssetView_post_anonymous_happy_path(self): """ This unit test test the POST route /transcribe/<collection>/asset/<Asset_name>/ for an anonymous user. This user should not be able to tag :return: """ # Arrange # create a collection self.collection = Collection( title="TestCollection", slug="Collection1", description="Collection Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.collection.save() # create an Asset self.asset = Asset( title="TestAsset", slug="Asset1", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, collection=self.collection, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset.save() # create anonymous user anon_user = User.objects.create(username="******", email="*****@*****.**") anon_user.set_password("blah_anonymous!") anon_user.save() # add a Transcription object self.transcription = Transcription( asset=self.asset, user_id=anon_user.id, text="Test transcription 1", status=Status.EDIT, ) self.transcription.save() tag_name = "Test tag 1" # Act response = self.client.get("/transcribe/Collection1/asset/Asset1/") self.assertEqual(response.status_code, 200) hash_ = re.findall(r'value="([0-9a-f]+)"', str(response.content))[0] captcha_response = CaptchaStore.objects.get(hashkey=hash_).response response = self.client.post( "/transcribe/Collection1/asset/Asset1/", { "tx": "First Test Transcription 1", "tags": tag_name, "action": "Save", "captcha_0": hash_, "captcha_1": captcha_response }, ) # Assert self.assertEqual(response.status_code, 302) self.assertEqual(response.url, "/transcribe/Collection1/asset/Asset1/") # Verify the new transcription in the db transcription = Transcription.objects.filter( text="First Test Transcription 1", asset=self.asset) self.assertEqual(len(transcription), 1) tags = UserAssetTagCollection.objects.filter(asset=self.asset, user_id=anon_user.id) # Tag is not in db, as anonymous user can't tag self.assertEqual(len(tags), 0) def test_ConcordiaAssetView_post_anonymous_invalid_captcha(self): """ This unit test test the POST route /transcribe/<collection>/asset/<Asset_name>/ for an anonymous user with missing captcha. This user should not be able to tag also :return: """ # Arrange # create a collection self.collection = Collection( title="TestCollection", slug="Collection1", description="Collection Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.collection.save() # create an Asset self.asset = Asset( title="TestAsset", slug="Asset1", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, collection=self.collection, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset.save() # create anonymous user anon_user = User.objects.create(username="******", email="*****@*****.**") anon_user.set_password("blah_anonymous!") anon_user.save() # add a Transcription object self.transcription = Transcription( asset=self.asset, user_id=anon_user.id, text="Test transcription 1", status=Status.EDIT, ) self.transcription.save() tag_name = "Test tag 1" # Act # post as anonymous user without captcha data response = self.client.post( "/transcribe/Collection1/asset/Asset1/", { "tx": "First Test Transcription", "tags": tag_name, "action": "Save" }, ) # Assert self.assertEqual(response.status_code, 200) # Verify the new transcription are not in db transcription = Transcription.objects.filter( text="First Test Transcription", asset=self.asset) self.assertEqual(len(transcription), 0) def test_ConcordiaAssetView_get(self): """ This unit test test the GET route /transcribe/<collection>/asset/<Asset_name>/ with already in use. Verify the updated_on time is updated on PageInUse :return: """ # Arrange self.login_user() # create a collection self.collection = Collection( title="TestCollection", slug="Collection1", description="Collection Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.collection.save() # create an Asset asset_slug = "Asset1" self.asset = Asset( title="TestAsset", slug=asset_slug, description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, collection=self.collection, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset.save() # add a Transcription object self.transcription = Transcription( asset=self.asset, user_id=self.user.id, text="Test transcription 1", status=Status.EDIT, ) self.transcription.save() url = "/transcribe/Collection1/asset/Asset1/" # Act response = self.client.get(url) # Assert self.assertEqual(response.status_code, 200) # get PageInUse value page_in_use = PageInUse.objects.get(page_url=url) # sleep so update time can be tested against original time time.sleep(2) # Act response = self.client.get(url) self.assertEqual(response.status_code, 200) # get PageInUse value page_in_use2 = PageInUse.objects.get(page_url=url) self.assertNotEqual(page_in_use.updated_on, page_in_use2.updated_on) self.assertEqual(page_in_use.created_on, page_in_use2.created_on) def test_page_in_use_same_user(self): """ Test the ConcordiaAssetView page_in_view returns False when PageInUse entry exists for same user :return: """ # Arrange self.login_user() # Add values to database self.collection = Collection( title="TestCollection", slug="TestCollection", description="Collection Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.collection.save() # create an Asset self.asset = Asset( title="TestAsset", slug="TestAsset", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, collection=self.collection, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset.save() in_use_url = "/transcribe/%s/asset/%s/" % (self.asset.collection.slug, self.asset.slug) PageInUse.objects.create(page_url=in_use_url, user=self.user) # Act concordia_asset_view = views.ConcordiaAssetView() results = concordia_asset_view.check_page_in_use(in_use_url, self.user) # Assert self.assertEqual(results, False) def test_page_in_use_different_user(self): """ Test the ConcordiaAssetView page_in_view returns True when PageInUse entry exists with different user :return: """ # Arrange self.login_user() user2 = User.objects.create(username="******", email="*****@*****.**") user2.set_password("top_secret2") user2.save() # Add values to database self.collection = Collection( title="TestCollection", slug="TestCollection", description="Collection Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.collection.save() # create an Asset self.asset = Asset( title="TestAsset", slug="TestAsset", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, collection=self.collection, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset.save() in_use_url = "/transcribe/%s/asset/%s/" % (self.asset.collection.slug, self.asset.slug) PageInUse.objects.create(page_url=in_use_url, user=user2) # Act concordia_asset_view = views.ConcordiaAssetView() results = concordia_asset_view.check_page_in_use(in_use_url, self.user) # Assert self.assertEqual(results, True) def test_redirect_when_same_page_in_use(self): """ Test the GET route for /transcribe/<collection>/alternateasset/<Asset_name>/ :return: """ # Arrange self.login_user() # create a collection self.collection = Collection( title="TestCollection", slug="Collection1", description="Collection Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.collection.save() # create 2 Assets self.asset = Asset( title="TestAsset", slug="Asset1", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, collection=self.collection, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset.save() self.asset2 = Asset( title="TestAsset2", slug="Asset2", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, collection=self.collection, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset2.save() # Act response = self.client.post("/transcribe/alternateasset/", { "collection": self.collection.slug, "asset": self.asset.slug }) # Assert self.assertEqual(response.status_code, 200) # only 2 assets in collection, this response should be for the other asset self.assertEqual(str(response.content, 'utf-8'), "/transcribe/Collection1/asset/Asset2/") def test_pageinuse_post(self): """ Test the POST method on /transcribe/pageinuse/ route test that matching PageInUse entries with same page_url are deleted test that old entries in PageInUse table are removed :return: """ # Arrange self.login_user() url = "foo.com/bar" user2 = User.objects.create(username="******", email="*****@*****.**") user2.set_password("top_secret") user2.save() page1 = PageInUse(page_url=url, user=user2) page1.save() from datetime import datetime, timedelta time_threshold = datetime.now() - timedelta(minutes=20) # add two entries with old timestamps page2 = PageInUse(page_url="foo.com/blah", user=self.user, created_on=time_threshold, updated_on=time_threshold) page2.save() page3 = PageInUse(page_url="bar.com/blah", user=self.user, created_on=time_threshold, updated_on=time_threshold) page3.save() # Act response = self.client.post( "/transcribe/pageinuse/", { "page_url": url, "user": self.user }, ) # Assert self.assertEqual(response.status_code, 200) pages = PageInUse.objects.all() self.assertEqual(len(pages), 1) self.assertNotEqual(page1.created_on, pages[0].created_on) def test_pageinuse_multiple_same_entries_in_pageinuse_post(self): """ Test the POST method on /transcribe/pageinuse/ route Create an additional entry in PageInUse, verify 1 different entry in PageInUse after call :return: """ # Arrange self.login_user() # Act response = self.client.post( "/transcribe/pageinuse/", { "page_url": "foo.com/bar", "user": self.user }, ) # Assert self.assertEqual(response.status_code, 200) def test_get_anonymous_user(self): """ Test retrieving the anonymous user :return: """ # Arrange anon_id = views.get_anonymous_user() # Act anon_user = User.objects.get(id=anon_id) # Assert self.assertEqual(anon_user.id, anon_id) def test_get_anonymous_user_obj(self): """ Test retrieving the anonymous user object :return: """ # Arrange anon_obj = views.get_anonymous_user(False) # Act anon_user = User.objects.get(username=anon_obj.username) # Assert self.assertEqual(anon_user.id, anon_obj.id)
class ViewTest_Exporter(TestCase): """ This class contains the unit tests for the view in the exporter app. Make sure the postgresql db is available. Run docker-compose up db """ def setUp(self): """ setUp is called before the execution of each test below :return: """ self.client = Client() def login_user(self): """ Create a user and log the user in :return: """ # create user and login self.user = User.objects.create(username="******", email="*****@*****.**") self.user.set_password("top_secret") self.user.save() def test_ExportCollectionToBagit_get(self): """ Test the http GET on route /transcribe/exportBagit/<collectionname>/ :return: """ # Arrange self.login_user() ## Build test data for local storage collection ## # Collection Info (local storage) locstor_media_url_str = "/locstorcollection/testasset/asset.jpg" locstor_collection_name_str = "locstorcollection" locstor_asset_folder_name_str = "testasset" locstor_asset_name_str = "asset.jpg" # create a collection (local Storage) self.collection1 = Collection( title="LocStorCollection", slug=locstor_collection_name_str, description="Collection Description", metadata={"key": "val1"}, is_active=True, s3_storage=False, status=Status.EDIT, ) self.collection1.save() # create an Asset (local Storage) self.asset1 = Asset( title="TestAsset", slug=locstor_asset_folder_name_str, description="Asset Description", media_url=locstor_media_url_str, media_type=MediaType.IMAGE, collection=self.collection1, sequence=0, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset1.save() # add a Transcription object self.transcription1 = Transcription( asset=self.asset1, user_id=self.user.id, status=Status.EDIT, text="Sample" ) self.transcription1.save() ## Build test data for S3 Storage Collection ## # Collection Info (S3 storage) s3_media_url_str = "https://s3.us-east-2.amazonaws.com/chc-collections/test_s3/mss859430177/0.jpg" s3_collection_name_str = "test_s3" s3_asset_folder_name_str = "testasset" s3_asset_name_str = "asset.jpg" # create a collection (local Storage) self.collection2 = Collection( title="Test S3", slug=s3_collection_name_str, description="Collection Description", metadata={"key": "val1"}, is_active=True, s3_storage=True, status=Status.EDIT, ) self.collection2.save() # create an Asset (local Storage) self.asset2 = Asset( title="TestAsset", slug=s3_asset_folder_name_str, description="Asset Description", media_url=s3_media_url_str, media_type=MediaType.IMAGE, collection=self.collection2, sequence=0, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset2.save() # add a Transcription object self.transcription2 = Transcription( asset=self.asset2, user_id=self.user.id, status=Status.EDIT, text="Sample" ) self.transcription2.save() # Make sure correct folders structure exists for Local Storage Collection collection_folder = "{0}/{1}".format(settings.MEDIA_ROOT, locstor_collection_name_str) if not os.path.exists(collection_folder): os.makedirs(collection_folder) item_dir = "{0}/{1}".format(collection_folder, locstor_asset_folder_name_str) if not os.path.exists(item_dir): os.makedirs(item_dir) # create source asset file for Local Storage Collection with open("{0}/{1}".format(item_dir, locstor_asset_name_str), "w+") as csv_file: writer = csv.writer(csv_file) writer.writerow( [ "Collection", "Title", "Description", "MediaUrl", "Transcription", "Tags", ] ) # Act (local storage collection) response = self.client.get("/transcribe/exportBagit/locstorcollection/") # Assert for Local Storage Collection self.assertEqual(response.status_code, 200) self.assertEquals( response.get("Content-Disposition"), "attachment; filename=locstorcollection.zip", ) try: f = io.BytesIO(response.content) zipped_file = zipfile.ZipFile(f, "r") # self.assertIsNone(zipped_file.testzip()) self.assertIn("bagit.txt", zipped_file.namelist()) self.assertIn("bag-info.txt", zipped_file.namelist()) self.assertIn("data/testasset/asset.txt", zipped_file.namelist()) finally: zipped_file.close() f.close() # Act (s3 collection) response2 = self.client.get("/transcribe/exportBagit/test_s3/") # Assert for s3 Collection self.assertEqual(response2.status_code, 200) self.assertEquals( response2.get("Content-Disposition"), "attachment; filename=test_s3.zip", ) try: f = io.BytesIO(response2.content) zipped_file = zipfile.ZipFile(f, "r") self.assertIn("bagit.txt", zipped_file.namelist()) self.assertIn("bag-info.txt", zipped_file.namelist()) self.assertIn("data/mss859430177/0.txt", zipped_file.namelist()) self.assertIn("data/mss859430177/0.jpg", zipped_file.namelist()) finally: zipped_file.close() f.close() # Clean up temp folders try: shutil.rmtree(collection_folder) except Exception as e: pass
class ViewTest_Concordia(TestCase): """ This class contains the unit tests for the view in the concordia app. Make sure the postgresql db is available. Run docker-compose up db """ def setUp(self): """ setUp is called before the execution of each test below :return: """ # make sure the config-optional-override.json mode is "unittest" self.assertEqual(Config.GetOverrideMode(), 'unittest') self.client = Client() def login_user(self): """ Create a user and log the user in :return: """ # create user and login self.user = User.objects.create(username='******', email='*****@*****.**') self.user.set_password('top_secret') self.user.save() login = self.client.login(username='******', password='******') def test_concordia_api(self): """ Test the tracribr_api. Provide a mock of requests :return: """ # Arrange relative_path = Mock() with patch('views.requests') as mock_requests: mock_requests.get.return_value = mock_response = Mock() mock_response.status_code = 200 mock_response.json.return_value = {'concordia_data': 'abc123456'} # Act results = views.concordia_api('relative_path') # Assert self.assertEqual(results['concordia_data'], 'abc123456') def test_AccountProfileView_get(self): """ Test the http GET on route account/profile :return: """ # Arrange self.login_user() # create a collection self.collection = Collection(title='TextCollection', slug='www.foo.com/slug2', description='Collection Description', metadata={"key": "val1"}, status=Status.PCT_0) self.collection.save() # create an Asset self.asset = Asset(title='TestAsset', slug='www.foo.com/slug1', description='Asset Description', media_url='http://www.foo.com/1/2/3', media_type=MediaType.IMAGE, collection=self.collection, metadata={"key": "val2"}, status=Status.PCT_0) self.asset.save() # add a Transcription object self.transcription = Transcription(asset=self.asset, user_id=self.user.id, status=Status.PCT_0) self.transcription.save() # Act response = self.client.get('/account/profile/') # Assert # validate the web page has the "tester" and "*****@*****.**" as values self.assertTrue('value="tester"' in str(response.content)) self.assertTrue('value="*****@*****.**"' in str(response.content)) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, template_name='profile.html') def test_AccountProfileView_post(self): """ This unit test tests the post entry for the route account/profile :param self: :return: """ # Arrange self.login_user() # Act response = self.client.post( '/account/profile/', { 'first_name': 'Jimmy', 'email': '*****@*****.**', 'username': '******', 'password1': '', 'password2': '' }) # Assert self.assertEqual(response.status_code, 302) self.assertEqual(response.url, '/account/profile/') # Verify the User was correctly updated updated_user = User.objects.get(id=self.user.id) self.assertEqual(updated_user.first_name, 'Jimmy') def test_AccountProfileView_post_invalid_form(self): """ This unit test tests the post entry for the route account/profile but submits an invalid form :param self: :return: """ # Arrange self.login_user() # Act response = self.client.post('/account/profile/', {'first_name': 'Jimmy'}) # Assert self.assertEqual(response.status_code, 302) self.assertEqual(response.url, '/account/profile/') # Verify the User was not changed updated_user = User.objects.get(id=self.user.id) self.assertEqual(updated_user.first_name, '') def test_AccountProfileView_post_new_password(self): """ This unit test test the post entry for the route account/profile with new password :param self: :return: """ # Arrange self.login_user() # Act response = self.client.post( '/account/profile/', { 'first_name': 'Jimmy', 'email': '*****@*****.**', 'username': '******', 'password1': 'abc', 'password2': 'abc' }) # Assert self.assertEqual(response.status_code, 302) self.assertEqual(response.url, '/account/profile/') # Verify the User was correctly updated updated_user = User.objects.get(id=self.user.id) self.assertEqual(updated_user.first_name, 'Jimmy') # logout and login with new password logout = self.client.logout() login2 = self.client.login(username='******', password='******') self.assertTrue(login2) def test_AccountProfileView_post_with_image(self): """ This unit test tests the post entry for the route account/profile with new image file :param self: :return: """ # Arrange self.login_user() existing_userprofile_count = UserProfile.objects.all().count() # Act image = Image.new('RGBA', size=(50, 50), color=(155, 0, 0)) file = tempfile.NamedTemporaryFile(suffix='.png') image.save(file) with open(file.name, encoding="ISO-8859-1") as fp: response = self.client.post( '/account/profile/', { 'myfile': fp, 'first_name': 'Jimmy', 'email': '*****@*****.**', 'username': '******', 'password1': '', 'password2': '' }) # Assert self.assertEqual(response.status_code, 302) self.assertEqual(response.url, '/account/profile/') # Verify the UserProfile was correctly updated, a new entry in db exists profile = UserProfile.objects.all() self.assertEqual(len(profile), existing_userprofile_count + 1) @patch('concordia.views.requests') def test_concordiaView(self, mock_requests): """ Test the GET method for route /transcribe :return: """ # Arrange mock_requests.get.return_value.status_code = 200 mock_requests.get.return_value.json.return_value = { 'concordia_data': 'abc123456' } # Act response = self.client.get('/transcribe/') # Assert self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, template_name='transcriptions/home.html') def test_concordiaCollectionView_get(self): """ Test GET on route /transcribe/<slug-value> (collection) :return: """ # Arrange # add an item to Collection self.collection = Collection(title='TextCollection', slug='test-slug2', description='Collection Description', metadata={"key": "val1"}, status=Status.PCT_0) self.collection.save() # Act response = self.client.get('/transcribe/test-slug2/') # Assert self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, template_name='transcriptions/collection.html') def test_concordiaCollectionView_get_page2(self): """ Test GET on route /transcribe/<slug-value>/ (collection) on page 2 :return: """ # Arrange # add an item to Collection self.collection = Collection(title='TextCollection', slug='test-slug2', description='Collection Description', metadata={"key": "val1"}, status=Status.PCT_0) self.collection.save() # Act response = self.client.get('/transcribe/test-slug2/', {'page': 2}) # Assert self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, template_name='transcriptions/collection.html') def test_ExportCollectionView_get(self): """ Test GET route /transcribe/export/<slug-value>/ (collection) :return: """ # Arrange self.collection = Collection(title='TextCollection', slug='slug2', description='Collection Description', metadata={"key": "val1"}, status=Status.PCT_0) self.collection.save() self.asset = Asset(title='TestAsset', slug='test-slug2', description='Asset Description', media_url='http://www.foo.com/1/2/3', media_type=MediaType.IMAGE, collection=self.collection, metadata={"key": "val2"}, status=Status.PCT_0) self.asset.save() # Act response = self.client.get('/transcribe/export/slug2/') # Assert self.assertEqual(response.status_code, 200) self.assertEqual( str(response.content), "b'Collection,Title,Description,MediaUrl,Transcription,Tags\\r\\nTextCollection,TestAsset,Asset Description,http://www.foo.com/1/2/3,,\\r\\n\'" ) def test_DeleteCollection_get(self): """ Test GET route /transcribe/delete/<slug-value>/ (collection) :return: """ # Arrange # add an item to Collection self.collection = Collection(title='TextCollection', slug='test-slug2', description='Collection Description', metadata={"key": "val1"}, status=Status.PCT_0) self.collection.save() self.asset = Asset(title='TestAsset', slug='test-slug2', description='Asset Description', media_url='http://www.foo.com/1/2/3', media_type=MediaType.IMAGE, collection=self.collection, metadata={"key": "val2"}, status=Status.PCT_0) self.asset.save() # Act response = self.client.get('/transcribe/delete/test-slug2', follow=True) # Assert self.assertEqual(response.status_code, 200) # verify the collection is not in db collection2 = Collection.objects.all() self.assertEqual(len(collection2), 0)
class ViewTest_Exporter(TestCase): """ This class contains the unit tests for the view in the exporter app. Make sure the postgresql db is available. Run docker-compose up db """ def setUp(self): """ setUp is called before the execution of each test below :return: """ self.client = Client() def login_user(self): """ Create a user and log the user in :return: """ # create user and login self.user = User.objects.create(username="******", email="*****@*****.**") self.user.set_password("top_secret") self.user.save() def test_ExportCollectionToBagit_get(self): """ Test the http GET on route /transcribe/exportBagit/<collectionname>/ :return: """ media_url_str = "/foocollection/testasset/asset.jpg" collection_name_str = "foocollection" asset_folder_name_str = "testasset" asset_name_str = "asset.jpg" # Arrange self.login_user() # create a collection self.collection = Collection( title="FooCollection", slug=collection_name_str, description="Collection Description", metadata={"key": "val1"}, is_active=True, s3_storage=False, status=Status.EDIT, ) self.collection.save() # create an Asset self.asset = Asset( title="TestAsset", slug=asset_folder_name_str, description="Asset Description", media_url=media_url_str, media_type=MediaType.IMAGE, collection=self.collection, sequence=0, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset.save() # add a Transcription object self.transcription = Transcription(asset=self.asset, user_id=self.user.id, status=Status.EDIT, text="Sample") self.transcription.save() # Make sure correct folders structure exists collection_folder = "{0}/{1}".format(settings.MEDIA_ROOT, collection_name_str) if not os.path.exists(collection_folder): os.makedirs(collection_folder) source_dir = "{0}/{1}".format(collection_folder, asset_folder_name_str) if not os.path.exists(source_dir): os.makedirs(source_dir) # create source asset file with open("{0}/{1}".format(source_dir, asset_name_str), "w+") as csv_file: writer = csv.writer(csv_file) writer.writerow([ "Collection", "Title", "Description", "MediaUrl", "Transcription", "Tags", ]) # Act response = self.client.get("/transcribe/exportBagit/foocollection/") # Assert self.assertEqual(response.status_code, 200) self.assertEquals( response.get("Content-Disposition"), "attachment; filename=foocollection.zip", ) try: f = io.BytesIO(response.content) zipped_file = zipfile.ZipFile(f, "r") # self.assertIsNone(zipped_file.testzip()) self.assertIn("bagit.txt", zipped_file.namelist()) self.assertIn("bag-info.txt", zipped_file.namelist()) self.assertIn("data/testasset/export.csv", zipped_file.namelist()) csv_file = zipped_file.read("data/testasset/export.csv") self.assertEqual( str(csv_file), "b'Collection,Title,Description,MediaUrl,Transcription,Tags\\r\\nFooCollection,TestAsset,Asset Description,{0},,\\r\\n'" .format(media_url_str), # noqa ) finally: zipped_file.close() f.close() # Clean up temp folders try: shutil.rmtree(collection_folder) except Exception as e: pass
class ViewWSTest_Concordia(TestCase): """ This class contains the unit tests for the view_ws in the concordia app. Make sure the postgresql db is available. Run docker-compose up db """ def setUp(self): """ setUp is called before the execution of each test below :return: """ self.client = Client() def login_user(self): """ Create a user and log the user in :return: """ # create user and login self.user = User.objects.create(username="******", email="*****@*****.**") self.user.set_password("top_secret") self.user.save() self.client.login(username="******", password="******") # create a session cookie self.client.session['foo'] = 123 # HACK: needed for django Client def test_PageInUse_post(self): """ This unit test tests the post entry for the route ws/page_in_use :param self: :return: """ # Arrange self.login_user() # Act response = self.client.post( "/ws/page_in_use/", { "page_url": "transcribe/American-Jerusalem/asset/mamcol.0930/", "user": self.user.id, }, ) # Assert self.assert_post_successful(response) def test_PageInUse_delete_old_entries_post(self): """ This unit test tests the post entry for the route ws/page_in_use the database has two items added the created_on timestamp of now - 10 minutes :param self: :return: """ # Arrange self.login_user() time_threshold = datetime.now() - timedelta(minutes=10) page1 = PageInUse(page_url="foo.com/blah", user=self.user, created_on=time_threshold, updated_on=time_threshold) page1.save() page2 = PageInUse(page_url="bar.com/blah", user=self.user, created_on=time_threshold, updated_on=time_threshold) page2.save() pages_in_use = PageInUse.objects.all() for p in pages_in_use: print(p.page_url, p.created_on, p.updated_on) # Act response = self.client.post( "/ws/page_in_use/", { "page_url": "transcribe/American-Jerusalem/asset/mamcol.0930/", "user": self.user.id, }, ) # Assert self.assert_post_successful(response) def test_PageInUse_nologin_post(self): """ This unit test tests the post entry for the route ws/page_in_use without logging in :param self: :return: """ # Arrange # create user self.user = User.objects.create(username="******", email="*****@*****.**") self.user.set_password("top_secret") self.user.save() # Act response = self.client.post( "/ws/page_in_use/", { "page_url": "transcribe/American-Jerusalem/asset/mamcol.0930/", "user": self.user.id, }, ) # Assert self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) # Verify the entry is not in the PagInUse table page_in_use = PageInUse.objects.all() self.assertEqual(len(page_in_use), 0) def test_PageInUse_nologin_anonymous_post(self): """ This unit test tests the post entry for the route ws/page_in_use without logging and the user is anonymous :param self: :return: """ # Arrange # create user self.user = User.objects.create(username="******", email="*****@*****.**") self.user.set_password("top_secret") self.user.save() # Act response = self.client.post( "/ws/page_in_use/", { "page_url": "transcribe/American-Jerusalem/asset/mamcol.0930/", "user": self.user.id, }, ) # Assert self.assert_post_successful(response) def assert_post_successful(self, response): """ Check the results of a successful post and insert of a PageInUse database item :param response: :return: """ self.assertEqual(response.status_code, status.HTTP_201_CREATED) # Verify the entry is in the PagInUse table page_in_use = PageInUse.objects.all() self.assertEqual(len(page_in_use), 1) def test_PageInUse_get(self): """ This unit test tests the get entry for the route ws/page_in_use/url :param self: :return: """ # Arrange self.login_user() # Add two values to database PageInUse.objects.create(page_url="foo.com/blah", user=self.user) PageInUse.objects.create(page_url="bar.com/blah", user=self.user) # Act response = self.client.get("/ws/page_in_use/bar.com/blah/") # Assert self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertJSONEqual(str(response.content, encoding='utf8'), { "page_url": "bar.com/blah", "user": self.user.id }) def test_PageInUseUser_get(self): """ This unit test tests the get entry for the route ws/page_in_use_user/user/url/ :param self: :return: """ # Arrange self.login_user() # create second user self.user2 = User.objects.create(username="******", email="*****@*****.**") self.user2.set_password("top_secret") self.user2.save() test_page_url = "foo.com/blah" # Add two values to database PageInUse.objects.create(page_url=test_page_url, user=self.user) PageInUse.objects.create(page_url="bar.com/blah", user=self.user2) # Act response = self.client.get("/ws/page_in_use_user/%s/%s/" % (self.user.id, test_page_url)) # Assert self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertJSONEqual(str(response.content, encoding='utf8'), { "page_url": test_page_url, "user": self.user.id }) def test_PageInUse_put(self): """ This unit test tests the update of an existing PageInUse using PUT on route ws/page_in_use/url :return: """ # Arrange self.login_user() # Add a value to database page = PageInUse(page_url="foo.com/blah", user=self.user) page.save() min_update_time = page.created_on + timedelta(seconds=2) change_page_in_use = {"page_url": "foo.com/blah", "user": self.user.id} # sleep so update time can be tested against original time time.sleep(2) # Act response = self.client.put("/ws/page_in_use_update/foo.com/blah/", data=json.dumps(change_page_in_use), content_type='application/json') # Assert self.assertEqual(response.status_code, status.HTTP_200_OK) updated_page = PageInUse.objects.filter(page_url="foo.com/blah") self.assertTrue(len(updated_page), 1) self.assertEqual(page.id, updated_page[0].id) self.assertTrue(updated_page[0].updated_on > min_update_time) def test_Collection_get(self): """ Test getting a Collection object :return: """ # Arrange self.login_user() # create 2 collections self.collection = Collection( title="TextCollection", slug="slug1", description="Collection Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.collection.save() self.collection2 = Collection( title="TextCollection2", slug="slug2", description="Collection2 Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.collection2.save() # Act response = self.client.get("/ws/collection/slug2/") # Assert self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertJSONEqual( str(response.content, encoding='utf8'), { 'description': 'Collection2 Description', 'end_date': None, 'id': self.collection2.id, 'slug': 'slug2', 'start_date': None, 'status': Status.EDIT, 'title': 'TextCollection2' }) def test_get_assets_by_collection(self): """ Test getting a list of assets by collection :return: """ # Arrange self.login_user() # create 2 collections self.collection = Collection( title="TextCollection", slug="slug1", description="Collection Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.collection.save() self.collection2 = Collection( title="TextCollection2", slug="slug2", description="Collection2 Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.collection2.save() # Add 2 assets to collection2, 1 asset to collection1 self.asset = Asset( title="TestAsset", slug="Asset1", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, collection=self.collection2, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset.save() self.asset2 = Asset( title="TestAsset2", slug="Asset2", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, collection=self.collection2, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset2.save() self.asset3 = Asset( title="TestAsset3", slug="Asset3", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, collection=self.collection, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset3.save() # Act response = self.client.get("/ws/asset/slug2/") json_resp = json.loads(response.content) # Assert self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(json_resp['results']), 2) def test_get_assets_by_collection_and_slug(self): """ Test getting an asset by collection and slug :return: """ # Arrange self.login_user() # create 2 collections self.collection = Collection( title="TextCollection", slug="slug1", description="Collection Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.collection.save() self.collection2 = Collection( title="TextCollection2", slug="slug2", description="Collection2 Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.collection2.save() # Add 2 assets to collection2, 1 asset to collection1 self.asset = Asset( title="TestAsset", slug="Asset1", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, collection=self.collection2, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset.save() self.asset2 = Asset( title="TestAsset2", slug="Asset2", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, collection=self.collection2, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset2.save() self.asset3 = Asset( title="TestAsset3", slug="Asset3", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, collection=self.collection, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset3.save() # Act response = self.client.get("/ws/asset_by_slug/slug1/Asset3/") # Assert self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertJSONEqual( force_text(response.content), { "title": "TestAsset3", "slug": "Asset3", "description": "Asset Description", "media_url": "http://www.foo.com/1/2/3", "media_type": MediaType.IMAGE, "collection": self.collection.id, "sequence": 1, "metadata": { "key": "val2" }, "subcollection": None, "status": Status.EDIT, }) def test_get_assets_by_collection_and_slug_no_match(self): """ Test getting an asset by collection and slug using a slug that doesn't exist :return: """ # Arrange self.login_user() # create 2 collections self.collection = Collection( title="TextCollection", slug="slug1", description="Collection Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.collection.save() self.collection2 = Collection( title="TextCollection2", slug="slug2", description="Collection2 Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.collection2.save() # Add 2 assets to collection2, 1 asset to collection1 self.asset = Asset( title="TestAsset", slug="Asset1", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, collection=self.collection2, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset.save() self.asset2 = Asset( title="TestAsset2", slug="Asset2", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, collection=self.collection2, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset2.save() self.asset3 = Asset( title="TestAsset3", slug="Asset3", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, collection=self.collection, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset3.save() # Act response = self.client.get("/ws/asset_by_slug/slugxxx/Asset3xxx/") # Assert self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertJSONEqual( force_text(response.content), { "title": "", "slug": "", "description": "", "media_url": "", "media_type": None, "collection": None, "sequence": None, "metadata": None, "subcollection": None, "status": None, }) def test_PageInUse_filter_get(self): """ Test the route ws/page_in_use_filter/user/page_url/ It should return a list of PageInUse updated in last 5 minutes by user other than self.user :return: """ # Arrange self.login_user() # create a second user username = "******" test_url = "bar.com/blah" self.user2 = User.objects.create(username=username, email="*****@*****.**") self.user2.set_password("top_secret") self.user2.save() # Add values to database PageInUse.objects.create(page_url="foo.com/blah", user=self.user) PageInUse.objects.create(page_url=test_url, user=self.user2) # Act response = self.client.get("/ws/page_in_use_filter/%s/%s/" % ( self.user.username, test_url, )) json_resp = json.loads(response.content) # Assert self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertTrue(len(json_resp['results']) > 0) def test_PageInUse_filter_no_pages_get(self): """ Test the route ws/page_in_use_filter/user/page_url/ It should return an empty list :return: """ # Arrange self.login_user() # create a second user username = "******" test_url = "bar.com/blah" self.user2 = User.objects.create(username=username, email="*****@*****.**") self.user2.set_password("top_secret") self.user2.save() # Act response = self.client.get("/ws/page_in_use_filter/%s/%s/" % ( self.user.username, test_url, )) json_resp = json.loads(response.content) # Assert self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(json_resp['results']), 0) def test_Transcriptions_latest_get(self): """ Test getting latest transcription for an asset. route ws/transcriptions/asset/ :return: """ # Arrange self.login_user() # create a second user username = "******" self.user2 = User.objects.create(username=username, email="*****@*****.**") self.user2.set_password("top_secret") self.user2.save() # create a collection self.collection = Collection( title="TextCollection", slug="www.foo.com/slug2", description="Collection Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.collection.save() # create Assets self.asset = Asset( title="TestAsset", slug="www.foo.com/slug1", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, collection=self.collection, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset.save() self.asset2 = Asset( title="TestAsset2", slug="www.foo.com/slug2", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, collection=self.collection, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset2.save() # add Transcription objects self.transcription = Transcription(asset=self.asset, user_id=self.user.id, status=Status.EDIT, text="T1") self.transcription.save() t2_text = "T2" self.transcription2 = Transcription(asset=self.asset, user_id=self.user2.id, status=Status.EDIT, text=t2_text) self.transcription2.save() # Act response = self.client.get("/ws/transcription/%s/" % self.asset.id) json_resp = json.loads(response.content) # Assert self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(json_resp["text"], t2_text) def test_Transcriptions_create_post(self): """ Test creating a transcription. route ws/transcription_create/ :return: """ # Arrange self.login_user() # create a collection self.collection = Collection( title="TextCollection", slug="www.foo.com/slug2", description="Collection Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.collection.save() # create Assets self.asset = Asset( title="TestAsset", slug="www.foo.com/slug1", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, collection=self.collection, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset.save() # Act response = self.client.post( "/ws/transcription_create/", { "asset": self.asset.id, "user_id": self.user.id, "status": Status.EDIT, "text": "T1" }, ) # Assert self.assertEqual(response.status_code, status.HTTP_201_CREATED) # Get all Transcriptions for the asset transcriptions_count = Transcription.objects.filter( asset=self.asset).count() self.assertEqual(transcriptions_count, 1) # Add Another transcription response = self.client.post( "/ws/transcription_create/", { "asset": self.asset.id, "user_id": self.user.id, "status": Status.EDIT, "text": "T2" }, ) # Get all Transcriptions for the asset, should be another one transcriptions_count = Transcription.objects.filter( asset=self.asset).count() self.assertEqual(transcriptions_count, 2) def test_Tag_create_post(self): """ Test creating a tag. route ws/tag_create/ :return: """ # Arrange self.login_user() # create a collection self.collection = Collection( title="TextCollection", slug="www.foo.com/slug2", description="Collection Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.collection.save() # create Assets self.asset = Asset( title="TestAsset", slug="www.foo.com/slug1", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, collection=self.collection, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset.save() # Act response = self.client.post( "/ws/tag_create/", { "collection": self.collection.slug, "asset": self.asset.slug, "user_id": self.user.id, "name": "T1", "value": "T1" }, ) # Assert self.assertEqual(response.status_code, status.HTTP_200_OK) def test_Tag_create_with_an_existing_tag_post(self): """ Test creating a tag, adding to an asset that already has a tag. route ws/tag_create/ :return: """ # Arrange self.login_user() # create a collection self.collection = Collection( title="TextCollection", slug="www.foo.com/slug2", description="Collection Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.collection.save() # create Assets self.asset = Asset( title="TestAsset", slug="www.foo.com/slug1", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, collection=self.collection, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset.save() # Act response = self.client.post( "/ws/tag_create/", { "collection": self.collection.slug, "asset": self.asset.slug, "user_id": self.user.id, "name": "T1", "value": "T1" }, ) response = self.client.post( "/ws/tag_create/", { "collection": self.collection.slug, "asset": self.asset.slug, "user_id": self.user.id, "name": "T2", "value": "T3" }, ) # Assert self.assertEqual(response.status_code, status.HTTP_200_OK) def test_GetTags_get(self): """ Test getting the tags for an asset, route /ws/tags/<asset> :return: """ # Arrange self.login_user() # create a second user username = "******" self.user2 = User.objects.create(username=username, email="*****@*****.**") self.user2.set_password("top_secret") self.user2.save() # create a collection self.collection = Collection( title="TextCollection", slug="www.foo.com/slug2", description="Collection Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.collection.save() # create Assets self.asset = Asset( title="TestAsset", slug="www.foo.com/slug1", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, collection=self.collection, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset.save() self.tag1 = Tag(name="Tag1", value="Tag1") self.tag1.save() self.tag2 = Tag(name="Tag2", value="Tag2") self.tag2.save() self.tag3 = Tag(name="Tag3", value="Tag3") self.tag3.save() # Save for User1 self.asset_tag_collection = UserAssetTagCollection( asset=self.asset, user_id=self.user.id) self.asset_tag_collection.save() self.asset_tag_collection.tags.add(self.tag1, self.tag2) # Save for User2 self.asset_tag_collection2 = UserAssetTagCollection( asset=self.asset, user_id=self.user2.id) self.asset_tag_collection2.save() self.asset_tag_collection2.tags.add(self.tag3) # Act response = self.client.get("/ws/tags/%s/" % self.asset.id) json_resp = json.loads(response.content) # Assert self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(json_resp["results"]), 3)
class ViewWSTest_Concordia(TestCase): """ This class contains the unit tests for the view_ws in the concordia app. Make sure the postgresql db is available. Run docker-compose up db """ def setUp(self): """ setUp is called before the execution of each test below :return: """ self.client = Client() def login_user(self): """ Create a user and log the user in :return: """ # create user and login self.user = User.objects.create(username="******", email="*****@*****.**") self.user.set_password("top_secret") self.user.save() self.client.login(username="******", password="******") # create a session cookie self.client.session["foo"] = 123 # HACK: needed for django Client def test_AnonymousUser_get(self): """ This unit test tests the get route ws/anonymous_user/ :param self: :return: """ # Arrange self.login_user() # Act response = self.client.get("/ws/anonymous_user/") response2 = self.client.get("/ws/anonymous_user/") # Assert self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.content, response2.content) def test_UserProfile_get(self): """ This unit test tests the get route ws/user_profile/<user_id>/ :param self: :return: """ # Arrange self.login_user() profile = UserProfile(user_id=self.user.id) profile.save() # Act response = self.client.get("/ws/user_profile/%s/" % self.user.id) # Assert self.assertEqual(response.status_code, status.HTTP_200_OK) def test_PageInUse_post(self): """ This unit test tests the post entry for the route ws/page_in_use :param self: :return: """ # Arrange self.login_user() # Act response = self.client.post( "/ws/page_in_use/", { "page_url": "campaigns/American-Jerusalem/asset/mamcol.0930/", "user": self.user.id, "updated_on": datetime.now(), }, ) # Assert self.assert_post_successful(response) def test_PageInUse_delete_old_entries_post(self): """ This unit test tests the post entry for the route ws/page_in_use the database has two items added the created_on timestamp of now - 10 minutes :param self: :return: """ # Arrange self.login_user() time_threshold = datetime.now() - timedelta(minutes=10) page1 = PageInUse( page_url="foo.com/blah", user=self.user, created_on=time_threshold, updated_on=time_threshold, ) page1.save() page2 = PageInUse( page_url="bar.com/blah", user=self.user, created_on=time_threshold, updated_on=time_threshold, ) page2.save() # Act response = self.client.post( "/ws/page_in_use/", { "page_url": "campaigns/American-Jerusalem/asset/mamcol.0930/", "user": self.user.id, "updated_on": datetime.now(), }, ) # Assert self.assert_post_successful(response) def test_PageInUse_nologin_post(self): """ This unit test tests the post entry for the route ws/page_in_use without logging in :param self: :return: """ # Arrange # create user self.user = User.objects.create(username="******", email="*****@*****.**") self.user.set_password("top_secret") self.user.save() # Act response = self.client.post( "/ws/page_in_use/", { "page_url": "campaigns/American-Jerusalem/asset/mamcol.0930/", "user": self.user.id, }, ) # Assert self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) # Verify the entry is not in the PagInUse table page_in_use = PageInUse.objects.all() self.assertEqual(len(page_in_use), 0) def test_PageInUse_nologin_anonymous_post(self): """ This unit test tests the post entry for the route ws/page_in_use without logging and the user is anonymous :param self: :return: """ # Arrange # create user self.user = User.objects.create(username="******", email="*****@*****.**") self.user.set_password("top_secret") self.user.save() # Act response = self.client.post( "/ws/page_in_use/", { "page_url": "campaigns/American-Jerusalem/asset/mamcol.0930/", "user": self.user.id, "updated_on": datetime.now(), }, ) # Assert self.assert_post_successful(response) def assert_post_successful(self, response): """ Check the results of a successful post and insert of a PageInUse database item :param response: :return: """ self.assertEqual(response.status_code, status.HTTP_201_CREATED) # Verify the entry is in the PagInUse table page_in_use = PageInUse.objects.all() self.assertEqual(len(page_in_use), 1) def test_PageInUse_get(self): """ This unit test tests the get entry for the route ws/page_in_use/url :param self: :return: """ # Arrange self.login_user() # Add two values to database PageInUse.objects.create(page_url="foo.com/blah", user=self.user) page_in_use = PageInUse.objects.create(page_url="bar.com/blah", user=self.user) # Act response = self.client.get("/ws/page_in_use/bar.com/blah/") # Assert self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertJSONEqual( str(response.content, encoding="utf8"), { "page_url": "bar.com/blah", "user": self.user.id, "updated_on": page_in_use.updated_on.strftime("%Y-%m-%dT%H:%M:%S.%fZ"), }, ) def test_PageInUseUser_get(self): """ This unit test tests the get entry for the route ws/page_in_use_user/user/url/ :param self: :return: """ # Arrange self.login_user() # create second user self.user2 = User.objects.create(username="******", email="*****@*****.**") self.user2.set_password("top_secret") self.user2.save() test_page_url = "foo.com/blah" # Add two values to database page_in_use = PageInUse.objects.create(page_url=test_page_url, user=self.user) PageInUse.objects.create(page_url="bar.com/blah", user=self.user2) # Act response = self.client.get("/ws/page_in_use_user/%s/%s/" % (self.user.id, test_page_url)) # Assert self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertJSONEqual( str(response.content, encoding="utf8"), { "page_url": test_page_url, "user": self.user.id, "updated_on": page_in_use.updated_on.strftime("%Y-%m-%dT%H:%M:%S.%fZ"), }, ) def test_PageInUse_put(self): """ This unit test tests the update of an existing PageInUse using PUT on route ws/page_in_use/url :return: """ # Arrange self.login_user() # Add a value to database page = PageInUse(page_url="foo.com/blah", user=self.user) page.save() min_update_time = page.created_on + timedelta(seconds=2) # sleep so update time can be tested against original time time.sleep(2) change_page_in_use = {"page_url": "foo.com/blah", "user": self.user.id} # Act response = self.client.put( "/ws/page_in_use_update/foo.com/blah/", data=json.dumps(change_page_in_use), content_type="application/json", ) # Assert self.assertEqual(response.status_code, status.HTTP_200_OK) updated_page = PageInUse.objects.filter(page_url="foo.com/blah") self.assertTrue(len(updated_page), 1) self.assertEqual(page.id, updated_page[0].id) self.assertTrue(updated_page[0].updated_on > min_update_time) def test_PageInUse_delete(self): """ This unit test tests the delete of an existing PageInUse using DELETE on route ws/page_in_use_delete/ :return: """ # Arrange self.login_user() # Add a value to database page = PageInUse(page_url="foo.com/blah", user=self.user) page.save() current_page_in_use_count = PageInUse.objects.all().count() # Act response = self.client.delete("/ws/page_in_use_delete/%s/" % "foo.com/blah") # Assert self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) deleted_page_in_use_count = PageInUse.objects.all().count() deleted_page = PageInUse.objects.filter(page_url="foo.com/blah") self.assertEqual(len(deleted_page), 0) self.assertEqual(current_page_in_use_count - 1, deleted_page_in_use_count) def test_Campaign_get(self): """ Test getting a Campaign object :return: """ # Arrange self.login_user() # create 2 campaigns self.campaign = Campaign( title="TextCampaign", slug="slug1", description="Campaign Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.campaign.save() self.campaign2 = Campaign( title="TextCampaign2", slug="slug2", description="Campaign2 Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.campaign2.save() # Act response = self.client.get("/ws/campaign/slug2/") # Assert self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertJSONEqual( str(response.content, encoding="utf8"), { "description": "Campaign2 Description", "end_date": None, "id": self.campaign2.id, "slug": "slug2", "start_date": None, "status": Status.EDIT, "s3_storage": False, "title": "TextCampaign2", 'projects': [], "assets": [], }, ) def test_Campaign_delete(self): """ Test deleting a Campaign object :return: """ # Arrange self.login_user() # create 2 campaigns self.campaign = Campaign( title="TextCampaign", slug="slug1", description="Campaign Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.campaign.save() self.campaign2 = Campaign( title="TextCampaign2", slug="slug2", description="Campaign2 Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.campaign2.save() current_campaign_count = Campaign.objects.all().count() # Act response = self.client.delete("/ws/campaign_delete/slug2/") # Assert self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) deleted_campaign_count = Campaign.objects.all().count() self.assertEqual(current_campaign_count - 1, deleted_campaign_count) def test_Campaign_by_id_get(self): """ Test getting a Campaign object by id :return: """ # Arrange self.login_user() # create 2 campaigns self.campaign = Campaign( title="TextCampaign", slug="slug1", description="Campaign Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.campaign.save() self.campaign2 = Campaign( title="TextCampaign2", slug="slug2", description="Campaign2 Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.campaign2.save() # Act response = self.client.get("/ws/campaign_by_id/%s/" % self.campaign2.id) # Assert self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertJSONEqual( str(response.content, encoding="utf8"), { "description": "Campaign2 Description", "end_date": None, "id": self.campaign2.id, "slug": "slug2", "start_date": None, "status": Status.EDIT, "s3_storage": False, "title": "TextCampaign2", 'projects': [], "assets": [], }, ) def test_get_assets_by_item(self): """ Test getting a list of assets by item :return: """ self.login_user() # Create a campaign self.campaign = Campaign( title="TextCampaign", slug="slug1", description="Campaign Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.campaign.save() # Create a project self.project = Project(title="A Project", slug="project-slug", campaign=self.campaign) self.project.save() # Create two items self.item1 = Item(title="item1", slug="item1", item_id="item1", campaign=self.campaign, project=self.project) self.item1.save() self.item2 = Item(title="item2", slug="item2", item_id="item2", campaign=self.campaign, project=self.project) self.item2.save() # Add 2 assets to item2, 1 asset to item1 self.asset = Asset(title="TestAsset", slug="Asset1", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, campaign=self.campaign, metadata={"key": "val2"}, status=Status.EDIT, item=self.item1) self.asset.save() self.asset2 = Asset(title="TestAsset2", slug="Asset2", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, campaign=self.campaign, metadata={"key": "val2"}, status=Status.EDIT, item=self.item1) self.asset2.save() self.asset3 = Asset(title="TestAsset3", slug="Asset3", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, campaign=self.campaign, metadata={"key": "val2"}, status=Status.EDIT, item=self.item2) self.asset3.save() # Act response = self.client.get("/ws/item_by_id/item1/") json_resp = json.loads(response.content) # Assert self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(json_resp["assets"]), 2) def test_get_assets_by_campaign(self): """ Test getting a list of assets by campaign :return: """ # Arrange self.login_user() # create 2 campaigns self.campaign = Campaign( title="TextCampaign", slug="slug1", description="Campaign Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.campaign.save() self.campaign2 = Campaign( title="TextCampaign2", slug="slug2", description="Campaign2 Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.campaign2.save() # Add 2 assets to campaign2, 1 asset to campaign1 self.asset = Asset( title="TestAsset", slug="Asset1", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, campaign=self.campaign2, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset.save() self.asset2 = Asset( title="TestAsset2", slug="Asset2", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, campaign=self.campaign2, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset2.save() self.asset3 = Asset( title="TestAsset3", slug="Asset3", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, campaign=self.campaign, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset3.save() # Act response = self.client.get("/ws/asset/slug2/") json_resp = json.loads(response.content) # Assert self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(json_resp["results"]), 2) def test_Asset_Update_put(self): """ Test updating an asset by campaign and slug to inactive :return: """ # Arrange self.login_user() self.maxDiff = None self.campaign = Campaign( title="TextCampaign", slug="slug1", description="Campaign Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.campaign.save() self.asset = Asset( title="TestAsset", slug="Asset1", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, campaign=self.campaign, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset.save() expected_response = { "id": self.asset.id, "title": "TestAsset3", "slug": "Asset3", "description": "Asset Description", "media_url": "http://www.foo.com/1/2/3", "media_type": "IMG", "campaign": { "id": self.campaign.id, "slug": "slug1", "title": "TextCampaign", "description": "Campaign Description", "s3_storage": False, "start_date": None, "end_date": None, "status": "Edit", 'projects': [], "assets": [{ "title": "TestAsset3", "slug": "Asset3", "description": "Asset Description", "media_url": "http://www.foo.com/1/2/3", "media_type": "IMG", "sequence": 1, "metadata": { "key": "val2" }, "status": "Edit", }], }, "project": None, "sequence": 1, "metadata": { "key": "val2" }, "status": "Edit", } # Act asset_update = { "campaign": self.campaign.slug, "slug": self.asset.slug } # Act response = self.client.put( "/ws/asset_update/%s/%s/" % (self.campaign.slug, self.asset.slug), data=json.dumps(asset_update), content_type="application/json", ) # Assert self.assertEqual(response.status_code, status.HTTP_200_OK) updated_asset = Asset.objects.get(slug=self.asset.slug) self.assertEqual(updated_asset.status, Status.INACTIVE) def test_get_assets_by_campaign_and_slug(self): """ Test getting an asset by campaign and slug :return: """ # Arrange self.login_user() self.maxDiff = None # create 2 campaigns self.campaign = Campaign( title="TextCampaign", slug="slug1", description="Campaign Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.campaign.save() self.campaign2 = Campaign( title="TextCampaign2", slug="slug2", description="Campaign2 Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.campaign2.save() # Add 2 assets to campaign2, 1 asset to campaign1 self.asset = Asset( title="TestAsset", slug="Asset1", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, campaign=self.campaign2, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset.save() self.asset2 = Asset( title="TestAsset2", slug="Asset2", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, campaign=self.campaign2, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset2.save() self.asset3 = Asset( title="TestAsset3", slug="Asset3", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, campaign=self.campaign, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset3.save() expected_response = { "id": self.asset3.id, "title": "TestAsset3", "slug": "Asset3", "description": "Asset Description", "media_url": "http://www.foo.com/1/2/3", "media_type": "IMG", "campaign": { "id": self.campaign.id, "slug": "slug1", "title": "TextCampaign", "description": "Campaign Description", "s3_storage": False, "start_date": None, "end_date": None, "status": "Edit", 'projects': [], "assets": [{ "id": self.asset3.id, "title": "TestAsset3", "slug": "Asset3", "description": "Asset Description", "media_url": "http://www.foo.com/1/2/3", "media_type": "IMG", "sequence": 1, "metadata": { "key": "val2" }, "status": "Edit", }], }, "project": None, "sequence": 1, "metadata": { "key": "val2" }, "status": "Edit", } # Act response = self.client.get("/ws/asset_by_slug/slug1/Asset3/") # Assert self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertJSONEqual(force_text(response.content), expected_response) def test_get_assets_by_campaign_and_slug_no_match(self): """ Test getting an asset by campaign and slug using a slug that doesn't exist :return: """ # Arrange self.login_user() # create 2 campaigns self.campaign = Campaign( title="TextCampaign", slug="slug1", description="Campaign Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.campaign.save() self.campaign2 = Campaign( title="TextCampaign2", slug="slug2", description="Campaign2 Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.campaign2.save() # Add 2 assets to campaign2, 1 asset to campaign1 self.asset = Asset( title="TestAsset", slug="Asset1", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, campaign=self.campaign2, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset.save() self.asset2 = Asset( title="TestAsset2", slug="Asset2", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, campaign=self.campaign2, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset2.save() self.asset3 = Asset( title="TestAsset3", slug="Asset3", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, campaign=self.campaign, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset3.save() # Act response = self.client.get("/ws/asset_by_slug/slugxxx/Asset3xxx/") # Assert self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertJSONEqual( force_text(response.content), { "title": "", "slug": "", "description": "", "media_url": "", "media_type": None, "campaign": { "description": "", "end_date": None, "s3_storage": False, "slug": "", "start_date": None, "status": None, "assets": [], 'projects': [], "title": "", }, "sequence": None, "metadata": None, 'project': { 'metadata': None, 'slug': '', 'is_publish': False, 'status': None, 'title': '' }, "status": None, }, ) def test_PageInUse_filter_get(self): """ Test the route ws/page_in_use_filter/user/page_url/ It should return a list of PageInUse updated in last 5 minutes by user other than self.user :return: """ # Arrange self.login_user() # create a second user username = "******" test_url = "bar.com/blah" self.user2 = User.objects.create(username=username, email="*****@*****.**") self.user2.set_password("top_secret") self.user2.save() # Add values to database PageInUse.objects.create(page_url="foo.com/blah", user=self.user) PageInUse.objects.create(page_url=test_url, user=self.user2) # Act response = self.client.get("/ws/page_in_use_filter/%s/%s/" % (self.user.username, test_url)) json_resp = json.loads(response.content) # Assert self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertTrue(len(json_resp["results"]) > 0) def test_PageInUse_filter_no_pages_get(self): """ Test the route ws/page_in_use_filter/user/page_url/ It should return an empty list :return: """ # Arrange self.login_user() # create a second user username = "******" test_url = "bar.com/blah" self.user2 = User.objects.create(username=username, email="*****@*****.**") self.user2.set_password("top_secret") self.user2.save() # Act response = self.client.get("/ws/page_in_use_filter/%s/%s/" % (self.user.username, test_url)) json_resp = json.loads(response.content) # Assert self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(json_resp["results"]), 0) def test_Transcriptions_latest_get(self): """ Test getting latest transcription for an asset. route ws/transcriptions/asset/ :return: """ # Arrange self.login_user() # create a second user username = "******" self.user2 = User.objects.create(username=username, email="*****@*****.**") self.user2.set_password("top_secret") self.user2.save() # create a campaign self.campaign = Campaign( title="TextCampaign", slug="www.foo.com/slug2", description="Campaign Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.campaign.save() # create Assets self.asset = Asset( title="TestAsset", slug="www.foo.com/slug1", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, campaign=self.campaign, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset.save() self.asset2 = Asset( title="TestAsset2", slug="www.foo.com/slug2", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, campaign=self.campaign, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset2.save() # add Transcription objects self.transcription = Transcription(asset=self.asset, user_id=self.user.id, status=Status.EDIT, text="T1") self.transcription.save() t2_text = "T2" self.transcription2 = Transcription(asset=self.asset, user_id=self.user2.id, status=Status.EDIT, text=t2_text) self.transcription2.save() # Act response = self.client.get("/ws/transcription/%s/" % self.asset.id) json_resp = json.loads(response.content) # Assert self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(json_resp["text"], t2_text) def test_Transcriptions_by_user(self): """ Test getting the user's transcriptions. route ws/transcription_by_user/<userid>/ :return: """ # Arrange self.login_user() # create a second user username = "******" self.user2 = User.objects.create(username=username, email="*****@*****.**") self.user2.set_password("top_secret") self.user2.save() # create a campaign self.campaign = Campaign( title="TextCampaign", slug="www.foo.com/slug2", description="Campaign Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.campaign.save() # create Assets self.asset = Asset( title="TestAsset", slug="www.foo.com/slug1", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, campaign=self.campaign, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset.save() self.asset2 = Asset( title="TestAsset2", slug="www.foo.com/slug2", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, campaign=self.campaign, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset2.save() # add Transcription objects t1_text = "T1" self.transcription = Transcription(asset=self.asset, user_id=self.user.id, status=Status.EDIT, text=t1_text) self.transcription.save() t2_text = "T2" self.transcription2 = Transcription(asset=self.asset, user_id=self.user2.id, status=Status.EDIT, text=t2_text) self.transcription2.save() t3_text = "T3" self.transcription3 = Transcription(asset=self.asset, user_id=self.user.id, status=Status.EDIT, text=t3_text) self.transcription3.save() # Act response = self.client.get("/ws/transcription_by_user/%s/" % self.user.id) json_resp = json.loads(response.content) transcriptions_array = [] for trans in json_resp["results"]: transcriptions_array.append(trans["text"]) # Assert self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(json_resp["count"], 2) self.assertTrue("T3" in transcriptions_array) self.assertTrue("T1" in transcriptions_array) self.assertFalse("T2" in transcriptions_array) def test_Transcriptions_create_post(self): """ Test creating a transcription. route ws/transcription_create/ :return: """ # Arrange self.login_user() # create a campaign self.campaign = Campaign( title="TextCampaign", slug="www.foo.com/slug2", description="Campaign Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.campaign.save() # create Assets self.asset = Asset( title="TestAsset", slug="www.foo.com/slug1", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, campaign=self.campaign, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset.save() # Act response = self.client.post( "/ws/transcription_create/", { "asset": self.asset.id, "user_id": self.user.id, "status": Status.EDIT, "text": "T1", }, ) # Assert self.assertEqual(response.status_code, status.HTTP_201_CREATED) # Get all Transcriptions for the asset transcriptions_count = Transcription.objects.filter( asset=self.asset).count() self.assertEqual(transcriptions_count, 1) # Add Another transcription response = self.client.post( "/ws/transcription_create/", { "asset": self.asset.id, "user_id": self.user.id, "status": Status.EDIT, "text": "T2", }, ) # Get all Transcriptions for the asset, should be another one transcriptions_count = Transcription.objects.filter( asset=self.asset).count() self.assertEqual(transcriptions_count, 2) def test_Tag_create_post(self): """ Test creating a tag. route ws/tag_create/ :return: """ # Arrange self.login_user() # create a campaign self.campaign = Campaign( title="TextCampaign", slug="www.foo.com/slug2", description="Campaign Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.campaign.save() # create Assets self.asset = Asset( title="TestAsset", slug="www.foo.com/slug1", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, campaign=self.campaign, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset.save() # Act response = self.client.post( "/ws/tag_create/", { "campaign": self.campaign.slug, "asset": self.asset.slug, "user_id": self.user.id, "name": "T1", "value": "T1", }, ) # Assert self.assertEqual(response.status_code, status.HTTP_200_OK) def test_Tag_delete(self): """ Test deleting a tag. route ws/tag_/ :return: """ # Arrange self.login_user() # create a campaign self.campaign = Campaign( title="TextCampaign", slug="campaignslug", description="Campaign Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.campaign.save() # create Assets self.asset = Asset( title="TestAsset", slug="assetslug1", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, campaign=self.campaign, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset.save() self.tag1 = Tag(name="Tag1", value="Tag1") self.tag1.save() self.tag2 = Tag(name="Tag2", value="Tag2") self.tag2.save() # Save for User1 self.asset_tag_collection = UserAssetTagCollection( asset=self.asset, user_id=self.user.id) self.asset_tag_collection.save() self.asset_tag_collection.tags.add(self.tag1, self.tag2) # Act url = "/ws/tag_delete/%s/%s/%s/%s/" % ( self.campaign.slug, self.asset.slug, "Tag1", self.user.id, ) response = self.client.delete(url, follow=True) # Assert self.assertEqual(response.status_code, status.HTTP_200_OK) # verify only 1 tag in db remaining_tags = Tag.objects.all() self.assertEqual(len(remaining_tags), 1) def test_Tag_create_with_an_existing_tag_post(self): """ Test creating a tag, adding to an asset that already has a tag. route ws/tag_create/ :return: """ # Arrange self.login_user() # create a campaign self.campaign = Campaign( title="TextCampaign", slug="www.foo.com/slug2", description="Campaign Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.campaign.save() # create Assets self.asset = Asset( title="TestAsset", slug="www.foo.com/slug1", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, campaign=self.campaign, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset.save() # Act response = self.client.post( "/ws/tag_create/", { "campaign": self.campaign.slug, "asset": self.asset.slug, "user_id": self.user.id, "name": "T1", "value": "T1", }, ) response = self.client.post( "/ws/tag_create/", { "campaign": self.campaign.slug, "asset": self.asset.slug, "user_id": self.user.id, "name": "T2", "value": "T3", }, ) # Assert self.assertEqual(response.status_code, status.HTTP_200_OK) def test_GetTags_get(self): """ Test getting the tags for an asset, route /ws/tags/<asset> :return: """ # Arrange self.login_user() # create a second user username = "******" self.user2 = User.objects.create(username=username, email="*****@*****.**") self.user2.set_password("top_secret") self.user2.save() # create a campaign self.campaign = Campaign( title="TextCampaign", slug="www.foo.com/slug2", description="Campaign Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.campaign.save() # create Assets self.asset = Asset( title="TestAsset", slug="www.foo.com/slug1", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, campaign=self.campaign, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset.save() self.tag1 = Tag(name="Tag1", value="Tag1") self.tag1.save() self.tag2 = Tag(name="Tag2", value="Tag2") self.tag2.save() self.tag3 = Tag(name="Tag3", value="Tag3") self.tag3.save() # Save for User1 self.asset_tag_collection = UserAssetTagCollection( asset=self.asset, user_id=self.user.id) self.asset_tag_collection.save() self.asset_tag_collection.tags.add(self.tag1, self.tag2) # Save for User2 self.asset_tag_collection2 = UserAssetTagCollection( asset=self.asset, user_id=self.user2.id) self.asset_tag_collection2.save() self.asset_tag_collection2.tags.add(self.tag3) # Act response = self.client.get("/ws/tags/%s/" % self.asset.id) json_resp = json.loads(response.content) # Assert self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(json_resp["results"]), 3) def test_GetTags_notags_get(self): """ Test getting the tags for an asset when no tags exist, route /ws/tags/<asset> :return: """ # Arrange self.login_user() # create a second user username = "******" self.user2 = User.objects.create(username=username, email="*****@*****.**") self.user2.set_password("top_secret") self.user2.save() # create a campaign self.campaign = Campaign( title="TextCampaign", slug="www.foo.com/slug2", description="Campaign Description", metadata={"key": "val1"}, status=Status.EDIT, ) self.campaign.save() # create Assets self.asset = Asset( title="TestAsset", slug="www.foo.com/slug1", description="Asset Description", media_url="http://www.foo.com/1/2/3", media_type=MediaType.IMAGE, campaign=self.campaign, metadata={"key": "val2"}, status=Status.EDIT, ) self.asset.save() # Act response = self.client.get("/ws/tags/%s/" % self.asset.id) json_resp = json.loads(response.content) # Assert self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(json_resp["results"]), 0)