Skip to content
This repository has been archived by the owner on Dec 5, 2023. It is now read-only.

Commit

Permalink
Merge 74e4e71 into bdfeb4d
Browse files Browse the repository at this point in the history
  • Loading branch information
vleong2332 committed Jun 8, 2016
2 parents bdfeb4d + 74e4e71 commit 362a8ed
Show file tree
Hide file tree
Showing 6 changed files with 71 additions and 26 deletions.
4 changes: 2 additions & 2 deletions td/api/urls.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
from django.conf.urls import url

from .views import questionnaire_json, templanguages_json, lang_assignment_json, lang_assignment_changed_json
from .views import QuestionnaireView, templanguages_json, lang_assignment_json, lang_assignment_changed_json


urlpatterns = [
url(r"^questionnaire/$", questionnaire_json, name="questionnaire"),
url(r"^questionnaire/$", QuestionnaireView.as_view(), name="questionnaire"),
url(r"^templanguages/$", templanguages_json, name="templanguages"),
url(r"^templanguages/assignment/$", lang_assignment_json, name="templanguages_assignment"),
url(r"^templanguages/assignment/changed/$", lang_assignment_changed_json, name="templanguages_changed"),
Expand Down
42 changes: 29 additions & 13 deletions td/api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,53 +2,69 @@

from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import View

from td.models import TempLanguage, Country
from td.resources.models import Questionnaire


# I admit this is not the best solution nor a good practice. Our goal is to use the django REST framework to receive
# temporary language submission in the future.
@csrf_exempt
def questionnaire_json(request):
if request.method == "GET":
class QuestionnaireView(View):

# I admit this is not the best solution nor a good practice. Our goal is to use the django REST framework to receive
# temporary language submission in the future.
@csrf_exempt
def dispatch(self, request, *args, **kwargs):
return super(QuestionnaireView, self).dispatch(request, *args, **kwargs)

def get(self, request, *args, **kwargs):
# In the future, when we're ready to accommodate translations of the questionnaires, we should iterate through
# the queryset and construct the data content appropriately.
questionnaire = Questionnaire.objects.latest("created_at")
data = {
"languages": [
{
"name": questionnaire.language.ln,
"dir": questionnaire.language.direction,
"dir": questionnaire.language.get_direction_display(),
"slug": questionnaire.language.lc,
"questionnaire_id": questionnaire.id,
"language_data": questionnaire.language_data,
"questions": questionnaire.questions,
}
]
}
return JsonResponse(data, safe=False)
elif request.method == "POST":

@csrf_exempt
def post(self, request, *args, **kwargs):
# First pass only. Will need more validation and refactoring
try:
message = ""
data = request.POST
data = request.POST if len(request.POST) else json.loads(request.body)
questionnaire = Questionnaire.objects.get(pk=data.get("questionnaire_id"))
field_mapping = questionnaire.field_mapping
answers = json.loads(data.get("answers")) if len(request.POST) else data.get("answers")

obj = TempLanguage(code=data.get("temp_code"), questionnaire=questionnaire, app=data.get("app"),
request_id=data.get("request_id"), requester=data.get("requester"),
answers=json.loads(data.get("answers")))
answers=answers)

for a in json.loads(data.get("answers")):
qid = a.get("question_id")
for answer in answers:
qid = str(answer.get("question_id"))
if qid is not None and qid in field_mapping:
answer_text = answer.get("text")
if field_mapping[qid] == "country":
obj.country = Country.objects.get(name__iexact=a["text"])
obj.country = Country.objects.get(name__iexact=answer_text)
elif field_mapping[qid] == "direction":
obj.direction = "l" if answer_text.lower() == "yes" else "r"
else:
obj.__dict__[field_mapping[qid]] = a["text"]
obj.__dict__[field_mapping[qid]] = answer_text

obj.save()

except Questionnaire.DoesNotExist:
message = "questionnaire_id given does not return a matching Questionnaire object"
except Country.DoesNotExist:
message = "The answer for country results in an invalid lookup"
except Exception as e:
message = e.message

Expand Down
13 changes: 13 additions & 0 deletions td/resources/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,15 @@
from td.models import Language


NAME_TO_PROPERTY = {
"name": "ln",
"code": "lc",
"direction": "ld",
"country": "cc",
"region": "lr"
}


def transform_country_data(data):
tree = {"name": "World", "parent": None, "children": []}
for code in data:
Expand Down Expand Up @@ -123,6 +132,10 @@ class Questionnaire(models.Model):
def __str__(self):
return str(self.pk)

@property
def language_data(self):
return {NAME_TO_PROPERTY.get(field_name): int(qid) for qid, field_name in self.field_mapping.items()}

@property
def grouped_questions(self):
group = []
Expand Down
15 changes: 8 additions & 7 deletions td/tests/api/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from django.test import TestCase
from djcelery.tests.req import RequestFactory

from td.api.views import questionnaire_json, templanguages_json, lang_assignment_json, lang_assignment_changed_json
from td.api.views import QuestionnaireView, templanguages_json, lang_assignment_json, lang_assignment_changed_json
from td.models import Language, TempLanguage, Country
from td.resources.models import Questionnaire

Expand Down Expand Up @@ -38,13 +38,14 @@ def setUp(self):
field_mapping = {"0": "name", "1": "country"}
self.questionnaire = Questionnaire.objects.create(pk=999, language=lang, questions=json.dumps(questions),
field_mapping=field_mapping)
self.view = QuestionnaireView()

def test_get(self):
"""
Request should successfully return a JsonResponse
"""
request = RequestFactory().get(reverse("api:questionnaire"))
response = questionnaire_json(request)
response = self.view.get(request)
self.assertEqual(response.status_code, 200)
self.assertEqual(response["Content-Type"], "application/json")

Expand All @@ -61,7 +62,7 @@ def test_post_success(self):
"answers": json.dumps([{"question_id": "0", "text": "answer"}, {"question_id": "1", "text": "narnia"}])
}
request = RequestFactory().post(reverse("api:questionnaire"), data=data)
response = questionnaire_json(request)
response = self.view.post(request)
self.assertEqual(response.status_code, 200)
self.assertEqual(response["Content-Type"], "application/json")
content = json.loads(response.content)
Expand All @@ -83,10 +84,10 @@ def test_post_error_country(self):
"answers": json.dumps([{"question_id": "0", "text": "answer"}, {"question_id": "1", "text": "oz"}])
}
request = RequestFactory().post(reverse("api:questionnaire"), data=data)
content = json.loads(questionnaire_json(request).content)
content = json.loads(self.view.post(request).content)
self.assertEqual(content["status"], "error")
self.assertGreater(len(content["message"]), 0)
self.assertIn("Country", content["message"])
self.assertIn("country", content["message"].lower())

def test_post_error_questionnaire(self):
"""
Expand All @@ -102,7 +103,7 @@ def test_post_error_questionnaire(self):
"answers": json.dumps([{"question_id": "0", "text": "answer"}, {"question_id": "1", "text": "narnia"}])
}
request = RequestFactory().post(reverse("api:questionnaire"), data=data)
content = json.loads(questionnaire_json(request).content)
content = json.loads(self.view.post(request).content)
self.assertEqual(content["status"], "error")
self.assertGreater(len(content["message"]), 0)
self.assertIn("Questionnaire", content["message"])
Expand All @@ -120,7 +121,7 @@ def test_post_integrity_error(self):
"answers": json.dumps([{"question_id": "0", "text": "answer"}, {"question_id": "1", "text": "narnia"}])
}
request = RequestFactory().post(reverse("api:questionnaire"), data=data)
content = json.loads(questionnaire_json(request).content)
content = json.loads(self.view.post(request).content)
self.assertEqual(content["status"], "error")
self.assertGreater(len(content["message"]), 0)
self.assertIn("app", content["message"])
Expand Down
19 changes: 17 additions & 2 deletions td/tests/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@

from djcelery.tests.req import RequestFactory

from td.models import TempLanguage, Language
from td.models import TempLanguage, Language, WARegion
from td.resources.models import Questionnaire
from td.views import TempLanguageListView, TempLanguageDetailView, TempLanguageUpdateView, AjaxTemporaryCode,\
TempLanguageAdminView, TempLanguageWizardView, LanguageDetailView
TempLanguageAdminView, TempLanguageWizardView, LanguageDetailView, WARegionDetailView
from td.forms import TempLanguageForm


Expand All @@ -38,6 +38,21 @@ def create_user():
)


class WARegionDetailViewTestCase(TestCase):

def setUp(self):
self.object = WARegion.objects.create(name="Middle Earth", slug="middleearth")

# @patch("td.views.WARegionDetailView.get_object")
def test_get_context_data(self):
view = setup_view(WARegionDetailView())
view.object = self.object
view.get_object = Mock(return_value=self.object)
context = view.get_context_data()
self.assertIn("gl_directors", context)
self.assertIn("gl_helpers", context)


class LanguageDetailViewTestCase(TestCase):
def setUp(self):
self.request = RequestFactory().get("uw/languages/")
Expand Down
4 changes: 2 additions & 2 deletions td/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -572,11 +572,9 @@ def form_valid(self, form):
"success": True,
"object": self.object,
}
print "- self.object is ", self.object
temp_lang = self.object.templanguage
temp_lang.status = "a"
temp_lang.save()
print "- templang.lang_assigned is ", temp_lang.lang_assigned
return render(self.request, "resources/language_modal_form.html", context)


Expand Down Expand Up @@ -719,6 +717,8 @@ def done(self, form_list, **kwargs):
try:
if field_mapping[qid] == "country":
obj.country = Country.objects.get(name__iexact=a["text"])
elif field_mapping[qid] == "direction":
obj.direction = "l" if a["text"].lower() == "yes" else "r"
else:
obj.__dict__[field_mapping[qid]] = a["text"]
except Country.DoesNotExist:
Expand Down

0 comments on commit 362a8ed

Please sign in to comment.