class TestErrorViewSet(ApiAccessMixinTest, MyTestCase): namespace = 'api:v0:errors' def setUp(self): super(TestErrorViewSet, self).setUp() self.unit_lesson_error = UnitLesson( unit=self.unit, order=0, lesson=self.lesson, addedBy=self.user, treeID=self.lesson.id ) self.unit_lesson_error.save() self.student_error = StudentError( response=self.resp1, errorModel=self.unit_lesson_error, author=self.user ) self.student_error.save() def test_serializer_em_data(self): response = self.client.get(reverse(self.namespace, kwargs={'course_id': self.course.id})) fields_set = set([ 'id', 'lesson_concept_id', 'lesson_concept_isAbort', 'lesson_concept_isFail', 'lesson_text', 'treeID' ]) em_data_set = set(json.loads(response.content)[0]['em_data']) self.assertSetEqual(fields_set, em_data_set)
def setUp(self): self.user = User.objects.create_user(username='******', password='******') self.course = Course(title='test_title', addedBy=self.user) self.course.save() self.concept = Concept(title='test title', addedBy=self.user) self.concept.save() self.lesson = Lesson(title='ugh', text='brr', addedBy=self.user, kind=Lesson.ORCT_QUESTION) self.lesson.save_root() self.lesson.add_concept_link(self.concept, ConceptLink.TESTS, self.user) self.unit = Unit(title='test unit title', addedBy=self.user) self.unit.save() self.unit_lesson = UnitLesson(unit=self.unit, addedBy=self.user, treeID=42, lesson=self.lesson) self.unit_lesson.save() self.response = Response(course=self.course, lesson=self.lesson, author=self.user, unitLesson=self.unit_lesson, confidence=Response.GUESS, title='test title', text='test text') self.response.save() self.context = { 'actionTarget': '/ct/courses/1/units/1/', 'ul': self.unit_lesson, 'test_text': 'This is a test text', 'r': self.response }
def test_simple_chat_flow(fsm, enroll_unit_code, client, user): """ Try to test very simply chat flow. """ get_specs()[0].save_graph('admin') get_specs_additional()[0].save_graph('admin') get_specs_resource()[0].save_graph('admin') get_specs_faq()[0].save_graph('admin') lesson = Lesson(title='title', text='きつね', addedBy=user, url='/test/url/') lesson.save() unitlesson = UnitLesson(unit=enroll_unit_code.courseUnit.unit, order=0, lesson=lesson, addedBy=user, treeID=lesson.id) unitlesson.save() client.login(username='******', password='******') page = Session(enroll_unit_code, client) page.create_session() assert page.show_input() is None assert len(page.show_messages()) == 3 assert page.show_extras() == {'updates': {'threadId': None}}
def setUp(self): self.username, self.password = '******', 'test' self.user = User.objects.create_user('test', '*****@*****.**', 'test') self.instructor = Instructor.objects.create(user=self.user, institution='institute', what_do_you_teach='something') self.user2 = User.objects.create_user('test1', '*****@*****.**', 'test') self.instructor2 = Instructor.objects.create(user=self.user2, institution='institution', what_do_you_teach='something') self.unit = Unit(title='Test title', addedBy=self.user) self.unit.save() self.course = Course(title='Test title', description='test description', access='Public', enrollCode='111', lockout='222', addedBy=self.user) self.course.save() self.courseunit = CourseUnit( unit=self.unit, course=self.course, order=0, addedBy=self.user, releaseTime=timezone.now() ) self.courseunit.save() self.lesson = Lesson(title='title', text='text', addedBy=self.user) self.lesson.save() self.unitlesson = UnitLesson( unit=self.unit, order=0, lesson=self.lesson, addedBy=self.user, treeID=self.lesson.id ) self.unitlesson.save() self.client.login(username=self.username, password=self.password) self.url = reverse('ctms:my_courses')
class TestErrorViewSet(ApiAccessMixinTest, MyTestCase): namespace = 'api:v0:errors' def setUp(self): super(TestErrorViewSet, self).setUp() concept = Concept(title='test title', addedBy=self.user) concept.save() self.lesson.concept = concept self.lesson.save() self.unit_lesson_error = UnitLesson(unit=self.unit, order=0, lesson=self.lesson, addedBy=self.user, treeID=self.lesson.id) self.unit_lesson_error.save() self.student_error = StudentError(response=self.resp1, errorModel=self.unit_lesson_error, author=self.user) self.student_error.save() def test_serializer_em_data(self): response = self.client.get( reverse(self.namespace, kwargs={'course_id': self.course.id})) fields_set = set([ 'id', 'lesson_concept_id', 'lesson_concept_isAbort', 'lesson_concept_isFail', 'lesson_text', 'treeID' ]) em_data_set = set(json.loads(response.content)[0]['em_data']) self.assertSetEqual(fields_set, em_data_set)
def setUp(self): self.user = User.objects.create_user(username='******', password='******') self.client.login(username='******', password='******') self.course = Course(title='test_title', addedBy=self.user) self.course.save() self.unit = Unit(title='test unit title', addedBy=self.user) self.unit.save() self.course_unit = CourseUnit(course=self.course, unit=self.unit, order=0, addedBy=self.user) self.course_unit.save() self.role = Role(course=self.course, user=self.user, role=Role.INSTRUCTOR) self.role.save() self.concept = Concept.new_concept('bad', 'idea', self.unit, self.user) self.lesson = Lesson(title='New York Test Lesson', text='brr', addedBy=self.user) self.lesson.save_root(self.concept) self.unit_lesson = UnitLesson(unit=self.unit, lesson=self.lesson, addedBy=self.user, treeID=self.lesson.id) self.unit_lesson.save()
class ConceptsTests(TestCase): def setUp(self): self.user = User.objects.create_user(username='******', password='******') self.client.login(username='******', password='******') self.course = Course(title='test_title', addedBy=self.user) self.course.save() self.unit = Unit(title='test unit title', addedBy=self.user) self.unit.save() self.course_unit = CourseUnit(course=self.course, unit=self.unit, order=0, addedBy=self.user) self.course_unit.save() self.role = Role(course=self.course, user=self.user, role=Role.INSTRUCTOR) self.role.save() self.concept = Concept.new_concept('bad', 'idea', self.unit, self.user) self.lesson = Lesson(title='New York Test Lesson', text='brr', addedBy=self.user) self.lesson.save_root(self.concept) self.unit_lesson = UnitLesson(unit=self.unit, lesson=self.lesson, addedBy=self.user, treeID=self.lesson.id) self.unit_lesson.save() def test_unit_concepts_search(self): self.lesson.concept = self.concept self.lesson.save() response = self.client.get( reverse('ct:unit_concepts', kwargs={'course_id': self.course.id, 'unit_id': self.unit.id}), {'search': 'New York'}, follow=True ) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'ct/concepts.html') self.assertIn('actionTarget', response.context) cset_dict = {i[0]: i[1] for i in response.context['cset']} self.assertIn('New York Test Lesson', cset_dict) self.assertIn('New York', cset_dict) self.assertIn('The New York Times Company', cset_dict)
def setUp(self): self.user = User.objects.create_user(username='******', password='******') self.client.login(username='******', password='******') self.course = Course(title='test_title', addedBy=self.user) self.course.save() self.unit = Unit(title='test unit title', addedBy=self.user) self.unit.save() self.course_unit = CourseUnit( course=self.course, unit=self.unit, order=0, addedBy=self.user ) self.course_unit.releaseTime = timezone.now() - datetime.timedelta(days=1) self.course_unit.save() self.enroll = EnrollUnitCode(courseUnit=self.course_unit) self.enroll.save() self.role = Role(course=self.course, user=self.user, role=Role.INSTRUCTOR) self.role.save() self.student_role = Role(course=self.course, user=self.user, role=Role.ENROLLED) self.student_role.save() self.concept = Concept.new_concept('bad', 'idea', self.unit, self.user) self.lesson = Lesson( title='New York Test Lesson', text='brr', addedBy=self.user, kind=Lesson.ORCT_QUESTION ) self.lesson.save_root(self.concept) self.unit_lesson = UnitLesson( unit=self.unit, lesson=self.lesson, addedBy=self.user, treeID=self.lesson.id, order=0 ) self.unit_lesson.save() self.unit_lesson_answer = UnitLesson( parent=self.unit_lesson, unit=self.unit, lesson=self.lesson, addedBy=self.user, treeID=self.lesson.id, kind=UnitLesson.ANSWERS ) self.unit_lesson_answer.save() self.user = User.objects.create_user(username='******', password='******') call_command('fsm_deploy')
def test_wikipedia_view(self): """ Check wikipedia view and concept addition method. """ url = '/ct/teach/courses/1/units/%d/concepts/wikipedia/%s/' % (self.unit.pk, urllib.quote('New York City')) response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertContains(response, 'City of New York') self.check_post_get(url, dict(task='add'), '/', 'City of New York') ul = UnitLesson.objects.get( lesson__concept__title='New York City', unit=self.unit ) # check UL & concept added self.assertTrue(ul in UnitLesson.search_sourceDB('New York City')[0]) self.assertTrue(ul in UnitLesson.search_sourceDB('New York City', unit=self.unit)[0])
def test_wikipedia_view(self): """ Check wikipedia view and concept addition method. """ url = '/ct/teach/courses/1/units/%d/concepts/wikipedia/%s/' % (self.unit.pk, urllib.parse.quote('New York City')) response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertContains(response, 'City of New York') self.check_post_get(url, dict(task='add'), '/', 'City of New York') ul = UnitLesson.objects.get( lesson__concept__title='New York City', unit=self.unit ) # check UL & concept added self.assertTrue(ul in UnitLesson.search_sourceDB('New York City')[0]) self.assertTrue(ul in UnitLesson.search_sourceDB('New York City', unit=self.unit)[0])
def setUp(self): self.user = User.objects.create_user(username="******", password="******") self.course = Course(title="test_title", addedBy=self.user) self.course.save() self.concept = Concept(title="test title", addedBy=self.user) self.concept.save() self.lesson = Lesson(title="ugh", text="brr", addedBy=self.user, kind=Lesson.ORCT_QUESTION) self.lesson.save_root() self.lesson.add_concept_link(self.concept, ConceptLink.TESTS, self.user) self.unit = Unit(title="test unit title", addedBy=self.user) self.unit.save() self.unit_lesson = UnitLesson(unit=self.unit, addedBy=self.user, treeID=42, lesson=self.lesson) self.unit_lesson.save() self.response = Response( course=self.course, lesson=self.lesson, author=self.user, unitLesson=self.unit_lesson, confidence=Response.GUESS, title="test title", text="test text", ) self.response.save() self.context = { "actionTarget": "/ct/courses/1/units/1/", "ul": self.unit_lesson, "test_text": "This is a test text", "r": self.response, }
def setUp(self): self.user = User.objects.create_user( username='******', email='jacob@_', password='******' ) # have to login or Django self.client.session storage won't work self.client.login(username='******', password='******') self.course = Course( title='Great Course', description='the bestest', addedBy=self.user ) self.course.save() self.unit = Unit(title='My Courselet', addedBy=self.user) self.unit.save() self.lesson = Lesson( title='Big Deal', text='very interesting info', addedBy=self.user ) self.lesson.save_root() self.unitLesson = UnitLesson.create_from_lesson( self.lesson, self.unit, order='APPEND' ) self.ulQ = create_question_unit(self.user) self.ulQ2 = create_question_unit( self.user, 'Pretest', 'Scary Question', 'Tell me something.' ) self.json_mixin = JSONBlobMixin() self.fsmDict = dict(name='test', title='try this') self.nodeDict = dict( START=dict(title='start here', path='ct:home', funcName='fsm.fsm_plugin.testme.START'), MID=dict(title='in the middle', path='ct:about', doLogging=True), END=dict(title='end here', path='ct:home') ) self.edgeDict = ( dict(name='next', fromNode='START', toNode='END', title='go go go'), dict(name='select_Lesson', fromNode='MID', toNode='MID', title='go go go'), )
def setUp(self): super(TestErrorViewSet, self).setUp() concept = Concept(title='test title', addedBy=self.user) concept.save() self.lesson.concept = concept self.lesson.save() self.unit_lesson_error = UnitLesson(unit=self.unit, order=0, lesson=self.lesson, addedBy=self.user, treeID=self.lesson.id) self.unit_lesson_error.save() self.student_error = StudentError(response=self.resp1, errorModel=self.unit_lesson_error, author=self.user) self.student_error.save()
def save(self, unit, user, ul, commit=True): should_create_ul = not self.instance.id self.instance.text = self.cleaned_data['answer'] self.instance.title = 'Answer' self.instance.addedBy = user self.instance.kind = Lesson.ANSWER self.instance.save_root() if should_create_ul: ul = UnitLesson.create_from_lesson(self.instance, unit, kind=UnitLesson.ANSWERS, parent=ul) lesson = super(CreateEditUnitAnswerForm, self).save(commit) return lesson
class SetUpMixin(object): """ Mixin to provide setUp method. """ def setUp(self): self.client = Client() self.user = User.objects.create_user('test', '*****@*****.**', 'test') get_specs()[0].save_graph(self.user.username) get_specs_additional()[0].save_graph(self.user.username) get_specs_resource()[0].save_graph(self.user.username) self.unit = Unit(title='Test title', addedBy=self.user) self.unit.save() self.course = Course(title='Test title', description='test description', access='Public', enrollCode='111', lockout='222', addedBy=self.user) self.course.save() self.courseunit = CourseUnit( unit=self.unit, course=self.course, order=0, addedBy=self.user, releaseTime=timezone.now() ) self.courseunit.save() self.concept = Concept.new_concept('bad', 'idea', self.unit, self.user) lesson = Lesson(title='title', text='text', addedBy=self.user) lesson.save() self.unitlesson = UnitLesson( unit=self.unit, order=0, lesson=lesson, addedBy=self.user, treeID=lesson.id ) self.unitlesson.save() resource_lesson = Lesson( title='title for resource', text='text for resource', addedBy=self.user ) resource_lesson.save() self.resource_unitlesson = UnitLesson( unit=self.unit, lesson=resource_lesson, addedBy=self.user, treeID=resource_lesson.id ) self.resource_unitlesson.save()
def form_valid(self, form): courslet = self.get_courslet() unit = courslet.unit self.object = Lesson(title=form.cleaned_data['title'], text='', kind=Lesson.ORCT_QUESTION, addedBy=self.request.user) self.object.save() self.object.treeID = self.object.pk self.object.save() # create UnitLesson with blank answer for this unit unit_lesson = UnitLesson.create_from_lesson(self.object, unit, order='APPEND', addAnswer=False) self.object.unit_lesson = unit_lesson cache.delete(memoize.cache_key('get_units_by_courselet', courslet)) return redirect(self.get_success_url())
def setUp(self): super(TestErrorViewSet, self).setUp() self.unit_lesson_error = UnitLesson( unit=self.unit, order=0, lesson=self.lesson, addedBy=self.user, treeID=self.lesson.id ) self.unit_lesson_error.save() self.student_error = StudentError( response=self.resp1, errorModel=self.unit_lesson_error, author=self.user ) self.student_error.save()
def setUp(self): self.user = User.objects.create_user(username="******", email="jacob@_", password="******") # have to login or Django self.client.session storage won't work self.client.login(username="******", password="******") self.course = Course(title="Great Course", description="the bestest", addedBy=self.user) self.course.save() self.unit = Unit(title="My Courselet", addedBy=self.user) self.unit.save() self.lesson = Lesson(title="Big Deal", text="very interesting info", addedBy=self.user) self.lesson.save_root() self.unitLesson = UnitLesson.create_from_lesson(self.lesson, self.unit, order="APPEND") self.ulQ = create_question_unit(self.user) self.ulQ2 = create_question_unit(self.user, "Pretest", "Scary Question", "Tell me something.") self.json_mixin = JSONBlobMixin() self.fsmDict = dict(name="test", title="try this") self.nodeDict = dict( START=dict(title="start here", path="ct:home", funcName="fsm.fsm_plugin.testme.START"), MID=dict(title="in the middle", path="ct:about", doLogging=True), END=dict(title="end here", path="ct:home"), ) self.edgeDict = ( dict(name="next", fromNode="START", toNode="END", title="go go go"), dict(name="select_Lesson", fromNode="MID", toNode="MID", title="go go go"), )
def lesson_answer(unit, lesson_question): return UnitLesson.create_from_lesson(unit=unit, lesson=lesson_question, addAnswer=True, order=1)
def lesson_answer_canvas(unit, lesson_question_canvas): return UnitLesson.create_from_lesson(unit=unit, lesson=lesson_question_canvas, addAnswer=True)
class TagsTest(TestCase): def setUp(self): self.user = User.objects.create_user(username="******", password="******") self.course = Course(title="test_title", addedBy=self.user) self.course.save() self.concept = Concept(title="test title", addedBy=self.user) self.concept.save() self.lesson = Lesson(title="ugh", text="brr", addedBy=self.user, kind=Lesson.ORCT_QUESTION) self.lesson.save_root() self.lesson.add_concept_link(self.concept, ConceptLink.TESTS, self.user) self.unit = Unit(title="test unit title", addedBy=self.user) self.unit.save() self.unit_lesson = UnitLesson(unit=self.unit, addedBy=self.user, treeID=42, lesson=self.lesson) self.unit_lesson.save() self.response = Response( course=self.course, lesson=self.lesson, author=self.user, unitLesson=self.unit_lesson, confidence=Response.GUESS, title="test title", text="test text", ) self.response.save() self.context = { "actionTarget": "/ct/courses/1/units/1/", "ul": self.unit_lesson, "test_text": "This is a test text", "r": self.response, } def render_template(self, string, context=None): context = context or {} context = Context(context) return Template(string).render(context) @unpack @data( ("{{ test_text | md2html }}", "<p>This is a test text</p>\n"), ("{{ actionTarget | get_object_url:ul }}", "/ct/courses/1/units/1/lessons/1/"), ("{{ actionTarget | get_home_url:ul }}", "/ct/courses/1/units/1/lessons/1/"), ("{{ actionTarget | get_thread_url:r }}", "/ct/courses/1/units/1/lessons/1/faq/1/"), ("{{ actionTarget | get_tasks_url:ul }}", "/ct/courses/1/units/1/lessons/1/tasks/"), ("{{ actionTarget | get_dummy_navbar }}", '<li><a href="/ct/courses/1/">Course</a></li>'), ) def test_all_filters(self, template_variable, expected_result): rendered = self.render_template("{% load ct_extras %}" + template_variable, context=self.context) self.assertEqual(rendered, expected_result) @patch("ct.templatetags.ct_extras.pypandoc") def test_md2html_pandoc_exception(self, pypandoc): pypandoc.convert.side_effect = StandardError rendered = self.render_template("{% load ct_extras %}" "{{ test_text | md2html }}", context=self.context) self.assertEqual(rendered, self.context["test_text"]) @data("get_base_url", "get_path_type") def test_get_base_url_exception(self, helper): with self.assertRaises(ValueError): getattr(inspect.getmodule(self), helper).__call__( "/ct/courses/1/units/1/lessons/1/", baseToken="non_existent_token" ) def test_get_object_url_exception(self): self.context["ul"] = self.unit # Unit object does not have get_url method rendered = self.render_template( "{% load ct_extras %}" "{{ actionTarget | get_object_url:ul }}", context=self.context ) self.assertEqual(rendered, "/ct/courses/1/units/1/unit/1/teach/") @patch("ct.templatetags.ct_extras.timezone") def test_display_datetime(self, timezone_patched): saved_time = timezone.now() timezone_patched.now.return_value = saved_time context = {"dt": saved_time - timedelta(1)} rendered = self.render_template("{% load ct_extras %}" "{{ dt|display_datetime }}", context=context) self.assertEqual(rendered, "1 day ago") def test_find_audio(self): result = find_audio("test tag head .. audio:: test tag tail \n", 4) self.assertEqual(result, (14, 39, "test tag tail")) def test_audio_html(self): """ Function should return string for embeding audio into html. """ result = audio_html("audio.mp3") self.assertEqual( result, """<audio controls><source src="audio.ogg" type="audio/ogg"><source src="audio.mp3" """ """type="audio/mpeg">no support for audio!</audio>""", ) def test_video_html(self): """ Function should return string for embeding youtube or vimeo link. """ result = video_html("youtube:test_video_path") self.assertIn("test_video_path", result) self.assertIn('src="https://www.youtube.com/embed/', result) result = video_html("vimeo:test_video_path") self.assertIn("test_video_path", result) self.assertIn('src="https://player.vimeo.com/video/', result) def test_video_html_with_exception(self): """ Test exception handling. """ result = video_html("youtube") self.assertEqual(result, "ERROR: bad video source: youtube") result = video_html("some_new_cdn:test_video_path") self.assertEqual(result, "ERROR: unknown video sourceDB: some_new_cdn") def test_add_replace_temporary_markers(self): """ Test add_temporary_markers and replace_temporary_markers in tandem. """ result = add_temporary_markers("test tag head .. audio:: test tag tail \n", find_audio) self.assertEqual(result, ("test tag head mArKeR:0:\n", [("mArKeR:0:", "test tag tail")])) result = replace_temporary_markers(result[0], audio_html, result[1]) self.assertEqual( result, """test tag head <audio controls><source src="test tag tail.ogg" type="audio/ogg">""" """<source src="test tag tail.mp3" type="audio/mpeg">no support for audio!</audio>\n""", )
class MyTestCase(TestCase): models_to_check = tuple() context_should_contain_keys = tuple() def setUp(self): self.username, self.password = '******', 'test' self.user = User.objects.create_user(self.username, '*****@*****.**', self.password) self.instructor = Instructor.objects.create(user=self.user, institution='institute', what_do_you_teach='something') self.username2, self.password2 = 'test1', 'test' self.user2 = User.objects.create_user(self.username2, '*****@*****.**', self.password2) self.instructor2 = Instructor.objects.create(user=self.user2, institution='institute', what_do_you_teach='something') self.unit = Unit(title='Test title', addedBy=self.user) self.unit.save() self.course = Course(title='Test title', description='test description', access='Public', enrollCode='111', lockout='222', addedBy=self.user) self.course.save() self.courseunit = CourseUnit( unit=self.unit, course=self.course, order=0, addedBy=self.user, releaseTime=timezone.now() ) self.courseunit.save() self.lesson = Lesson(title='title', text='text', addedBy=self.user) self.lesson.save() self.unitlesson = UnitLesson( unit=self.unit, order=0, lesson=self.lesson, addedBy=self.user, treeID=self.lesson.id ) self.unitlesson.save() self.resp1 = Response( unitLesson=self.unitlesson, kind=Response.ORCT_RESPONSE, lesson=self.lesson, course=self.course, text="Some text user may respond", author=self.user, status=NEED_HELP_STATUS, selfeval=Response.DIFFERENT ) self.resp1.save() self.resp2 = Response( unitLesson=self.unitlesson, kind=Response.ORCT_RESPONSE, lesson=self.lesson, course=self.course, text="Some text user may be responded 2", author=self.user, status=NEED_HELP_STATUS, selfeval=Response.DIFFERENT ) self.resp2.save() self.default_data = {} self.client.login(username=self.username, password=self.password) self.url = reverse('ctms:course_settings', kwargs={'pk': self.course.id}) def get_page(self): return self.client.get(self.url) def post_data(self, data={'name': 'some test name'}): response = self.client.post(self.url, data, follow=True) return response def get_client_method(self, method='post'): client_method = getattr(self.client, method) if not client_method: raise KeyError('self.client has no property {}'.format(method)) return client_method def post_valid_data(self, data={'name': 'some test name'}, method='post'): client_method = self.get_client_method(method) copied_data = {} if getattr(self, 'default_data', False): copied_data.update(self.default_data) copied_data.update(data) response = client_method(self.url, copied_data, follow=True) return response def post_invalid_data(self, data={'name': ''}, method='post'): client_method = self.get_client_method(method) copied_data = {} if getattr(self, 'default_data', False): copied_data.update(self.default_data) copied_data.update(data) response = client_method(self.url, copied_data, follow=True) return response def get_my_courses(self): return Course.objects.filter( models.Q(addedBy=self.user) | models.Q(role__role=Role.INSTRUCTOR, role__user=self.user) ) def get_test_course(self): return Course.objects.get(id=self.course.id) def get_test_unitlessons(self): return self.courseunit.unit.unitlesson_set.filter( kind=UnitLesson.COMPONENT, order__isnull=False ).order_by('order').annotate( responses_count=models.Count('response') ) def get_test_unitlesson(self): return self.courseunit.unit.unitlesson_set.filter( kind=UnitLesson.COMPONENT, order__isnull=False ).order_by('order').annotate( responses_count=models.Count('response') )[0] get_test_courslet = get_test_unitlesson get_test_response = lambda self: self.get_test_responses()[0] def get_test_courseunit(self): return CourseUnit.objects.get(id=self.courseunit.id) def get_test_responses(self): return Response.objects.filter( unitLesson=self.unitlesson, kind=Response.ORCT_RESPONSE, lesson=self.lesson, course=self.course, ) def get_model_counts(self, **kwargs): if isinstance(self.models_to_check, (list, tuple)): return {model: model.objects.filter().count() for model in self.models_to_check} return {self.models_to_check: self.models_to_check.objects.filter().count()} def validate_model_counts(self, first_counts, second_counts, must_equal=False): if isinstance(self.models_to_check, (list, tuple)): all_models = self.models_to_check else: all_models = [self.models_to_check] for model in all_models: if must_equal: self.assertEqual( first_counts[model], second_counts[model], "{} ({}) != {} ({}), with must_equal={}".format( model, first_counts[model], model, second_counts[model], must_equal ) ) else: self.assertNotEqual( first_counts[model], second_counts[model], "{} ({}) == {} ({}), with must_equal={}".format( model, first_counts[model], model, second_counts[model], must_equal ) ) def check_context_keys(self, response): for key in self.context_should_contain_keys: self.assertIn(key, response.context) def am_i_instructor(self, method='GET'): methods_map = {'GET', self.client.get, 'POST', self.client.post} client_method = methods_map.get(method) self.assertIsNotNone(client_method) if getattr(self, 'url'): if getattr(self, 'NEED_INSTRUCTOR'): response = client_method(self.url) if getattr(self, 'instructor'): self.assertEqual(response.status_code, 200) self.instructor.delete() response = client_method(self.url) self.assertEqual(response.status_code, 403) else: self.assertEqual(response.status_code, 403) else: response = client_method(self.url) self.assertEqual(response.status_code, 200)
class MyCoursesTests(MyTestCase): def setUp(self): self.username, self.password = '******', 'test' self.user = User.objects.create_user('test', '*****@*****.**', 'test') self.instructor = Instructor.objects.create(user=self.user, institution='institute', what_do_you_teach='something') self.user2 = User.objects.create_user('test1', '*****@*****.**', 'test') self.instructor2 = Instructor.objects.create(user=self.user2, institution='institution', what_do_you_teach='something') self.unit = Unit(title='Test title', addedBy=self.user) self.unit.save() self.course = Course(title='Test title', description='test description', access='Public', enrollCode='111', lockout='222', addedBy=self.user) self.course.save() self.courseunit = CourseUnit( unit=self.unit, course=self.course, order=0, addedBy=self.user, releaseTime=timezone.now() ) self.courseunit.save() self.lesson = Lesson(title='title', text='text', addedBy=self.user) self.lesson.save() self.unitlesson = UnitLesson( unit=self.unit, order=0, lesson=self.lesson, addedBy=self.user, treeID=self.lesson.id ) self.unitlesson.save() self.client.login(username=self.username, password=self.password) self.url = reverse('ctms:my_courses') def test_get_my_courses_page(self): response = self.client.get(self.url) # should contain 1 course self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'ctms/my_courses.html') self.assertIn('my_courses', response.context) self.assertIn(self.course, response.context['my_courses']) def test_get_my_courses_page_instructor_role(self): """ Ensure Role.INSTRUCTOR granted access to a Course. """ course = Course(title='Instructor2 Course', description='test description', access='Public', enrollCode='111', lockout='222', addedBy=self.user2) course.save() Role.objects.create(role=Role.INSTRUCTOR, course=course, user=self.user) response = self.client.get(self.url) # should contain 2 courses self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'ctms/my_courses.html') self.assertIn('my_courses', response.context) self.assertIn(self.course, response.context['my_courses']) self.assertIn(course, response.context['my_courses']) self.assertEqual(len(response.context['my_courses']), 2) @data(Role.TA, Role.SELFSTUDY, Role.ENROLLED) def test_get_my_courses_page_notinstructor_role(self, role): """ Ensure Role.INSTRUCTOR granted access to a Course. """ course = Course(title='Instructor2 Course', description='test description', access='Public', enrollCode='111', lockout='222', addedBy=self.user2) course.save() Role.objects.create(role=role, course=course, user=self.user) response = self.client.get(self.url) # should contain 1 courses self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'ctms/my_courses.html') self.assertIn('my_courses', response.context) self.assertIn(self.course, response.context['my_courses']) self.assertNotIn(course, response.context['my_courses']) self.assertEqual(len(response.context['my_courses']), 1) def test_my_courses_show_shared_courses(self): self.course.addedBy = self.user2 self.course.save() # create shared course enroll_unit_code = EnrollUnitCode.get_code(self.courseunit, give_instance=True) shared_course = Invite.create_new( True, self.course, self.instructor2, self.user.email, 'tester', enroll_unit_code) response = self.client.get(reverse('ctms:shared_courses')) # should return shared courses self.assertIn('shared_courses', response.context) self.assertNotEqual(len(response.context['shared_courses']), 0) self.assertTrue(shared_course.course.title in response.context['shared_courses']) def my_courses_show_create_course_form(self): self.course.delete() response = self.client.get(self.url) # should return Course form self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'ctms/my_courses.html') self.assertIn('my_courses', response.context) self.assertIn('shared_courses', response.context) self.assertIn('course_form', response.context) self.assertFalse(len(response.context['my_courses']) < 0) def post_valid_create_course_form(self): courses_cnt = Course.objects.filter(addedBy=self.user).count() course_ids = [ i['id'] for i in Course.objects.filter(addedBy=self.user).values('id') ] data = { 'name': 'some course' } response = self.client.post(self.url, data) new_courses = Course.objects.filter(addedBy=self.user) new_course = new_courses.exclude(id__in=course_ids).get() self.assertEqual(new_courses.count(), courses_cnt) self.assertRedirects(response, reverse('ctms:course_view', kwargs={'course_id': new_course.id})) return response def post_invalid_create_course_form(self): courses_cnt = Course.objects.filter(addedBy=self.user).count() course_ids = [ i['id'] for i in Course.obget_courslet_view_logged_out_user_testjects.filter(addedBy=self.user).values('id') ] data = { 'name': '' } response = self.client.post(self.url, data) new_courses = Course.objects.filter(addedBy=self.user) new_course = new_courses.exclude(id__in=course_ids) self.assertNotEqual(new_courses.count(), courses_cnt) # course was not created self.assertEqual(len(new_course) == 0) self.assertTemplateUsed(response, 'ctms/my_courses.html') return response def post_valid_create_course_form_to_create_course_view(self): self.url = reverse('ctms:create_course') self.post_valid_create_course_form() def post_invalid_create_course_form_to_create_course_view(self): self.url = reverse('ctms:create_course') self.post_invalid_create_course_form()
def setUp(self): """ Preconditions. """ from chat.fsm_plugin.chat import get_specs from chat.fsm_plugin.additional import get_specs as get_specs_additional self.client = Client() self.user = User.objects.create_user('test', '*****@*****.**', 'test') get_specs()[0].save_graph(self.user.username) get_specs_additional()[0].save_graph(self.user.username) mocked_nonce = u'135685044251684026041377608307' mocked_timestamp = u'1234567890' mocked_decoded_signature = u'my_signature=' self.headers = { u'user_id': 1, u'lis_person_name_full': u'Test Username', u'lis_person_name_given': u'First', u'lis_person_name_family': u'Second', u'lis_person_contact_email_primary': u'*****@*****.**', u'lis_person_sourcedid': u'Test_Username', u'oauth_callback': u'about:blank', u'launch_presentation_return_url': '', u'lti_message_type': u'basic-lti-launch-request', u'lti_version': 'LTI-1p0', u'roles': u'Student', u'context_id': 1, u'tool_consumer_info_product_family_code': u'moodle', u'context_title': u'Test title', u'tool_consumer_instance_guid': u'test.dot.com', u'resource_link_id': 'dfgsfhrybvrth', u'lis_result_sourcedid': 'wesgaegagrreg', u'oauth_nonce': mocked_nonce, u'oauth_timestamp': mocked_timestamp, u'oauth_consumer_key': u'consumer_key', u'oauth_signature_method': u'HMAC-SHA1', u'oauth_version': u'1.0', u'oauth_signature': mocked_decoded_signature } self.unit = Unit(title='Test title', addedBy=self.user) self.unit.save() self.course = Course(title='Test title', description='test description', access='Public', enrollCode='111', lockout='222', addedBy=self.user) self.course.save() self.course_ref = CourseRef( course=self.course, context_id=self.headers.get('context_id'), tc_guid=self.headers.get('tool_consumer_instance_guid') ) self.course_ref.save() self.course_ref.instructors.add(self.user) self.role1 = Role( role=Role.ENROLLED, user=self.user, course=self.course, ) self.role1.save() self.courseunit = CourseUnit( unit=self.unit, course=self.course, order=0, addedBy=self.user, releaseTime=timezone.now() ) self.courseunit.save() lesson = Lesson(title='title', text='text', addedBy=self.user) lesson.save() unitlesson = UnitLesson( unit=self.unit, order=0, lesson=lesson, addedBy=self.user, treeID=lesson.id ) unitlesson.save() self.lti_consumer = LtiConsumer( consumer_name='test', consumer_key='consumer_key', consumer_secret='test_key' ) self.lti_consumer.save()
def setUp(self): self.username, self.password = '******', 'test' self.user = User.objects.create_user(self.username, '*****@*****.**', self.password) self.instructor = Instructor.objects.create(user=self.user, institution='institute', what_do_you_teach='something') self.username2, self.password2 = 'test1', 'test' self.user2 = User.objects.create_user(self.username2, '*****@*****.**', self.password2) self.instructor2 = Instructor.objects.create(user=self.user2, institution='institute', what_do_you_teach='something') self.unit = Unit(title='Test title', addedBy=self.user) self.unit.save() self.course = Course(title='Test title', description='test description', access='Public', enrollCode='111', lockout='222', addedBy=self.user) self.course.save() self.courseunit = CourseUnit( unit=self.unit, course=self.course, order=0, addedBy=self.user, releaseTime=timezone.now() ) self.courseunit.save() self.lesson = Lesson(title='title', text='text', addedBy=self.user) self.lesson.save() self.unitlesson = UnitLesson( unit=self.unit, order=0, lesson=self.lesson, addedBy=self.user, treeID=self.lesson.id ) self.unitlesson.save() self.resp1 = Response( unitLesson=self.unitlesson, kind=Response.ORCT_RESPONSE, lesson=self.lesson, course=self.course, text="Some text user may respond", author=self.user, status=NEED_HELP_STATUS, selfeval=Response.DIFFERENT ) self.resp1.save() self.resp2 = Response( unitLesson=self.unitlesson, kind=Response.ORCT_RESPONSE, lesson=self.lesson, course=self.course, text="Some text user may be responded 2", author=self.user, status=NEED_HELP_STATUS, selfeval=Response.DIFFERENT ) self.resp2.save() self.default_data = {} self.client.login(username=self.username, password=self.password) self.url = reverse('ctms:course_settings', kwargs={'pk': self.course.id})
def setUp(self): """ Preconditions. """ from chat.fsm_plugin.chat import get_specs from chat.fsm_plugin.additional import get_specs as get_specs_additional self.client = Client() self.user = User.objects.create_user('test', '*****@*****.**', 'test') get_specs()[0].save_graph(self.user.username) get_specs_additional()[0].save_graph(self.user.username) mocked_nonce = u'135685044251684026041377608307' mocked_timestamp = u'1234567890' mocked_decoded_signature = u'my_signature=' self.headers = { u'user_id': 1, u'lis_person_name_full': u'Test Username', u'lis_person_name_given': u'First', u'lis_person_name_family': u'Second', u'lis_person_contact_email_primary': u'*****@*****.**', u'lis_person_sourcedid': u'Test_Username', u'oauth_callback': u'about:blank', u'launch_presentation_return_url': '', u'lti_message_type': u'basic-lti-launch-request', u'lti_version': 'LTI-1p0', u'roles': u'Student', u'context_id': 1, u'tool_consumer_info_product_family_code': u'moodle', u'context_title': u'Test title', u'tool_consumer_instance_guid': u'test.dot.com', u'resource_link_id': 'dfgsfhrybvrth', u'lis_result_sourcedid': 'wesgaegagrreg', u'oauth_nonce': mocked_nonce, u'oauth_timestamp': mocked_timestamp, u'oauth_consumer_key': u'', u'oauth_signature_method': u'HMAC-SHA1', u'oauth_version': u'1.0', u'oauth_signature': mocked_decoded_signature } self.unit = Unit(title='Test title', addedBy=self.user) self.unit.save() self.course = Course(title='Test title', description='test description', access='Public', enrollCode='111', lockout='222', addedBy=self.user) self.course.save() self.course_ref = CourseRef( course=self.course, context_id=self.headers.get('context_id'), tc_guid=self.headers.get('tool_consumer_instance_guid')) self.course_ref.save() self.course_ref.instructors.add(self.user) self.courseunit = CourseUnit(unit=self.unit, course=self.course, order=0, addedBy=self.user, releaseTime=timezone.now()) self.courseunit.save() lesson = Lesson(title='title', text='text', addedBy=self.user) lesson.save() unitlesson = UnitLesson(unit=self.unit, order=0, lesson=lesson, addedBy=self.user, treeID=lesson.id) unitlesson.save()
class TestCourseletViewHistoryTab(TestCase): def setUp(self): self.user = User.objects.create_user(username='******', password='******') self.client.login(username='******', password='******') self.course = Course(title='test_title', addedBy=self.user) self.course.save() self.unit = Unit(title='test unit title', addedBy=self.user) self.unit.save() self.course_unit = CourseUnit( course=self.course, unit=self.unit, order=0, addedBy=self.user ) self.course_unit.releaseTime = timezone.now() - datetime.timedelta(days=1) self.course_unit.save() self.enroll = EnrollUnitCode(courseUnit=self.course_unit) self.enroll.save() self.role = Role(course=self.course, user=self.user, role=Role.INSTRUCTOR) self.role.save() self.student_role = Role(course=self.course, user=self.user, role=Role.ENROLLED) self.student_role.save() self.concept = Concept.new_concept('bad', 'idea', self.unit, self.user) self.lesson = Lesson( title='New York Test Lesson', text='brr', addedBy=self.user, kind=Lesson.ORCT_QUESTION ) self.lesson.save_root(self.concept) self.unit_lesson = UnitLesson( unit=self.unit, lesson=self.lesson, addedBy=self.user, treeID=self.lesson.id, order=0 ) self.unit_lesson.save() self.unit_lesson_answer = UnitLesson( parent=self.unit_lesson, unit=self.unit, lesson=self.lesson, addedBy=self.user, treeID=self.lesson.id, kind=UnitLesson.ANSWERS ) self.unit_lesson_answer.save() self.user = User.objects.create_user(username='******', password='******') call_command('fsm_deploy') def test_click_on_courslet_creates_new_chat(self): # test that there's no history yet response = self.client.get( reverse('lms:course_view', kwargs={'course_id': self.course.id}) ) self.assertEqual(response.status_code, 200) self.assertIsNotNone(list(response.context['courslets'])) self.assertEqual(response.status_code, 200) chats_count_1 = Chat.objects.all().count() # firstly call to chat:init_chat_api function with enroll_key and chat_id=0 response = self.client.get( reverse( 'chat:init_chat_api', kwargs={ 'enroll_key': self.enroll.enrollCode, 'chat_id': 0 } ), HTTP_X_REQUESTED_WITH='XMLHttpRequest' ) json_content = json.loads(response.content) chat_id = json_content['id'] response = self.client.get( reverse('chat:chat_enroll', kwargs={'enroll_key': self.enroll.enrollCode, 'chat_id': chat_id}) ) self.assertEqual(response.context['chat'].id, Chat.objects.all().first().id) self.assertEqual(response.status_code, 200) chats_count_2 = Chat.objects.count() self.assertNotEqual(chats_count_2, chats_count_1) response = self.client.get( reverse('chat:chat_enroll', kwargs={'enroll_key': self.enroll.enrollCode, 'chat_id': chat_id}) ) chats_count_3 = Chat.objects.count() response = self.client.get( reverse('chat:chat_enroll', kwargs={'enroll_key': self.enroll.enrollCode, 'chat_id': chat_id}) ) chats_count_4 = Chat.objects.count() self.assertEqual(response.status_code, 200) self.assertEqual(chats_count_4, chats_count_2) self.assertEqual(chats_count_3, chats_count_2) self.assertEqual(response.context['chat'].id, Chat.objects.all().first().id) chat = Chat.objects.all().first() # get chat and set state to None it means that courslet finished. chat.state = None chat.save() response = self.client.get( reverse('lms:course_view', kwargs={'course_id': self.course.id}) ) self.assertEqual(response.status_code, 200) self.assertEqual(Chat.objects.count(), chats_count_2) self.assertEqual(len(list(response.context['courslets'])), 1) def test_courslet_history(self): enroll_code = EnrollUnitCode.get_code(self.course_unit) response = self.client.get( reverse( 'chat:init_chat_api', kwargs={ 'enroll_key': self.enroll.enrollCode, 'chat_id': 0 } ), HTTP_X_REQUESTED_WITH='XMLHttpRequest' ) json_content = json.loads(response.content) chat_id = json_content['id'] response = self.client.get( reverse('chat:chat_enroll', args=(enroll_code, chat_id)), follow=True ) response = self.client.get( reverse('chat:history'), {'chat_id': chat_id}, follow=True ) json_content = json.loads(response.content) next_url = json_content['input']['url'] answer = 'My Answer' response = self.client.put( next_url, data=json.dumps({"text": answer, "chat_id": chat_id}), content_type='application/json', follow=True ) json_content = json.loads(response.content) next_url = json_content['input']['url'] response = self.client.get( next_url, {'chat_id': chat_id}, follow=True ) json_content = json.loads(response.content) next_url = json_content['input']['url'] self.assertIsNotNone(json_content['input']['options']) self.assertEquals(len(json_content['addMessages']), 2) # emulate chat finished - set state to None Chat.objects.filter(id=chat_id).update(state=None) response = self.client.get( reverse('chat:chat_enroll', args=(enroll_code, chat_id)), follow=True ) response = self.client.get( reverse('chat:history'), {'chat_id': chat_id}, follow=True ) json_content = json.loads(response.content) self.assertIsNone(json_content['input']['options']) self.assertEquals(len(json_content['addMessages']), 4)
class TagsTest(TestCase): def setUp(self): self.user = User.objects.create_user(username='******', password='******') self.course = Course(title='test_title', addedBy=self.user) self.course.save() self.concept = Concept(title='test title', addedBy=self.user) self.concept.save() self.lesson = Lesson(title='ugh', text='brr', addedBy=self.user, kind=Lesson.ORCT_QUESTION) self.lesson.save_root() self.lesson.add_concept_link(self.concept, ConceptLink.TESTS, self.user) self.unit = Unit(title='test unit title', addedBy=self.user) self.unit.save() self.unit_lesson = UnitLesson(unit=self.unit, addedBy=self.user, treeID=42, lesson=self.lesson) self.unit_lesson.save() self.response = Response(course=self.course, lesson=self.lesson, author=self.user, unitLesson=self.unit_lesson, confidence=Response.GUESS, title='test title', text='test text') self.response.save() self.context = { 'actionTarget': '/ct/courses/1/units/1/', 'ul': self.unit_lesson, 'test_text': 'This is a test text', 'r': self.response } def render_template(self, string, context=None): context = context or {} context = Context(context) return Template(string).render(context) @unpack @data( ('{{ test_text | md2html }}', '<p>This is a test text</p>\n'), ('{{ actionTarget | get_object_url:ul }}', '/ct/courses/1/units/1/lessons/1/'), ('{{ actionTarget | get_home_url:ul }}', '/ct/courses/1/units/1/lessons/1/'), ('{{ actionTarget | get_thread_url:r }}', '/ct/courses/1/units/1/lessons/1/faq/1/'), ('{{ actionTarget | get_tasks_url:ul }}', '/ct/courses/1/units/1/lessons/1/tasks/'), ('{{ actionTarget | get_dummy_navbar }}', '<li><a href="/ct/courses/1/">Course</a></li>'), ) def test_all_filters(self, template_variable, expected_result): rendered = self.render_template('{% load ct_extras %}' + template_variable, context=self.context) self.assertEqual(rendered, expected_result) @patch('ct.templatetags.ct_extras.pypandoc') def test_md2html_pandoc_exception(self, pypandoc): pypandoc.convert.side_effect = StandardError rendered = self.render_template( '{% load ct_extras %}' '{{ test_text | md2html }}', context=self.context) self.assertEqual(rendered, self.context['test_text']) @data('get_base_url', 'get_path_type') def test_get_base_url_exception(self, helper): with self.assertRaises(ValueError): getattr(inspect.getmodule(self), helper).__call__('/ct/courses/1/units/1/lessons/1/', baseToken='non_existent_token') def test_get_object_url_exception(self): self.context[ 'ul'] = self.unit # Unit object does not have get_url method rendered = self.render_template( '{% load ct_extras %}' '{{ actionTarget | get_object_url:ul }}', context=self.context) self.assertEqual(rendered, '/ct/courses/1/units/1/unit/1/teach/') @patch('ct.templatetags.ct_extras.timezone') def test_display_datetime(self, timezone_patched): saved_time = timezone.now() timezone_patched.now.return_value = saved_time context = {'dt': saved_time - timedelta(1)} rendered = self.render_template( '{% load ct_extras %}' '{{ dt|display_datetime }}', context=context) self.assertEqual(rendered, '1 day ago') def test_find_audio(self): result = find_audio('test tag head .. audio:: test tag tail \n', 4) self.assertEqual(result, (14, 39, 'test tag tail')) def test_audio_html(self): """ Function should return string for embeding audio into html. """ result = audio_html('audio.mp3') self.assertEqual( result, '''<audio controls><source src="audio.ogg" type="audio/ogg"><source src="audio.mp3" ''' '''type="audio/mpeg">no support for audio!</audio>''') def test_video_html(self): """ Function should return string for embeding youtube or vimeo link. """ result = video_html('youtube:test_video_path') self.assertIn('test_video_path', result) self.assertIn('src="https://www.youtube.com/embed/', result) result = video_html('vimeo:test_video_path') self.assertIn('test_video_path', result) self.assertIn('src="https://player.vimeo.com/video/', result) def test_video_html_with_exception(self): """ Test exception handling. """ result = video_html('youtube') self.assertEqual(result, 'ERROR: bad video source: youtube') result = video_html('some_new_cdn:test_video_path') self.assertEqual(result, 'ERROR: unknown video sourceDB: some_new_cdn') def test_add_replace_temporary_markers(self): """ Test add_temporary_markers and replace_temporary_markers in tandem. """ result = add_temporary_markers( 'test tag head .. audio:: test tag tail \n', find_audio) self.assertEqual( result, ('test tag head mArKeR:0:\n', [('mArKeR:0:', 'test tag tail')])) result = replace_temporary_markers(result[0], audio_html, result[1]) self.assertEqual( result, '''test tag head <audio controls><source src="test tag tail.ogg" type="audio/ogg">''' '''<source src="test tag tail.mp3" type="audio/mpeg">no support for audio!</audio>\n''' )
class MyCoursesTests(MyTestCase): def setUp(self): self.username, self.password = '******', 'test' self.user = User.objects.create_user('test', '*****@*****.**', 'test') self.instructor = Instructor.objects.create(user=self.user, institution='institute', what_do_you_teach='something') self.user2 = User.objects.create_user('test1', '*****@*****.**', 'test') self.instructor2 = Instructor.objects.create(user=self.user2, institution='institution', what_do_you_teach='something') self.unit = Unit(title='Test title', addedBy=self.user) self.unit.save() self.course = Course(title='Test title', description='test description', access='Public', enrollCode='111', lockout='222', addedBy=self.user) self.course.save() self.courseunit = CourseUnit( unit=self.unit, course=self.course, order=0, addedBy=self.user, releaseTime=timezone.now() ) self.courseunit.save() self.lesson = Lesson(title='title', text='text', addedBy=self.user) self.lesson.save() self.unitlesson = UnitLesson( unit=self.unit, order=0, lesson=self.lesson, addedBy=self.user, treeID=self.lesson.id ) self.unitlesson.save() self.client.login(username=self.username, password=self.password) self.url = reverse('ctms:my_courses') @mock.patch('ctms.views.get_onboarding_percentage') def test_get_my_courses_page(self, onboarding_percentage): onboarding_percentage.return_value = 100 response = self.client.get(self.url) # should contain 1 course self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'ctms/my_courses.html') self.assertIn('my_courses', response.context) self.assertIn(self.course, response.context['my_courses']) @mock.patch('ctms.views.get_onboarding_percentage') def test_my_courses_show_shared_courses(self, onboarding_percentage): onboarding_percentage.return_value = 100 self.course.addedBy = self.user2 self.course.save() # create shared course enroll_unit_code = EnrollUnitCode.get_code(self.courseunit, give_instance=True) shared_course = Invite.create_new(True, self.course, self.instructor2, self.user.email, 'tester', enroll_unit_code) response = self.client.get(reverse('ctms:shared_courses')) # should return shared courses self.assertIn('shared_courses', response.context) self.assertNotEqual(len(response.context['shared_courses']), 0) self.assertTrue(shared_course.course.title in response.context['shared_courses']) def my_courses_show_create_course_form(self): self.course.delete() response = self.client.get(self.url) # should return Course form self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'ctms/my_courses.html') self.assertIn('my_courses', response.context) self.assertIn('shared_courses', response.context) self.assertIn('course_form', response.context) self.assertFalse(len(response.context['my_courses']) < 0) def post_valid_create_course_form(self): courses_cnt = Course.objects.filter(addedBy=self.user).count() course_ids = [ i['id'] for i in Course.objects.filter(addedBy=self.user).values('id') ] data = { 'name': 'some course' } response = self.client.post(self.url, data) new_courses = Course.objects.filter(addedBy=self.user) new_course = new_courses.exclude(id__in=course_ids).get() self.assertEqual(new_courses.count(), courses_cnt) self.assertRedirects(response, reverse('ctms:course_view', kwargs={'course_id': new_course.id})) return response def post_invalid_create_course_form(self): courses_cnt = Course.objects.filter(addedBy=self.user).count() course_ids = [ i['id'] for i in Course.obget_courslet_view_logged_out_user_testjects.filter(addedBy=self.user).values('id') ] data = { 'name': '' } response = self.client.post(self.url, data) new_courses = Course.objects.filter(addedBy=self.user) new_course = new_courses.exclude(id__in=course_ids) self.assertNotEqual(new_courses.count(), courses_cnt) # course was not created self.assertEqual(len(new_course) == 0) self.assertTemplateUsed(response, 'ctms/my_courses.html') return response def post_valid_create_course_form_to_create_course_view(self): self.url = reverse('ctms:create_course') self.post_valid_create_course_form() def post_invalid_create_course_form_to_create_course_view(self): self.url = reverse('ctms:create_course') self.post_invalid_create_course_form()
class TestCourseletViewHistoryTab(TestCase): def setUp(self): self.user = User.objects.create_user(username='******', password='******') self.client.login(username='******', password='******') self.course = Course(title='test_title', addedBy=self.user) self.course.save() self.unit = Unit(title='test unit title', addedBy=self.user) self.unit.save() self.course_unit = CourseUnit( course=self.course, unit=self.unit, order=0, addedBy=self.user ) self.course_unit.releaseTime = timezone.now() - datetime.timedelta(days=1) self.course_unit.save() self.enroll = EnrollUnitCode(courseUnit=self.course_unit) self.enroll.save() self.role = Role(course=self.course, user=self.user, role=Role.INSTRUCTOR) self.role.save() self.student_role = Role(course=self.course, user=self.user, role=Role.ENROLLED) self.student_role.save() self.concept = Concept.new_concept('bad', 'idea', self.unit, self.user) self.lesson = Lesson( title='New York Test Lesson', text='brr', addedBy=self.user, kind=Lesson.ORCT_QUESTION ) self.lesson.save_root(self.concept) self.unit_lesson = UnitLesson( unit=self.unit, lesson=self.lesson, addedBy=self.user, treeID=self.lesson.id, order=0 ) self.unit_lesson.save() self.unit_lesson_answer = UnitLesson( parent=self.unit_lesson, unit=self.unit, lesson=self.lesson, addedBy=self.user, treeID=self.lesson.id, kind=UnitLesson.ANSWERS ) self.unit_lesson_answer.save() self.user = User.objects.create_user(username='******', password='******') call_command('fsm_deploy') def test_click_on_courslet_creates_new_chat(self): # test that there's no history yet response = self.client.get( reverse('lms:course_view', kwargs={'course_id': self.course.id}) ) self.assertEqual(response.status_code, 200) self.assertIsNotNone(list(response.context['courslets'])) self.assertEqual(response.status_code, 200) chats_count_1 = Chat.objects.all().count() # firstly call to chat:init_chat_api function with enroll_key and chat_id=0 response = self.client.get( reverse( 'chat:init_chat_api', kwargs={ 'enroll_key': self.enroll.enrollCode, 'chat_id': 0 } ), HTTP_X_REQUESTED_WITH='XMLHttpRequest' ) json_content = json.loads(response.content) chat_id = json_content['id'] response = self.client.get( reverse('chat:chat_enroll', kwargs={'enroll_key': self.enroll.enrollCode, 'chat_id': chat_id}) ) self.assertEqual(response.context['chat'].id, Chat.objects.all().first().id) self.assertEqual(response.status_code, 200) chats_count_2 = Chat.objects.count() self.assertNotEqual(chats_count_2, chats_count_1) response = self.client.get( reverse('chat:chat_enroll', kwargs={'enroll_key': self.enroll.enrollCode, 'chat_id': chat_id}) ) chats_count_3 = Chat.objects.count() response = self.client.get( reverse('chat:chat_enroll', kwargs={'enroll_key': self.enroll.enrollCode, 'chat_id': chat_id}) ) chats_count_4 = Chat.objects.count() self.assertEqual(response.status_code, 200) self.assertEqual(chats_count_4, chats_count_2) self.assertEqual(chats_count_3, chats_count_2) self.assertEqual(response.context['chat'].id, Chat.objects.all().first().id) chat = Chat.objects.all().first() # get chat and set state to None it means that courslet finished. chat.state = None chat.save() response = self.client.get( reverse('lms:course_view', kwargs={'course_id': self.course.id}) ) self.assertEqual(response.status_code, 200) self.assertEqual(Chat.objects.count(), chats_count_2) self.assertEqual(len(list(response.context['courslets'])), 1) def test_courslet_history(self): enroll_code = EnrollUnitCode.get_code(self.course_unit) response = self.client.get( reverse( 'chat:init_chat_api', kwargs={ 'enroll_key': self.enroll.enrollCode, 'chat_id': 0 } ), HTTP_X_REQUESTED_WITH='XMLHttpRequest' ) json_content = json.loads(response.content) chat_id = json_content['id'] response = self.client.get( reverse('chat:chat_enroll', args=(enroll_code, chat_id)), follow=True ) response = self.client.get( reverse('chat:history'), {'chat_id': chat_id}, follow=True ) json_content = json.loads(response.content) next_url = json_content['input']['url'] answer = 'My Answer' response = self.client.put( next_url, data=json.dumps({"text": answer, "chat_id": chat_id}), content_type='application/json', follow=True ) json_content = json.loads(response.content) next_url = json_content['input']['url'] response = self.client.get( next_url, {'chat_id': chat_id}, follow=True ) json_content = json.loads(response.content) next_url = json_content['input']['url'] self.assertIsNotNone(json_content['input']['options']) self.assertEqual(len(json_content['addMessages']), 2) # emulate chat finished - set state to None Chat.objects.filter(id=chat_id).update(state=None) response = self.client.get( reverse('chat:chat_enroll', args=(enroll_code, chat_id)), follow=True ) response = self.client.get( reverse('chat:history'), {'chat_id': chat_id}, follow=True ) json_content = json.loads(response.content) self.assertIsNone(json_content['input']['options']) self.assertEqual(len(json_content['addMessages']), 4)
def perform_update(self, serializer): chat_id = self.request.data.get('chat_id') message = self.get_object() chat = Chat.objects.get(id=chat_id, user=self.request.user) activity = chat.state and chat.state.activity is_in_node = lambda node: message.chat.state.fsmNode.name == node # Check if message is not in current chat if not message.chat or message.chat != chat: return # Chat add unit lesson if is_chat_add_lesson(message): message.chat = chat text = self.request.data.get('text') option = self.request.data.get('option') course_unit = message.chat.enroll_code.courseUnit unit = course_unit.unit if message.input_type == 'options' and is_in_node('HAS_UNIT_ANSWER'): message = self.next_handler.next_point( current=message.content, chat=chat, message=message, request=self.request ) chat.next_point = message chat.save() serializer.save(chat=chat, timestamp=timezone.now()) if is_in_node('GET_UNIT_NAME_TITLE'): if course_unit and unit: if not message.content_id: lesson = Lesson.objects.create(title=text, addedBy=self.request.user, kind=Lesson.ORCT_QUESTION, text='') lesson.treeID = lesson.id lesson.save() ul = UnitLesson.create_from_lesson( lesson=lesson, unit=unit, kind=UnitLesson.COMPONENT, order='APPEND', ) chat.state.unitLesson = ul chat.state.save() else: ul = message.content if not message.timestamp: serializer.save( content_id=ul.id, timestamp=timezone.now(), chat=chat, text=text, contenttype='unitlesson' ) else: serializer.save() if is_in_node('GET_UNIT_QUESTION'): ul = message.content ul.lesson.text = text ul.lesson.save() if not message.timestamp: serializer.save( content_id=ul.id, timestamp=timezone.now(), chat=chat, contenttype='unitlesson', text=text ) else: serializer.save() if is_in_node('GET_UNIT_ANSWER'): # create answer ul = message.content if not message.timestamp: answer = Lesson.objects.create( title='Answer', text=text, addedBy=self.request.user, kind=Lesson.ANSWER, ) answer.save_root() unit_lesson_answer = UnitLesson.create_from_lesson( unit=ul.unit, lesson=answer, parent=ul, kind=UnitLesson.ANSWERS ) # chat.next_point = message chat.save() serializer.save(content_id=ul.id, timestamp=timezone.now(), chat=chat, contenttype='unitlesson', text=text) else: serializer.save() if is_in_node('GET_HAS_UNIT_ANSWER'): yes_no_map = { 'yes': True, 'no': False } ul = message.content has_answer = yes_no_map.get(self.request.data.get('option')) if has_answer is None: raise ValueError("Recieved not valid response from user") ul.lesson.kind = Lesson.ORCT_QUESTION if has_answer else Lesson.BASE_EXPLANATION ul.lesson.save() message.text = self.request.data.get('option') message.save() if message.input_type == 'text' and not is_chat_add_lesson(message): message.chat = chat text = self.request.data.get('text') if message.lesson_to_answer.sub_kind == Lesson.EQUATION: text = text.strip("$") text = '.. math:: ' + text resp = StudentResponse(text=text) # convert base64 attachment string to django File data_attachment = self.request.data.get('attachment') if data_attachment and data_attachment.startswith('data:image'): format, image_string = data_attachment.split(';base64,') extension = format.split('/')[-1].split('+')[0] name = '{}.{}'.format('canvas', extension) resp.attachment = ContentFile(base64.b64decode(image_string), name=name) if not message.content_id: resp.lesson = message.lesson_to_answer.lesson resp.unitLesson = message.lesson_to_answer resp.course = message.chat.enroll_code.courseUnit.course resp.author = self.request.user resp.activity = activity resp.is_test = chat.is_test resp.is_preview = chat.enroll_code.isPreview resp.sub_kind = resp.lesson.sub_kind else: resp = message.content resp.text = text resp.is_trial = chat.is_trial resp.save() if not message.timestamp: message.content_id = resp.id chat.next_point = message chat.last_modify_timestamp = timezone.now() chat.save() serializer.save(content_id=resp.id, timestamp=timezone.now(), chat=chat) else: serializer.save() message_is_response = message.contenttype == 'response' lesson_has_sub_kind = message.lesson_to_answer and message.lesson_to_answer.sub_kind content_is_not_additional = not message.content and not message.is_additional mc_selfeval = None if message_is_response and lesson_has_sub_kind and content_is_not_additional: resp_text = '' if message.lesson_to_answer.sub_kind == Lesson.MULTIPLE_CHOICES: selected_items = self.request.data.get('selected') try: selected = selected_items[str(message.id)]['choices'] except KeyError: # here request.data is like {"option":1,"chat_id":9,"selected":{"116":{"choices":[0]}}} selected_msg_ids = self.request.data.get( 'selected' ).keys() # selected_messages == tuple with keys of this dict {"116":{"choices":[0]}} - it will be ("116",) msg_ids = Message.objects.filter(id__in=selected_msg_ids, chat=chat).values_list('id', flat=True) correct_ids = set(msg_ids).intersection( set(int(i) for i in selected_items.keys()) ) selected_choices = [] for i in correct_ids: selected_choices.append(selected_items[str(i)]['choices']) selected = chain(*selected_choices) resp_text = '[selected_choices] ' + ' '.join(str(i) for i in selected) correct_choices = set([_[0] for _ in message.lesson_to_answer.lesson.get_correct_choices()]) selected_choices = set([_ for _ in chain(*selected_choices)]) if not (correct_choices - selected_choices or correct_choices ^ selected_choices): mc_selfeval = StudentResponse.CORRECT elif selected_choices & correct_choices: mc_selfeval = StudentResponse.CLOSE else: mc_selfeval = StudentResponse.DIFFERENT resp = StudentResponse(text=resp_text) # tes, preview flags resp.is_test = chat.is_test resp.selfeval = mc_selfeval or None resp.is_preview = chat.enroll_code.isPreview resp.is_trial = chat.is_trial resp.kind = message.lesson_to_answer.kind resp.sub_kind = message.lesson_to_answer.sub_kind resp.lesson = message.lesson_to_answer.lesson resp.unitLesson = message.lesson_to_answer resp.course = message.chat.enroll_code.courseUnit.course resp.author = self.request.user resp.activity = activity resp.save() if not message.timestamp: serializer.save(content_id=resp.id, timestamp=timezone.now(), chat=chat, response_to_check=resp) else: serializer.save() return if message.input_type == 'options' and message.kind != 'button': if ( message.contenttype == 'uniterror' and 'selected' in self.request.data ): # user selected error model message.chat = chat try: selected = self.request.data.get( 'selected' )[str(message.id)]['errorModel'] except KeyError: selected = [] uniterror = message.content uniterror.save_response(user=self.request.user, response_list=selected) if not message.chat.is_live: get_additional_messages(uniterror.response, chat) chat.next_point = self.next_handler.next_point( current=message.content, chat=chat, message=message, request=self.request ) chat.last_modify_timestamp = timezone.now() chat.save() serializer.save(chat=chat) elif message.contenttype == 'NoneType' and message.kind == 'abort': # user selected abort model message.chat = chat try: selected = self.request.data.get( 'selected' )[str(message.id)]['errorModel'] except KeyError: selected = [] if not message.chat.is_live and selected: get_help_messages(chat) chat.next_point = self.next_handler.next_point( current=message.content, chat=chat, message=message, request=self.request ) chat.last_modify_timestamp = timezone.now() chat.save() serializer.save(chat=chat) elif message.content_id and not message.student_error: # confidence and selfeval message.chat = chat opt_data = self.request.data.get('option') resp = message.content if chat.state and chat.state.fsmNode.node_name_is_one_of('GET_CONFIDENCE'): resp.confidence = opt_data text = resp.get_confidence_display() else: resp.selfeval = opt_data text = resp.get_selfeval_display() # FIX if response was correct - user will not go to `else` section and response status should be set if resp.selfeval == StudentResponse.CORRECT: resp.status = DONE_STATUS message.text = text resp.save() chat.next_point = message chat.last_modify_timestamp = timezone.now() chat.save() serializer.save(content_id=resp.id, chat=chat, text=text) else: # message.chat = chat selfeval = self.request.data.get('option') resp = message.student_error resp.status = selfeval resp.save() # pass status to main response resp.response.status = selfeval resp.response.save() chat.next_point = message chat.last_modify_timestamp = timezone.now() chat.save() message.text = selfeval message.save() serializer.save(text=selfeval, chat=chat) if message.kind == 'button' and not (message.content_id and message.content and message.content.sub_kind): chat.last_modify_timestamp = timezone.now() chat.next_point = self.next_handler.next_point( current=message.content, chat=chat, message=message, request=self.request, ) chat.save()
class MyTestCase(TestCase): models_to_check = tuple() context_should_contain_keys = tuple() def setUp(self): self.username, self.password = '******', 'test' self.user = User.objects.create_user(self.username, '*****@*****.**', self.password) self.instructor = Instructor.objects.create(user=self.user, institution='institute', what_do_you_teach='something') self.username2, self.password2 = 'test1', 'test' self.user2 = User.objects.create_user(self.username2, '*****@*****.**', self.password2) self.instructor2 = Instructor.objects.create(user=self.user2, institution='institute', what_do_you_teach='something') self.unit = Unit(title='Test title', addedBy=self.user) self.unit.save() self.course = Course(title='Test title', description='test description', access='Public', enrollCode='111', lockout='222', addedBy=self.user) self.course.save() self.courseunit = CourseUnit( unit=self.unit, course=self.course, order=0, addedBy=self.user, releaseTime=timezone.now() ) self.courseunit.save() self.lesson = Lesson(title='title', text='text', addedBy=self.user) self.lesson.save() self.unitlesson = UnitLesson( unit=self.unit, order=0, lesson=self.lesson, addedBy=self.user, treeID=self.lesson.id ) self.unitlesson.save() self.resp1 = Response( unitLesson=self.unitlesson, kind=Response.ORCT_RESPONSE, lesson=self.lesson, course=self.course, text="Some text user may respond", author=self.user, status=NEED_HELP_STATUS, selfeval=Response.DIFFERENT ) self.resp1.save() self.resp2 = Response( unitLesson=self.unitlesson, kind=Response.ORCT_RESPONSE, lesson=self.lesson, course=self.course, text="Some text user may be responded 2", author=self.user, status=NEED_HELP_STATUS, selfeval=Response.DIFFERENT ) self.resp2.save() self.default_data = {} self.client.login(username=self.username, password=self.password) self.url = reverse('ctms:course_settings', kwargs={'pk': self.course.id}) def get_page(self): return self.client.get(self.url) def post_data(self, data={'name': 'some test name'}): response = self.client.post(self.url, data, follow=True) return response def get_client_method(self, method='post'): client_method = getattr(self.client, method) if not client_method: raise KeyError('self.client has no property {}'.format(method)) return client_method def post_valid_data(self, data={'name': 'some test name'}, method='post'): client_method = self.get_client_method(method) copied_data = {} if getattr(self, 'default_data', False): copied_data.update(self.default_data) copied_data.update(data) response = client_method(self.url, copied_data, follow=True) return response def post_invalid_data(self, data={'name': ''}, method='post'): client_method = self.get_client_method(method) copied_data = {} if getattr(self, 'default_data', False): copied_data.update(self.default_data) copied_data.update(data) response = client_method(self.url, copied_data, follow=True) return response def get_my_courses(self): return Course.objects.filter(addedBy=self.user) def get_test_course(self): return Course.objects.get(id=self.course.id) def get_test_unitlessons(self): return self.courseunit.unit.unitlesson_set.filter( kind=UnitLesson.COMPONENT, order__isnull=False ).order_by('order').annotate( responses_count=models.Count('response') ) def get_test_unitlesson(self): return self.courseunit.unit.unitlesson_set.filter( kind=UnitLesson.COMPONENT, order__isnull=False ).order_by('order').annotate( responses_count=models.Count('response') )[0] get_test_courslet = get_test_unitlesson get_test_response = lambda self: self.get_test_responses()[0] def get_test_courseunit(self): return CourseUnit.objects.get(id=self.courseunit.id) def get_test_responses(self): return Response.objects.filter( unitLesson=self.unitlesson, kind=Response.ORCT_RESPONSE, lesson=self.lesson, course=self.course, ) def get_model_counts(self, **kwargs): if isinstance(self.models_to_check, (list, tuple)): return {model: model.objects.filter().count() for model in self.models_to_check} return {self.models_to_check: self.models_to_check.objects.filter().count()} def validate_model_counts(self, first_counts, second_counts, must_equal=False): if isinstance(self.models_to_check, (list, tuple)): all_models = self.models_to_check else: all_models = [self.models_to_check] for model in all_models: if must_equal: self.assertEqual( first_counts[model], second_counts[model], "{} ({}) != {} ({}), with must_equal={}".format( model, first_counts[model], model, second_counts[model], must_equal ) ) else: self.assertNotEqual( first_counts[model], second_counts[model], "{} ({}) == {} ({}), with must_equal={}".format( model, first_counts[model], model, second_counts[model], must_equal ) ) def check_context_keys(self, response): for key in self.context_should_contain_keys: self.assertIn(key, response.context) def am_i_instructor(self, method='GET'): methods_map = {'GET', self.client.get, 'POST', self.client.post} client_method = methods_map.get(method) self.assertIsNotNone(client_method) if getattr(self, 'url'): if getattr(self, 'NEED_INSTRUCTOR'): response = client_method(self.url) if getattr(self, 'instructor'): self.assertEqual(response.status_code, 200) self.instructor.delete() response = client_method(self.url) self.assertEqual(response.status_code, 403) else: self.assertEqual(response.status_code, 403) else: response = client_method(self.url) self.assertEqual(response.status_code, 200)