Beispiel #1
0
    def test_create_course_form(self):
        s = Student(
            username='******',
            first_name='Testvorname4',
            last_name='Testnachname4',
            email='*****@*****.**'
        )
        s.save()
        l = Lecturer(
            username='******',
            first_name='Testvorname3',
            last_name='Testnachname3',
            email='*****@*****.**'
        )
        l.save()

        course_form = {
            'lecturer': l.id,
            'start_date': '2021-06-09',
            'end_date': '2023-06-09',
            'student': [s.id],
            'name': 'TestCourse'
        }
        course = CourseForm(course_form)
        self.assertTrue(course.is_valid())
        course.save()
 def test_public_teacher_dashboard_empty(self):
     user = User(username="******")
     user.save()
     student = Student(user=user)
     student.save()
     result = public_teacher_threads_student(student)
     expected = set()
     self.assertEquals(expected, result)
class TestDeleteMessage(TestCase):
    def setUp(self):
        self.first_user = User(username="******")
        self.first_user.set_password('12345')
        self.first_user.save()
        self.second_user = User(username="******")
        self.second_user.set_password('12345')
        self.second_user.save()
        self.third_user = User(username="******")
        self.third_user.save()
        self.first_student = Student(user=self.first_user)
        self.first_student.save()
        self.second_student = Student(user=self.second_user)
        self.second_student.save()
        self.teacher = Professor(user=self.third_user)
        self.teacher.save()
        self.stage = Stage(id=1, name="Stage1", level=1)
        self.stage.save()
        self.lesson = Lesson(id=1, name="Lesson 1", stage_id=1)
        self.lesson.save()
        self.thread_lesson = Thread.objects.create(author=self.first_user,
                                                   lesson=self.lesson,
                                                   title="Thread 1",
                                                   id=1)
        self.thread_lesson.save()
        self.thread_id = self.thread_lesson.id
        self.message = Message.objects.create(
            author=self.first_user,
            content="Content of message",
            thread=self.thread_lesson,
            created_date=utc.localize(datetime.now()),
            modified_date=utc.localize(datetime.now()))
        self.message.save()
        self.c = Client()
        self.c.login(username='******', password='******')
        self.c2 = Client()
        self.c2.login(username='******', password='******')

    def test_delete_unknown_thread(self):
        response = self.c.post('/forum/thread/{}/delete/{}'.format(402552, 1))
        self.assertEquals(response.status_code, 404)

    def test_delete_unknown_message(self):
        response = self.c.post('/forum/thread/{}/delete/{}'.format(
            self.thread_lesson.id, 1138282))
        self.assertEquals(response.status_code, 404)

    def test_delete_message(self):
        response = self.c.post('/forum/thread/{}/delete/{}'.format(
            self.thread_lesson.id, self.message.id))

        self.assertEquals(response.status_code, 302)
        self.assertFalse(Message.objects.filter(pk=self.message.id).exists())

    def test_edit_message_unauthorized(self):
        response = self.c2.post('/forum/thread/{}/delete/{}'.format(
            self.thread_lesson.id, self.message.id))
        self.assertEquals(response.status_code, 403)
Beispiel #4
0
    def test_create_and_delete_course_view(self):
        self.client.force_login(self.my_admin)
        s = Student(
            username='******',
            first_name='Testvorname4',
            last_name='Testnachname4',
            email='*****@*****.**'
        )
        s.save()
        l = Lecturer(
            username='******',
            first_name='Testvorname3',
            last_name='Testnachname3',
            email='*****@*****.**'
        )
        l.save()

        course_form = {
            'lecturer': l.id,
            'start_date': '2021-06-09',
            'end_date': '2023-06-09',
            'student': [s.id],
            'name': 'TestCourse'
        }

        course_form2 = {
            'lecturer': l.id,
            'start_date': '2021-06-09',
            'end_date': '2023-06-09',
            'student': [s.id],
            'name': 'ChangedCourse'
        }

        response = self.client.post(
            reverse('create_course'), course_form)
        self.assertEqual(response.status_code, HTTPStatus.OK)

        query_set = Course.objects.all()
        self.assertTrue(Course.objects.filter(name='TestCourse').exists())
        my_id = Course.objects.get(name='TestCourse').id

        response = self.client.post(
            reverse('edit_course', kwargs={'id': my_id}), course_form2)
        self.assertEqual(response.status_code, HTTPStatus.OK)
        self.assertTrue(Course.objects.filter(name='ChangedCourse').exists())

        response = self.client.post(
            reverse('detailed_course', args=(my_id,)))
        self.assertEqual(response.status_code, HTTPStatus.OK)

        response = self.client.post(
            reverse('delte_course', args=(my_id,)))
        self.assertEqual(response.status_code, HTTPStatus.OK)

        query_set = Course.objects.all()
        self.assertFalse(Course.objects.filter(name='TestCourse').exists())
Beispiel #5
0
def create_student():
    user = create_appuser()

    courses = Course.objects.all()
    course_list = [course for course in courses]

    faculties = Faculty.objects.all()
    faculty_list = [faculty for faculty in faculties]

    student = Student(
        app_user=user,
        number=random.randrange(1, 10000000000),
        call=random.choice([1, 2]),
        entry_grade=random.randrange(0, 201),
        statute=random.choice([
            "worker", "athlete", "fireman", "military", "union", "special",
            "parent"
        ]),
        faculty=random.choice(faculty_list),
    )

    student.save()
    student.course.add(random.choice(course_list))
Beispiel #6
0
def about(request):
    context={
        'posts': Post.objects.all()
    }
    username, password, state = request.user.username, request.GET.get('password', None), request.GET.get("state", None) # Get the username and password of the student
    print("\n\nThis is the username {username} and password {password}".format(username=username, password=password))
    # if the user the about page has been rendered
    
    if type(password) == str:
        try:
            user = Student.objects.filter(student_number=username)[0]
        
        except (IndexError):
            user = Student(student_number=username)

        results = init_web_scrap(username, password)
        user.courses = results
        user.save()

        password = None
        return JsonResponse(results)
   
    elif str(state) == "local":
        print("outside if condition")
        try:
            user = Student.objects.filter(student_number=username)[0]
            results = {}
            entry = user.courses.replace("{", "").replace("}","").replace("'","").split(",")
            # print(entry)
            for i in range(0, len(entry)):
                try:
                    index = entry[i].index(": course")
                    if i == 0:
                        key, value = entry[i][0: index], entry[i][index+2: ]
                    else:
                        key, value = entry[i][1: index], entry[i][index+2: ]
                except ValueError:
                    try:
                        index = entry[i].index(" resource")
                        if i == 0:
                            key, value = entry[i][0: index-1], entry[i][index+2: ]
                        else:
                            key, value = entry[i][1: index-1], entry[i][index+2: ]
                    except ValueError:
                        continue
                
                print("\n\n")
                print(key)
                print(value)
                results[key] = value
            print("\n\n after loop \n\n")
            return JsonResponse(results)
        except (IndexError):
            return JsonResponse({"User history not found, please click update resources to get your courses": "Error"})
    
    elif str(state) == "download":
        file_name = request.GET.get("file_name", None)
        # try:
        print("hgerjk")
        file_ = open(os.getcwd() + "/" + file_name + ".pdf", "rb").read()
        print(file_)
        #  sending response 
        response = HttpResponse(file_, content_type='pdf')
        response['Content-Disposition'] = 'attachment; filename={file_name}.pdf'.format(file_name=file_name)
        return response
        # except Exception:
            # handle file not exist case here
            # return JsonResponse({"File not found, please click update resources to get your courses": "Error"})

        return response

    return render(request,'blog/about.html', context)#these files are out of the directories of the prohects
class TestMisc(TestCase):
    def setUp(self):
        self.user = User(username="******")
        self.user.set_password('12345')
        self.user.save()
        self.second_user = User(username="******")
        self.second_user.set_password('12345')
        self.second_user.save()
        self.teacher_user = User(username="******")
        self.teacher_user.save()
        self.second_teacher_user = User(username="******")
        self.second_teacher_user.save()

        self.student = Student(user=self.user)
        self.student.save()
        self.second_student = Student(user=self.second_user)
        self.second_student.save()
        self.teacher = Professor(user=self.teacher_user)
        self.teacher.save()
        self.second_teacher = Professor(user=self.second_teacher_user)
        self.second_teacher.save()

        self.skill1 = Skill(id=1, name="Skill1", code="1")
        self.skill1.save()

        self.skill2 = Skill(id=2, name="Skill2", code="2")
        self.skill2.save()

        self.section = Section(id=1, name="Section1")
        self.section.save()

        self.skill3 = Skill(id=3, name="Skill3", code="3")
        self.skill3.section = self.section
        self.skill3.save()

        self.skill4 = Skill(id=4, name="Skill4", code="4")
        self.skill4.section = self.section
        self.skill4.save()

        self.stage = Stage(id=1, name="Stage1", level=1)
        self.stage.save()
        self.stage.skills.add(self.skill1)
        self.stage.skills.add(self.skill2)
        self.stage.save()

        self.second_stage = Stage(id=2, name="Stage2", level=1)
        self.second_stage.save()
        self.second_stage.skills.add(self.skill3)
        self.second_stage.skills.add(self.skill4)
        self.second_stage.save()

        self.lesson = Lesson(id=1, name="English", stage_id=1)
        self.lesson.save()
        self.lesson.students.add(self.student)
        self.lesson.students.add(self.second_student)
        self.lesson.professors.add(self.teacher)
        self.lesson.save()

        self.second_lesson = Lesson(id=2, name="French", stage_id=2)
        self.second_lesson.save()
        self.second_lesson.students.add(self.second_student)
        self.second_lesson.professors.add(self.teacher)
        self.second_lesson.save()

        self.thread = Thread(title="Help",
                             author=self.user,
                             recipient=self.teacher_user)
        self.thread.save()

        self.second_thread = Thread(title="Send help",
                                    author=self.second_user,
                                    lesson=self.second_lesson)
        self.second_thread.save()

        self.third_thread = Thread(title="Information regarding w/e",
                                   author=self.teacher_user,
                                   professor=self.teacher)
        self.third_thread.save()

        self.fourth_thread = Thread(title="Information regarding spam",
                                    author=self.teacher_user,
                                    professor=self.teacher)
        self.fourth_thread.save()

        self.c1 = Client()
        self.c1.login(username=self.user.username, password='******')

        self.c2 = Client()
        self.c2.login(username=self.second_user.username, password='******')

    def test_get_skills_user(self):
        skills, sections = get_skills(FakeRequest(self.user))
        self.assertEquals(len(skills), 2)

        self.assertListEqual(skills, [self.skill1, self.skill2])
        self.assertEquals(len(sections), 0)

    def test_get_skills_second_user(self):
        skills, sections = get_skills(FakeRequest(self.second_user))
        self.assertEquals(len(skills), 4)
        self.assertListEqual(
            skills, [self.skill1, self.skill2, self.skill3, self.skill4])

        self.assertEqual(len(sections), 1)
        self.assertEqual(sections[0], self.skill3.section)

    def test_get_professors_user(self):
        response = self.c1.get('/forum/write/professors/')
        json_data = json.loads(response.content)
        data = json_data["data"]

        professor = data[0]
        self.assertEquals(len(data), 1)
        self.assertEquals(
            professor, {
                "id": self.teacher.id,
                "username": self.teacher.user.username,
                "first_name": self.teacher.user.first_name,
                "last_name": self.teacher.user.last_name
            })

    def test_get_professors_second_user(self):
        response = self.c2.get('/forum/write/professors/')
        json_data = json.loads(response.content)
        data = json_data["data"]
        professor = data[0]
        self.assertEquals(len(data), 1)
        self.assertEquals(
            professor, {
                "id": self.teacher.id,
                "username": self.teacher.user.username,
                "first_name": self.teacher.user.first_name,
                "last_name": self.teacher.user.last_name
            })

    def test_get_lessons_user(self):
        response = self.c1.get('/forum/write/lessons/')
        json_data = json.loads(response.content)
        data = json_data["data"]
        self.assertEquals(len(data), 1)

        lesson = data[0]
        self.assertEqual(lesson["id"], self.lesson.id)
        self.assertEqual(lesson["name"], self.lesson.name)

    def test_get_lessons_second_user(self):
        response = self.c2.get('/forum/write/lessons/')
        json_data = json.loads(response.content)
        data = json_data["data"]

        self.assertEquals(len(data), 2)

        lesson = data[0]
        self.assertEqual(lesson["id"], self.lesson.id)
        self.assertEqual(lesson["name"], self.lesson.name)

        lesson2 = data[1]
        self.assertEqual(lesson2["id"], self.second_lesson.id)
        self.assertEqual(lesson2["name"], self.second_lesson.name)

    def test_get_users(self):
        response = self.c1.get('/forum/write/users/')
        json_data = json.loads(response.content)
        data = json_data["data"]
        users = User.objects.all()
        for i, user in enumerate(data):
            self.assertEquals(
                user, {
                    'id': users[i].id,
                    'username': users[i].username,
                    'first_name': users[i].first_name,
                    'last_name': users[i].last_name
                })
class TestPostThread(TestCase):
    def setUp(self):
        self.user1 = User(username='******')
        self.user1.set_password('12345')
        self.user1.save()
        self.teacher = Professor(user=self.user1)
        self.teacher.save()
        self.user2 = User(username="******")
        self.user2.save()
        self.student = Student(user=self.user2)
        self.student.save()
        self.stage = Stage(id=1, name="Stage1", level=1)
        self.stage.save()
        self.lesson = Lesson(id=1, name="Lesson 1", stage_id=1)
        self.lesson.save()
        self.skill1 = Skill(code=422230,
                            name="Compter deux par deux",
                            description="")
        self.skill1.save()
        self.skill2 = Skill(code=422231,
                            name="Lacer ses chaussures",
                            description="")
        self.skill2.save()
        self.c = Client()
        self.c.login(username='******', password='******')

    def test_post_valid_new_public_thread(self):
        new_thread = {
            "title": "titre_1",
            "visibdata": str(self.teacher.id),
            "skills": [422230, 422231],
            "content": "message_1",
            "visibility": "public"
        }
        response = self.c.post('/forum/write/', data=new_thread)
        new_thread = Thread.objects.order_by('-pk')[0]
        last_msg = Message.objects.order_by('-pk')[0]
        self.assertEquals(response.status_code, 302)
        self.assertEquals(new_thread.title, "titre_1")
        self.assertEquals(last_msg.content, "message_1")

    def test_post_valid_new_private_thread(self):
        new_thread = {
            "title": "titre_2",
            "visibdata": str(self.user2.id),
            "skills": [422230, 422231],
            "content": "message_2",
            "visibility": "private"
        }
        response = self.c.post('/forum/write/', data=new_thread)
        new_thread = Thread.objects.order_by('-pk')[0]
        last_msg = Message.objects.order_by('-pk')[0]
        self.assertEquals(response.status_code, 302)
        self.assertEquals(new_thread.title, "titre_2")
        self.assertEquals(last_msg.content, "message_2")

    def test_post_valid_new_class_thread(self):
        new_thread = {
            "title": "titre_3",
            "visibdata": str(self.lesson.id),
            "skills": [422230, 422231],
            "content": "message_3",
            "visibility": "class"
        }
        response = self.c.post('/forum/write/', data=new_thread)
        new_thread = Thread.objects.order_by('-pk')[0]
        last_msg = Message.objects.order_by('-pk')[0]
        self.assertEquals(response.status_code, 302)
        self.assertEquals(new_thread.title, "titre_3")
        self.assertEquals(last_msg.content, "message_3")

    def test_post_invalid_new_thread_blank_req_fields(self):
        thread_cnt_before = Thread.objects.all().count()
        msg_cnt_before = Message.objects.all().count()
        new_thread = {
            "title": "",
            "visibdata": "",
            "skills": "",
            "content": "",
            "visibility": ""
        }
        response = self.c.post('/forum/write/', data=new_thread)
        self.assertEquals(response.status_code, 200)
        self.assertEquals(thread_cnt_before, Thread.objects.all().count())
        self.assertEquals(msg_cnt_before, Message.objects.all().count())

    def test_post_invalid_new_thread_unknown_skills(self):
        thread_cnt_before = Thread.objects.all().count()
        msg_cnt_before = Message.objects.all().count()
        new_thread = {
            "title": "titre_5",
            "visibdata": str(self.lesson.id),
            "skills": ["l", "m"],
            "content": "message_5",
            "visibility": "class"
        }
        response = self.c.post('/forum/write/', data=new_thread)
        self.assertEquals(response.status_code, 200)
        self.assertEquals(thread_cnt_before, Thread.objects.all().count())
        self.assertEquals(msg_cnt_before, Message.objects.all().count())

    def test_post_invalid_new_private_thread_unknown_recipient(self):
        thread_cnt_before = Thread.objects.all().count()
        msg_cnt_before = Message.objects.all().count()
        new_thread = {
            "title": "titre_6",
            "visibdata": "unknown",
            "skills": "422230 422231",
            "content": "message_6",
            "visibility": "private"
        }
        response = self.c.post('/forum/write/', data=new_thread)
        self.assertEquals(response.status_code, 200)
        self.assertEquals(thread_cnt_before, Thread.objects.all().count())
        self.assertEquals(msg_cnt_before, Message.objects.all().count())

    def test_post_invalid_new_class_thread_unknown_class(self):
        thread_cnt_before = Thread.objects.all().count()
        msg_cnt_before = Message.objects.all().count()
        new_thread = {
            "title": "titre_7",
            "visibdata": "unknown",
            "skills": [422230, 422231],
            "content": "message_7",
            "visibility": "class"
        }
        response = self.c.post('/forum/write/', data=new_thread)
        self.assertEquals(response.status_code, 200)
        self.assertEquals(thread_cnt_before, Thread.objects.all().count())
        self.assertEquals(msg_cnt_before, Message.objects.all().count())

    def test_post_invalid_new_public_thread_unknown_professor(self):
        thread_cnt_before = Thread.objects.all().count()
        msg_cnt_before = Message.objects.all().count()
        new_thread = {
            "title": "titre_8",
            "visibdata": "unknown",
            "skills": [422230, 422231],
            "content": "message_7",
            "visibility": "public"
        }
        response = self.c.post('/forum/write/', data=new_thread)
        self.assertEquals(response.status_code, 200)
        self.assertEquals(thread_cnt_before, Thread.objects.all().count())
        self.assertEquals(msg_cnt_before, Message.objects.all().count())
class TestAttachment(TestCase):
    def setUp(self):
        self.first_user = User(username="******")
        self.first_user.set_password('12345')
        self.first_user.save()
        self.second_user = User(username="******")
        self.second_user.set_password('12345')
        self.second_user.save()
        self.third_user = User(username="******")
        self.third_user.save()
        self.first_student = Student(user=self.first_user)
        self.first_student.save()
        self.second_student = Student(user=self.second_user)
        self.second_student.save()
        self.teacher = Professor(user=self.third_user)
        self.teacher.save()
        self.stage = Stage(id=1, name="Stage1", level=1)
        self.stage.save()
        self.lesson = Lesson(id=1, name="Lesson 1", stage_id=1)
        self.lesson.save()
        self.thread_lesson = Thread.objects.create(author=self.first_user,
                                                   lesson=self.lesson,
                                                   title="Thread 1",
                                                   id=1)
        self.thread_lesson.save()
        self.thread_id = self.thread_lesson.id
        self.message = Message.objects.create(
            author=self.first_user,
            content="Content of message",
            thread=self.thread_lesson,
            created_date=utc.localize(datetime.now()),
            modified_date=utc.localize(datetime.now()))
        self.message.save()
        self.c = Client()
        self.c.login(username='******', password='******')
        self.c2 = Client()
        self.c2.login(username='******', password='******')
        self.file = SimpleUploadedFile('file.txt', b'OOOOOOOOOOOOOOOOOOOO')
        self.attachment = MessageAttachment.objects.create(
            name=self.file.name, file=self.file, message=self.message)
        self.attachment.save()

    def test_reply_thread_with_attachment(self):
        content = 'content of the new message'
        file = SimpleUploadedFile('file.png',
                                  b'AAAAAAAA',
                                  content_type='image/png')
        response = self.c.post('/forum/thread/{}'.format(self.thread_id),
                               data={
                                   'content': content,
                                   'file': file
                               })

        messages = Message.objects.all().filter(thread=self.thread_lesson)

        self.assertEquals(messages.last().content, content)
        self.assertTrue(messages.last().attachments()[0])
        self.assertEquals(response.status_code, 302)

    def test_reply_parent_message_with_attachment(self):
        content = 'content of the new message'
        response = self.c.post('/forum/thread/{}'.format(self.thread_id),
                               data={'content': content})

        messages = Message.objects.all().filter(thread=self.thread_lesson)

        self.assertEquals(messages.last().content, content)
        self.assertEquals(response.status_code, 302)  # 302 because redirects

        file = SimpleUploadedFile('file1',
                                  b'AAAAAAAA',
                                  content_type='image/png')
        content = 'content'
        response = self.c.post('/forum/thread/{}?reply_to={}'.format(
            self.thread_id,
            messages.last().id),
                               data={
                                   'content': content,
                                   'file': file
                               })
        self.assertEquals(response.status_code, 302)

    def test_edit_message_and_attachment(self):
        new_content = "New Content"
        new_file = SimpleUploadedFile('file.png',
                                      b'AAAAAAAA',
                                      content_type='image/png')
        response = self.c.post('/forum/thread/{}/edit/{}'.format(
            self.thread_lesson.id, self.message.id),
                               data={
                                   "content": new_content,
                                   "file": new_file
                               })

        self.assertEquals(response.status_code, 302)
        self.assertEquals(
            Message.objects.get(pk=self.message.id).content, new_content)
        self.assertFalse(
            Message.objects.get(pk=self.message.id).attachments()[0].file ==
            self.attachment.file)

    def test_delete_message_and_attachments(self):
        response = self.c.post('/forum/thread/{}/delete/{}'.format(
            self.thread_lesson.id, self.message.id))

        self.assertEquals(response.status_code, 302)
        self.assertFalse(Message.objects.filter(pk=self.message.id).exists())
        self.assertFalse(
            MessageAttachment.objects.filter(pk=self.attachment.id).exists())
class TestPostReply(TestCase):
    def setUp(self):
        self.first_user = User(username="******")
        self.first_user.set_password('12345')
        self.first_user.save()
        self.second_user = User(username="******")
        self.second_user.set_password('12345')
        self.second_user.save()
        self.third_user = User(username="******")
        self.third_user.save()
        self.first_student = Student(user=self.first_user)
        self.first_student.save()
        self.second_student = Student(user=self.second_user)
        self.second_student.save()
        self.teacher = Professor(user=self.third_user)
        self.teacher.save()
        self.stage = Stage(id=1, name="Stage1", level=1)
        self.stage.save()
        self.lesson = Lesson(id=1, name="Lesson 1", stage_id=1)
        self.lesson.save()
        self.thread_lesson = Thread.objects.create(author=self.first_user,
                                                   lesson=self.lesson,
                                                   title="Thread 1",
                                                   id=1)
        self.thread_lesson.save()
        self.thread_id = self.thread_lesson.id
        self.message = Message.objects.create(
            author=self.first_user,
            content="Content of message",
            thread=self.thread_lesson,
            created_date=utc.localize(datetime.now()),
            modified_date=utc.localize(datetime.now()))
        self.message.save()
        self.c = Client()
        self.c.login(username='******', password='******')
        self.c2 = Client()
        self.c2.login(username='******', password='******')

    def test_get_thread_page(self):
        response = self.c.get('/forum/thread/{}'.format(self.thread_id))
        self.assertEquals(response.status_code, 200)

    def test_reply_thread(self):
        content = 'content of the new message'
        response = self.c.post('/forum/thread/{}'.format(self.thread_id),
                               data={'content': content})

        messages = Message.objects.all().filter(thread=self.thread_lesson)

        self.assertEquals(messages.last().content, content)
        self.assertEquals(response.status_code, 302)  # 302 because redirects

    def test_reply_thread(self):
        response = self.c.post('/forum/thread/{}'.format(self.thread_id))

        self.assertEquals(response.status_code, 400)  # 302 because redirects

    def test_reply_parent_message(self):
        content = 'content of the new message'
        response = self.c.post('/forum/thread/{}'.format(self.thread_id),
                               data={'content': content})

        messages = Message.objects.all().filter(thread=self.thread_lesson)

        self.assertEquals(messages.last().content, content)
        self.assertEquals(response.status_code, 302)  # 302 because redirects

        content = 'content'
        response = self.c.post('/forum/thread/{}?reply_to={}'.format(
            self.thread_id,
            messages.last().id),
                               data={'content': content})
        self.assertEquals(response.status_code, 302)

    def test_reply_unknown_parent_message(self):
        content = 'content'
        response = self.c.post('/forum/thread/{}?reply_to=155'.format(
            self.thread_id),
                               data={'content': content})
        self.assertEquals(response.status_code, 404)
class TestGetDashboard(TestCase):
    def setUp(self):
        self.user = User(username="******")
        self.user.save()
        self.second_user = User(username="******")
        self.second_user.save()
        self.teacher_user = User(username="******")
        self.teacher_user.save()
        self.second_teacher_user = User(username="******")
        self.second_teacher_user.save()

        self.student = Student(user=self.user)
        self.student.save()
        self.second_student = Student(user=self.second_user)
        self.second_student.save()
        self.teacher = Professor(user=self.teacher_user)
        self.teacher.save()
        self.second_teacher = Professor(user=self.second_teacher_user)
        self.second_teacher.save()

        self.stage = Stage(id=1, name="Stage1", level=1)
        self.stage.save()
        self.second_stage = Stage(id=2, name="Stage2", level=1)
        self.second_stage.save()

        self.lesson = Lesson(id=1, name="English", stage_id=1)
        self.lesson.save()
        self.lesson.students.add(self.student)
        self.lesson.students.add(self.second_student)
        self.lesson.professors.add(self.teacher)
        self.lesson.save()

        self.second_lesson = Lesson(id=2, name="French", stage_id=2)
        self.second_lesson.save()
        self.second_lesson.students.add(self.second_student)
        self.second_lesson.professors.add(self.teacher)
        self.second_lesson.save()

        self.thread = Thread(title="Help",
                             author=self.user,
                             recipient=self.teacher_user)
        self.thread.save()

        self.second_thread = Thread(title="Send help",
                                    author=self.second_user,
                                    lesson=self.second_lesson)
        self.second_thread.save()

        self.third_thread = Thread(title="Information regarding w/e",
                                   author=self.teacher_user,
                                   professor=self.teacher)
        self.third_thread.save()

        self.fourth_thread = Thread(title="Information regarding spam",
                                    author=self.teacher_user,
                                    professor=self.teacher)
        self.fourth_thread.save()

    # TODO
    def test_forum_dashboard(self):
        factory = RequestFactory()
        request = factory.get("/forum/")
        request.user = self.user
        response = forum_dashboard(request)
        self.assertEquals(response.status_code, 200)

    def test_private_dashboard_empty(self):
        user = User(username="******")
        user.save()
        result = private_threads(user)
        expected = set()
        self.assertEquals(expected, result)

    def test_private_dashboard(self):
        result = private_threads(self.user)
        expected = set()
        expected.add(self.thread)
        self.assertEquals(expected, result)

    def test_public_class_dashboard_empty(self):
        user = User(username="******")
        user.save()
        student = Student(user=user)
        student.save()
        result = public_class_threads(student)
        expected = set()
        self.assertEquals(expected, result)

    def test_public_class_dashboard(self):
        result = public_class_threads(self.second_student)
        expected = set()
        expected.add(self.second_thread)
        self.assertEquals(expected, result)

    def test_public_teacher_dashboard_empty(self):
        user = User(username="******")
        user.save()
        student = Student(user=user)
        student.save()
        result = public_teacher_threads_student(student)
        expected = set()
        self.assertEquals(expected, result)

    def test_public_class_dashboard_teacher(self):
        result = public_teacher_threads_student(self.teacher)
        expected = set()
        expected.add(self.third_thread)
        expected.add(self.fourth_thread)
        self.assertEquals(expected, result)

    def test_get_thread_set_teacher(self):
        result = get_thread_set(self.teacher_user)
        expected = set()
        expected.add(self.thread)
        expected.add(self.second_thread)
        expected.add(self.third_thread)
        expected.add(self.fourth_thread)
        self.assertEquals(expected, result)
class TestResources(TestCase):
    def setUp(self):
        self.user = User(username="******")
        self.user.set_password('12345')
        self.user.save()
        self.teacher_user = User(username="******")
        self.teacher_user.set_password('12345')
        self.teacher_user.save()

        self.student = Student(user=self.user)
        self.student.save()
        self.teacher = Professor(user=self.teacher_user)
        self.teacher.save()

        res1_content = {"title": "Res1"}
        self.res1 = Resource(added_by=self.teacher_user, content=res1_content)
        self.res1.save()

        self.section = Section(id=1, name="Section1")
        self.section.save()
        self.section.resource.add(self.res1)
        self.section.save()

        self.skill2 = Skill(id=2, name="Skill2", code="2")
        self.skill2.save()

        res2_content = {"title": "Res2"}
        self.res2 = Resource(added_by=self.teacher_user, content=res2_content)
        self.res2.save()

        self.skill3 = Skill(id=3, name="Skill3", code="3")
        self.skill3.save()
        self.skill3.resource.add(self.res2)
        self.skill3.save()

        self.skill4 = Skill(id=4, name="Skill4", code="4")
        self.skill4.section = self.section
        self.skill4.save()

        self.stage = Stage(id=1, name="Stage1", level=1)
        self.stage.save()
        self.stage.skills.add(self.skill3)
        self.stage.skills.add(self.skill4)
        self.stage.save()

        self.lesson = Lesson(id=1, name="English", stage_id=1)
        self.lesson.save()
        self.lesson.students.add(self.student)
        self.lesson.professors.add(self.teacher)
        self.lesson.save()

        self.s1 = Client()
        self.s1.login(username=self.user.username, password='******')

        self.t1 = Client()
        self.t1.login(username=self.teacher_user.username, password='******')

    def test_get_all_resources(self):
        response = self.s1.get('/forum/write/resources/')
        json_data = json.loads(response.content)
        data = json_data["data"]

        self.assertEquals(len(data), 2)

        correct_ids = [self.res1.id, self.res2.id]
        self.assertTrue(data[0]["id"] in correct_ids)
        self.assertTrue(data[1]["id"] in correct_ids)

    def test_get_section_resources(self):
        response = self.s1.get(
            '/forum/write/resources/?section={0}&skills[]={1}'.format(
                self.section.id, 0))
        json_data = json.loads(response.content)
        data = json_data["data"]

        self.assertEquals(len(data), 1)

        self.assertEquals(data[0]["title"], self.res1.content['title'])

    def test_get_skills_resources(self):
        response = self.s1.get(
            '/forum/write/resources/?skills[]={0}&section={1}'.format(
                self.skill3.id, 0))
        json_data = json.loads(response.content)
        data = json_data["data"]

        self.assertEquals(len(data), 1)

        self.assertEquals(data[0]["title"], self.res2.content['title'])
Beispiel #13
0
def create_password(request, backend, *args, **kwargs):
    """
    1. existing student
        1. verified -> good to go
        2. not verified but we have email (i.e. hasn't clicked on link in email) -> resend verification email
        3. not verified and no email -> redirect
    2. new student
        1. if coming back from partial -> create student record and update, send verification email
        2. first entry -> redirect
    """
    print 1
    user = kwargs['user']
    if hasattr(user, 'student'):
        print 2
        print user.student.verified_email
        if user.student.verified_email:
            print 3
            if user.is_verified:
                print 4
                # everything's good!
                pass
            else:
                print 5
                # reminder message to update link
                pass
        else:
            print 6
            if 'verified_email' in request.session.keys(
            ) and 'school_network' in request.session.keys():
                print request.session['verified_email']
                print request.session['school_network']
                user.student.verified_email = request.session['verified_email']
                user.student.save()

                g = Group.objects.get(id=request.session['school_network'])
                user.groups.add(g)
                user.save()

                # send user verification email
                from_email = '*****@*****.**'
                to_email = user.student.verified_email
                verification_token = hashlib.sha224(
                    user.first_name + user.last_name +
                    user.student.verified_email +
                    request.session['school_network'] +
                    str(datetime.datetime.now())).hexdigest()
                verification_url = BASE_URL + "verify/" + verification_token + "/"
                user.verification_token = verification_token
                user.is_verified = False
                user.save()
                send_mail(
                    '[Occuhunt] Verify your network.',
                    'Click on the following link to verify your network: ' +
                    verification_url,
                    from_email, [to_email],
                    fail_silently=False)
                os.system('python manage.py send_mail')
            else:
                return redirect('get-email-network')
    else:
        print 7
        if 'verified_email' in request.session.keys(
        ) and 'school_network' in request.session.keys():
            # save network and verified email and convert to student
            print 8
            student_user = Student(user_ptr_id=user.id)
            student_user.__dict__.update(user.__dict__)
            student_user.verified_email = request.session['verified_email']

            g = Group.objects.get(id=request.session['school_network'])
            student_user.groups.add(g)
            student_user.save()

            # send student verification email
            from_email = '*****@*****.**'
            to_email = student_user.verified_email
            verification_token = hashlib.sha224(
                student_user.first_name + student_user.last_name +
                student_user.verified_email +
                request.session['school_network'] +
                str(datetime.datetime.now())).hexdigest()
            verification_url = BASE_URL + "verify/" + verification_token + "/"
            user.verification_token = verification_token
            user.is_verified = False
            user.save()
            send_mail('[Occuhunt] Verify your network.',
                      'Click on the following link to verify your network: ' +
                      verification_url,
                      from_email, [to_email],
                      fail_silently=False)
            os.system('python manage.py send_mail')
            print "sent email"
        else:
            print 10
            # create user and password for student
            uid = kwargs['uid']
            user.linkedin_uid = uid
            user.set_password(uid)
            user.save()
            # redirect to confirm network
            return redirect('get-email-network')
Beispiel #14
0
def register(request):
    """This is the register function"""

    base = get_base(request)

    # After use submits its credentials
    if request.method == 'POST':

        email = request.POST.get('email')
        rollno = request.POST.get('rollno')
        first_name = request.POST.get('first_name')
        last_name = request.POST.get('last_name')
        password1 = request.POST.get('password1')
        password2 = request.POST.get('password2')

        # Checks for missing form fieds
        if not email:
            message = "Please provide a valid email"
            return render(
                request, "login_error.html", {
                    "message": message,
                    "base": base,
                    'semesters': semesters,
                    'departments': departments,
                    'subjects': subjects
                })

        if not password1 or not password2:
            message = "Passwords do not match"
            return render(
                request, "login_error.html", {
                    "message": message,
                    "base": base,
                    'semesters': semesters,
                    'departments': departments,
                    'subjects': subjects
                })

        if not first_name:
            message = "Please provide your name"
            return render(
                request, "login_error.html", {
                    "message": message,
                    "base": base,
                    'semesters': semesters,
                    'departments': departments,
                    'subjects': subjects
                })

        if not last_name:
            last_name = ""

        if not rollno:
            message = "Please provide your roll number"
            return render(
                request, "login_error.html", {
                    "message": message,
                    "base": base,
                    'semesters': semesters,
                    'departments': departments,
                    'subjects': subjects
                })

        # Checks for invalid form fields
        invalid = []
        if "@" not in email or "." not in email:
            message = "Please provide a valid email."
            return render(
                request, "login_error.html", {
                    "message": message,
                    "base": base,
                    'semesters': semesters,
                    'departments': departments,
                    'subjects': subjects
                })

        # Check for duplicate email
        try:
            already_user = User.objects.get(username=rollno)
        except:
            already_user = None

        if already_user != None:
            message = "The roll number entered already has an account"
            return render(
                request, "login_error.html", {
                    "message": message,
                    "base": base,
                    'semesters': semesters,
                    'departments': departments,
                    'subjects': subjects
                })

        if password1 == password2:

            # Creating a user on the platform
            user_created = User.objects.create_user(email=email,
                                                    username=rollno,
                                                    password=password1,
                                                    first_name=first_name,
                                                    last_name=last_name)

            userprofile = UserProfile()
            userprofile.user = user_created
            #userprofile.name = user_created.first_name +" "+ user_created.last_name
            userprofile.save()

            userprofile = UserProfile.objects.get(user=user_created)

            student = Student()
            student.userprofile = userprofile
            student.rollno = rollno
            student.save()

            user = authenticate(username=rollno, password=password1)

            # The user can be inactive
            if user.is_active:
                auth_login(request, user)
                return redirect('/home/')
            else:
                message = """The user is not active.
                            Kindly contact the administrator"""
                return render(
                    request, 'login_error.html', {
                        "message": message,
                        "base": base,
                        'semesters': semesters,
                        'departments': departments,
                        'subjects': subjects
                    })

        else:
            message = "Passwords do not match"
            return render(
                request, "login_error.html", {
                    "message": message,
                    "base": base,
                    'semesters': semesters,
                    'departments': departments,
                    'subjects': subjects
                })

    return render(
        request, "register.html", {
            "base": base,
            'semesters': semesters,
            'departments': departments,
            'subjects': subjects
        })
Beispiel #15
0
def create_password(request, backend, *args, **kwargs):
    """
    1. existing student
        1. verified -> good to go
        2. not verified but we have email (i.e. hasn't clicked on link in email) -> resend verification email
        3. not verified and no email -> redirect
    2. new student
        1. if coming back from partial -> create student record and update, send verification email
        2. first entry -> redirect
    """
    print 1
    user = kwargs['user']
    if hasattr(user, 'student'):
        print 2
        print user.student.verified_email
        if user.student.verified_email:
            print 3
            if user.is_verified:
                print 4
                # everything's good!
                pass
            else:
                print 5
                # reminder message to update link
                pass
        else:
            print 6
            if 'verified_email' in request.session.keys() and 'school_network' in request.session.keys():
                print request.session['verified_email']
                print request.session['school_network']
                user.student.verified_email = request.session['verified_email']
                user.student.save()
                
                g = Group.objects.get(id=request.session['school_network'])
                user.groups.add(g)
                user.save()

                # send user verification email
                from_email = '*****@*****.**'
                to_email = user.student.verified_email
                verification_token = hashlib.sha224(user.first_name+user.last_name+user.student.verified_email+request.session['school_network']+str(datetime.datetime.now())).hexdigest()
                verification_url = BASE_URL+"verify/"+verification_token+"/"
                user.verification_token = verification_token
                user.is_verified = False
                user.save()
                send_mail('[Occuhunt] Verify your network.', 'Click on the following link to verify your network: '+verification_url, from_email, [to_email], fail_silently=False)
                os.system('python manage.py send_mail')
            else:
                return redirect('get-email-network')
    else:
        print 7
        if 'verified_email' in request.session.keys() and 'school_network' in request.session.keys():
            # save network and verified email and convert to student
            print 8
            student_user = Student(user_ptr_id=user.id)
            student_user.__dict__.update(user.__dict__)
            student_user.verified_email = request.session['verified_email']

            g = Group.objects.get(id=request.session['school_network'])
            student_user.groups.add(g)
            student_user.save()

            # send student verification email
            from_email = '*****@*****.**'
            to_email = student_user.verified_email
            verification_token = hashlib.sha224(student_user.first_name+student_user.last_name+student_user.verified_email+request.session['school_network']+str(datetime.datetime.now())).hexdigest()
            verification_url = BASE_URL+"verify/"+verification_token+"/"
            user.verification_token = verification_token
            user.is_verified = False
            user.save()
            send_mail('[Occuhunt] Verify your network.', 'Click on the following link to verify your network: '+verification_url, from_email, [to_email], fail_silently=False)
            os.system('python manage.py send_mail')
            print "sent email"
        else:
            print 10
            # create user and password for student
            uid = kwargs['uid']
            user.linkedin_uid = uid
            user.set_password(uid)
            user.save()
            # redirect to confirm network
            return redirect('get-email-network')