Skip to content

Commit

Permalink
test: add new tests
Browse files Browse the repository at this point in the history
  • Loading branch information
rpenido committed Nov 3, 2023
1 parent a6919a1 commit f030767
Show file tree
Hide file tree
Showing 3 changed files with 119 additions and 11 deletions.
21 changes: 16 additions & 5 deletions openedx_tagging/core/tagging/rest_api/v1/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,17 +186,28 @@ class TaxonomyImportBodySerializer(serializers.Serializer): # pylint: disable=a
taxonomy_description = serializers.CharField(default="")
file = serializers.FileField(required=True)

def get_parser_format(self, obj):
def validate_file(self, file):
"""
Validates the file extension
"""
filename = file.name
ext = filename.split('.')[-1]
parser_format = getattr(ParserFormat, ext.upper(), None)
if not parser_format:
raise serializers.ValidationError(f'File type not supported: {ext.lower()}')

return file

def get_parser_format(self, obj) -> ParserFormat:
"""
Returns the ParserFormat based on the file extension
"""
filename = obj["file"].name
ext = filename.split('.')[-1]
parser_format = getattr(ParserFormat, ext.upper(), None)
if parser_format:
return parser_format
else:
raise serializers.ValidationError(f'File type not supported: ${ext.lower()}')
assert parser_format, f'File type not supported: ${ext.lower()}'

return parser_format

def to_internal_value(self, data):
"""
Expand Down
4 changes: 2 additions & 2 deletions openedx_tagging/core/tagging/rest_api/v1/views_import.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

import os

from django.http import FileResponse, Http404, HttpResponse
from django.http import FileResponse, Http404, HttpResponse, HttpResponseBadRequest
from rest_framework.request import Request
from rest_framework.views import APIView

Expand Down Expand Up @@ -95,4 +95,4 @@ def post(self, request: Request, *args, **kwargs) -> HttpResponse:
if import_success:
return HttpResponse(status=200)
else:
return HttpResponse(status=400)
return HttpResponseBadRequest("Error importing taxonomy")
105 changes: 101 additions & 4 deletions tests/openedx_tagging/core/tagging/test_views_import.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,28 +45,48 @@ def test_download_method_not_allowed(self):
assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED


@ddt.ddt
class TestImportView(APITestCase):
"""
Tests the import taxonomy view.
"""

def test_import(self):
def _get_file(self, tags: list, file_format: str) -> SimpleUploadedFile:
"""
Returns a file for the given format.
"""
if file_format == "csv":
csv_data = "id,value"
for tag in tags:
csv_data += f"\n{tag['id']},{tag['value']}"
return SimpleUploadedFile("taxonomy.csv", csv_data.encode(), content_type="text/csv")
else: # json
json_data = {"tags": tags}
return SimpleUploadedFile("taxonomy.json", json.dumps(json_data).encode(), content_type="application/json")

@ddt.data(
"csv",
"json",
)
def test_import(self, file_format: str) -> None:
"""
Tests importing a valid taxonomy file.
"""
url = TAXONOMY_IMPORT_URL
new_tags = [
{"id": "tag_1", "value": "Tag 1"},
{"id": "tag_2", "value": "Tag 2"},
{"id": "tag_3", "value": "Tag 3"},
{"id": "tag_4", "value": "Tag 4"},
]
json_data = {"tags": new_tags}
file = SimpleUploadedFile("taxonomy.json", json.dumps(json_data).encode(), content_type="application/json")
file = self._get_file(new_tags, file_format)

response = self.client.post(
url,
{
"taxonomy_name": "Imported Taxonomy name",
"taxonomy_description": "Imported Taxonomy description",
"file": file
"file": file,
},
format="multipart"
)
Expand All @@ -81,3 +101,80 @@ def test_import(self):
assert len(tags) == len(new_tags)
for i, tag in enumerate(tags):
assert tag.value == new_tags[i]["value"]

def test_import_no_file(self) -> None:
"""
Tests importing a taxonomy without a file.
"""
url = TAXONOMY_IMPORT_URL
response = self.client.post(
url,
{
"taxonomy_name": "Imported Taxonomy name",
"taxonomy_description": "Imported Taxonomy description",
},
format="multipart"
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert response.data["file"][0] == "No file was submitted."

@ddt.data(
"csv",
"json",
)
def test_import_no_name(self, file_format) -> None:
"""
Tests importing a taxonomy without specifing a name.
"""
url = TAXONOMY_IMPORT_URL
file = SimpleUploadedFile(f"taxonomy.{file_format}", b"invalid file content")
response = self.client.post(
url,
{
"taxonomy_description": "Imported Taxonomy description",
"file": file,
},
format="multipart"
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert response.data["taxonomy_name"][0] == "This field is required."

def test_import_invalid_format(self) -> None:
"""
Tests importing a taxonomy with an invalid file format.
"""
url = TAXONOMY_IMPORT_URL
file = SimpleUploadedFile("taxonomy.invalid", b"invalid file content")
response = self.client.post(
url,
{
"taxonomy_name": "Imported Taxonomy name",
"taxonomy_description": "Imported Taxonomy description",
"file": file,
},
format="multipart"
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert response.data["file"][0] == "File type not supported: invalid"

@ddt.data(
"csv",
"json",
)
def test_import_invalid_content(self, file_format) -> None:
"""
Tests importing a taxonomy with an invalid file content.
"""
url = TAXONOMY_IMPORT_URL
file = SimpleUploadedFile(f"taxonomy.{file_format}", b"invalid file content")
response = self.client.post(
url,
{
"taxonomy_name": "Imported Taxonomy name",
"taxonomy_description": "Imported Taxonomy description",
"file": file,
},
format="multipart"
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert response.content == b"Error importing taxonomy"

0 comments on commit f030767

Please sign in to comment.