Пример #1
0
 def test_add_current_currency_and_calculator(self):
     client = APIClient()
     data = json.dumps({"base_total": 10, "target_currency": "TRY"})
     response = client.generic('POST', '/exchangeRateAPI/add/currentCurrency/', data)
     self.assertEqual(response.status_code, status.HTTP_200_OK)
Пример #2
0
 def test_add_category(self):
     client = APIClient()
     data = json.dumps({"category_name": "Soccer", "category_description": "Soccer description", "max_player": 100})
     response = client.generic('POST', '/exchangeRateAPI/add/category/', data)
     self.assertEqual(response.status_code, status.HTTP_200_OK)
Пример #3
0
class HawkAPITestClient:
    """Simple test client for making requests signed using Hawk."""

    DEFAULT_HTTP_X_FORWARDED_FOR = '1.2.3.4, 123.123.123.123'
    unset = object()

    def __init__(self):
        """Initialise the client and create an APIClient instance."""
        self.api_client = APIClient()
        self.credentials = None
        self.http_x_forwarded_for = self.DEFAULT_HTTP_X_FORWARDED_FOR

    def set_credentials(self, id_, key, algorithm='sha256'):
        """Set the credentials for requests."""
        self.credentials = {
            'id': id_,
            'key': key,
            'algorithm': algorithm,
        }

    def set_http_x_forwarded_for(self, http_x_forwarded_for):
        """Set client IP addresses."""
        self.http_x_forwarded_for = http_x_forwarded_for

    def get(self, path, params=None):
        """Make a GET request (optionally with query params)."""
        return self.request('get', path, params=params)

    def post(self, path, json_):
        """Make a POST request with a JSON body."""
        return self.request('post', path, json_=json_)

    def put(self, path, json_):
        """Make a PUT request with a JSON body."""
        return self.request('put', path, json_=json_)

    def patch(self, path, json_):
        """Make a PATCH request with a JSON body."""
        return self.request('patch', path, json_=json_)

    def delete(self, path, json_):
        """Make a DELETE request with a JSON body."""
        return self.request('delete', path, json_=json_)

    def request(self, method, path, params=None, json_=unset, content_type=''):
        """Make a request with a specified HTTP method."""
        params = urlencode(params) if params else ''
        url = join_truthy_strings(f'http://testserver{path}', params, sep='?')

        if json_ is not self.unset:
            content_type = 'application/json'
            body = json.dumps(json_, cls=DjangoJSONEncoder).encode('utf-8')
        else:
            body = b''

        sender = mohawk.Sender(
            self.credentials,
            url,
            method,
            content=body,
            content_type=content_type,
        )

        return self.api_client.generic(
            method,
            url,
            HTTP_AUTHORIZATION=sender.request_header,
            HTTP_X_FORWARDED_FOR=self.http_x_forwarded_for,
            data=body,
            content_type=content_type,
        )
class CategoryItemViewTest(TestCase):
    def setUp(self):
        self.client = APIClient()
        self.basic_client = Client()
        self.user = User.objects.create_superuser(
            email=EMAIL_TEST, password=PASSWORD_TEST)
        self.other_user = User.objects.create_superuser(
            email=OTHER_EMAIL_TEST, password=PASSWORD_TEST
        )
        self.category6 = Category.objects.create(
            category_title='title6',
            user=self.user,
            category_type='INCOME'
        )
        self.category7 = Category.objects.create(
            category_title='title7',
            user=self.user,
            category_type='EXPENSE'
        )
        self.category8 = Category.objects.create(
            category_title='title8',
            user=self.other_user,
            category_type='EXPENSE'
        )
        self.not_saved_category = Category(
            category_title='not_saved',
            user=self.user,
            category_type='EXPENSE'
        )

    def test_user_auth_can_get_one_item_of_category(self):
        token = UtilCategory.get_jwt_token(
            self.client, EMAIL_TEST, PASSWORD_TEST)
        self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + token)
        response_category6 = self.client.generic(
            method="GET",
            path=API_CATEGORY_ITEM+str(self.category6.category_id) + "/",
            content_type='application/json'
        )
        self.assertEqual(200, response_category6.status_code)
        json_category_item = json.loads(
            response_category6.content).get("category_title")
        self.assertEqual(json_category_item, self.category6.category_title)

    def test_user_not_auth_cannot_get_one_item_of_category(self):
        response_category6 = self.client.generic(
            method="GET",
            path=API_CATEGORY_ITEM+str(self.category6.category_id) + "/",
            content_type='application/json'
        )
        self.assertEqual(401, response_category6.status_code)

    def test_user_auth_cannot_get_other_user_category(self):
        token = UtilCategory.get_jwt_token(
            self.client, EMAIL_TEST, PASSWORD_TEST)
        self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + token)
        response_category8 = self.client.generic(
            method="GET",
            path=API_CATEGORY_ITEM+str(self.category8.category_id) + "/",
            content_type='application/json'
        )
        self.assertEqual(404, response_category8.status_code)

    def test_user_auth_can_delete_one_item_of_category(self):
        token = UtilCategory.get_jwt_token(
            self.client, EMAIL_TEST, PASSWORD_TEST)
        self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + token)
        response_category6 = self.client.generic(
            method="DELETE",
            path=API_CATEGORY_ITEM+str(self.category6.category_id) + "/",
            content_type='application/json'
        )
        self.assertEqual(200, response_category6.status_code)

    def test_user_not_auth_cannot_delete_one_item_of_category(self):
        response_category6 = self.client.generic(
            method="DELETE",
            path=API_CATEGORY_ITEM+str(self.category6.category_id) + "/",
            content_type='application/json'
        )
        self.assertEqual(401, response_category6.status_code)

    def test_user_auth_cannot_delete_other_user_category(self):
        token = UtilCategory.get_jwt_token(
            self.client, EMAIL_TEST, PASSWORD_TEST)
        self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + token)
        response_category8 = self.client.generic(
            method="DELETE",
            path=API_CATEGORY_ITEM+str(self.category8.category_id) + "/",
            content_type='application/json'
        )
        self.assertEqual(404, response_category8.status_code)

    def test_user_auth_can_put_one_item_of_category(self):
        category6_id = str(self.category6.category_id)
        token = UtilCategory.get_jwt_token(
            self.client, EMAIL_TEST, PASSWORD_TEST)
        self.basic_client.defaults["HTTP_AUTHORIZATION"] = 'Bearer ' + token
        data = {
            "category_title": "test_put",
            "category_type": "INCOME"
        }
        response_category = self.basic_client.put(
            API_CATEGORY_ITEM + category6_id + "/",
            data,
            content_type="application/json"
        )
        self.assertEqual(200, response_category.status_code)

        json_category_item = json.loads(
            response_category.content).get("message")
        self.assertEqual(json_category_item, "success add category")

        get_latest_category6 = Category.objects.get(category_id=category6_id)
        self.assertEqual(get_latest_category6.category_title, "test_put")

    def test_user_not_auth_cannot_put_one_item_of_category(self):
        category6_id = str(self.category6.category_id)
        data = {
            "category_title": "tester",
            "category_type": "INCOME"
        }
        response_category = self.basic_client.put(
            API_CATEGORY_ITEM + category6_id + "/",
            data,
            content_type="application/json"
        )
        self.assertEqual(401, response_category.status_code)

        get_latest_category6 = Category.objects.get(category_id=category6_id)
        self.assertNotEqual(get_latest_category6.category_title, "tester")

    def test_user_auth_cant_put_one_category_if_title_exist_for_user(self):
        category6_id = str(self.category6.category_id)
        category7_title = self.category7.category_title
        token = UtilCategory.get_jwt_token(
            self.client, EMAIL_TEST, PASSWORD_TEST)
        self.basic_client.defaults["HTTP_AUTHORIZATION"] = 'Bearer ' + token
        data = {
            "category_title": category7_title,
            "category_type": "INCOME"
        }
        response_category = self.basic_client.put(
            API_CATEGORY_ITEM + category6_id + "/",
            data,
            content_type="application/json"
        )
        self.assertEqual(400, response_category.status_code)
        json_category_item = json.loads(
            response_category.content).get("detail")
        self.assertIn("UNIQUE constraint", json_category_item)

    def test_user_auth_cant_put_one_category_if_type_not_income_or_expense(
        self
    ):
        category6_id = str(self.category6.category_id)
        token = UtilCategory.get_jwt_token(
            self.client, EMAIL_TEST, PASSWORD_TEST)
        self.basic_client.defaults["HTTP_AUTHORIZATION"] = 'Bearer ' + token
        data = {
            "category_title": "error type",
            "category_type": "ADD"
        }
        response_category = self.basic_client.put(
            API_CATEGORY_ITEM + category6_id + "/",
            data,
            content_type="application/json"
        )
        self.assertEqual(400, response_category.status_code)
        json_category_item = json.loads(
            response_category.content).get("category_type")
        self.assertIn("not a valid choice", json_category_item[0])

        get_latest_category6 = Category.objects.get(category_id=category6_id)
        self.assertNotEqual(get_latest_category6.category_title, "error type")

    def test_user_auth_can_put_one_category_if_title_exist_for_other_user(
        self
    ):
        category6_id = str(self.category6.category_id)
        token = UtilCategory.get_jwt_token(
            self.client, EMAIL_TEST, PASSWORD_TEST)
        self.basic_client.defaults["HTTP_AUTHORIZATION"] = 'Bearer ' + token
        data = {
            "category_title": self.category8.category_title,
            "category_type": self.category8.category_type
        }
        response_category = self.basic_client.put(
            API_CATEGORY_ITEM + category6_id + "/",
            data,
            content_type="application/json"
        )
        self.assertEqual(200, response_category.status_code)
        json_category_item = json.loads(
            response_category.content).get("message")
        self.assertEqual(json_category_item, "success add category")

        get_latest_category6 = Category.objects.get(category_id=category6_id)
        self.assertEqual(get_latest_category6.category_title,
                         self.category8.category_title)
Пример #5
0
class CommonTests(APITestCase):
    def __init__(self, **kwargs):
        super().__init__()
        self.common_client = APIClient(enforce_csrf_checks=True)
        self.predicted_msg = {
            'authorization':
            'Authentication credentials were not provided.',
            'invalid_token_header':
            'Invalid token header',
            'not_found':
            'Not found.',
            'account_suspended':
            'Your account is suspended. Please contact admin.',
            'no_token':
            'Invalid input. Only `Token` tag is allowed.',
            'blank_field':
            'This field may not be blank.',
            'empty_token':
            'Invalid token header. No credentials provided.',
            'not_allowed':
            'Method "{}" not allowed.'.format(kwargs.get('request_type', None))
        }
        self.http_response = {
            '403': status.HTTP_403_FORBIDDEN,
            '404': status.HTTP_404_NOT_FOUND,
            '405': status.HTTP_405_METHOD_NOT_ALLOWED
        }
        self.token = kwargs.get('token', None)
        self.url = kwargs.get('url', None)

    def invalid_request_with_error_msg(self, **kwargs):
        _predicted_msg = kwargs.get('predicted_msg', None)
        _request_type = kwargs.get('request_type', None)
        _data = kwargs.get('data', None)
        _response_check_tag = kwargs.get('response_tag', None)
        _http_response = kwargs.get('http_response', None)

        # Adding not allowed msg in predicted_msg dict.
        self.predicted_msg['not_allowed'] = 'Method "{}" not allowed.'.format(
            _request_type.upper())

        # generic requests with and without tokens
        response_without_token = self.common_client.generic(
            method=_request_type,
            path=self.url,
            data=_data,
            content_type='json')
        self.common_client.credentials(HTTP_AUTHORIZATION='Token ' +
                                       self.token.decode('utf-8'))
        response_with_token = self.common_client.generic(method=_request_type,
                                                         path=self.url,
                                                         data=_data,
                                                         content_type='json')
        self.assertEqual(response_with_token.status_code,
                         self.http_response[_http_response])
        self.assertEqual(response_without_token.status_code,
                         self.http_response[_http_response])
        self.assertEqual(response_with_token.data[_response_check_tag],
                         self.predicted_msg[_predicted_msg])
        self.assertEqual(response_without_token.data[_response_check_tag],
                         self.predicted_msg[_predicted_msg])
        return True

    def request_with_empty_token(self, **kwargs):
        _predicted_msg = kwargs.get('predicted_msg', None)
        _request_type = kwargs.get('request_type', None)
        _data = kwargs.get('data', None)
        _response_check_tag = kwargs.get('response_tag', None)
        self.common_client.credentials(HTTP_AUTHORIZATION='Token ' + '')
        response_with_token = self.common_client.generic(method=_request_type,
                                                         path=self.url,
                                                         data=_data,
                                                         content_type='json')
        self.assertEqual(response_with_token.status_code,
                         status.HTTP_403_FORBIDDEN)
        self.assertEqual(response_with_token.data[_response_check_tag],
                         self.predicted_msg[_predicted_msg])
        return True

    def invalid_token_header(self, **kwargs):
        _predicted_msg = kwargs.get('predicted_msg', None)
        _request_type = kwargs.get('request_type', None)
        _data = kwargs.get('data', None)
        _response_check_tag = kwargs.get('response_tag', None)
        self.common_client.credentials(HTTP_AUTHORIZATION='Token ' +
                                       ' get request with valid token')
        response_with_token = self.common_client.generic(method=_request_type,
                                                         path=self.url,
                                                         data=_data,
                                                         content_type='json')
        self.assertEqual(response_with_token.status_code,
                         status.HTTP_403_FORBIDDEN)
        self.assertEqual(response_with_token.data[_response_check_tag],
                         self.predicted_msg[_predicted_msg])
        return True

    def request_without_token(self, **kwargs):
        _predicted_msg = kwargs.get('predicted_msg', None)
        _request_type = kwargs.get('request_type', None)
        _data = kwargs.get('data', None)
        _response_check_tag = kwargs.get('response_tag', None)
        response_with_token = self.common_client.generic(method=_request_type,
                                                         path=self.url,
                                                         data=_data,
                                                         content_type='json')
        self.assertEqual(response_with_token.status_code,
                         status.HTTP_403_FORBIDDEN)
        self.assertEqual(response_with_token.data[_response_check_tag],
                         self.predicted_msg[_predicted_msg])
        return True
Пример #6
0
class TestMovieView(TestCase):
    def setUp(self):
        self.client = APIClient()

        self.user_data = {
            "username": "******",
            "first_name": "Edward",
            "last_name": "Stewart",
            "password": "******",
            "is_staff": False,
            "is_superuser": False,
        }

        self.user_login_data = {"username": "******", "password": "******"}

        self.critic_data = {
            "username": "******",
            "first_name": "Erick",
            "last_name": "Jacquin",
            "password": "******",
            "is_staff": True,
            "is_superuser": False,
        }

        self.critic_login_data = {"username": "******", "password": "******"}

        self.admin_data = {
            "username": "******",
            "first_name": "Jeff",
            "last_name": "Bezos",
            "password": "******",
            "is_staff": True,
            "is_superuser": True,
        }

        self.admin_login_data = {"username": "******", "password": "******"}

        self.movie_data = {
            "title":
            "O Poderoso Chefão",
            "duration":
            "175m",
            "genres": [{
                "name": "Crime"
            }, {
                "name": "Drama"
            }],
            "launch":
            "1972-09-10",
            "classification":
            14,
            "synopsis":
            "Don Vito Corleone (Marlon Brando) é o chefe de uma 'família' de Nova York que está feliz, pois Connie (Talia Shire), sua filha,se casou com Carlo (Gianni Russo). Por ser seu padrinho Vito foi procurar o líder da banda e ofereceu 10 mil dólares para deixar Johnny sair, mas teve o pedido recusado.",
        }

        self.movie_data_2 = {
            "title":
            "Um Sonho de liberdade",
            "duration":
            "142m",
            "genres": [{
                "name": "Ficção Científica"
            }, {
                "name": "Drama"
            }],
            "launch":
            "1994-10-14",
            "classification":
            14,
            "synopsis":
            "Andy Dufresne é condenado a duas prisões perpétuas consecutivas pelas mortes de sua esposa e de seu amante. Porém, só Andy sabe que ele não cometeu os crimes. No presídio, durante dezenove anos, ele faz amizade com Red, sofre as brutalidades da vida na cadeia, se adapta, ajuda os carcereiros, etc.",
        }

        self.movie_data_3 = {
            "title":
            "Em busca de liberdade",
            "duration":
            "175m",
            "genres": [{
                "name": "Obra de época"
            }, {
                "name": "Drama"
            }],
            "launch":
            "2018-02-22",
            "classification":
            14,
            "synopsis":
            "Representando a Grã-Bretanha,  corredor Eric Liddell (Joseph Fiennes) ganha uma medalha de ouro nas Olimpíadas de Paris em 1924. Ele decide ir até a China para trabalhar como missionário e acaba encontrando um país em guerra. Com a invasão japonesa no território chinês durante a Segunda Guerra Mundial, Liddell acaba em um campo de concentração.",
        }

    def test_admin_can_create_movie(self):
        # create admin user
        self.client.post("/api/accounts/", self.admin_data, format="json")

        # login
        token = self.client.post("/api/login/",
                                 self.admin_login_data,
                                 format="json").json()["token"]

        self.client.credentials(HTTP_AUTHORIZATION="Token " + token)

        # create movie
        movie = self.client.post("/api/movies/",
                                 self.movie_data,
                                 format="json")
        self.assertEqual(movie.json()["id"], 1)
        self.assertEqual(movie.status_code, 201)

    def test_critic_or_user_cannot_create_movie(self):
        # create critic user
        self.client.post("/api/accounts/", self.critic_data, format="json")

        # login
        token = self.client.post("/api/login/",
                                 self.critic_login_data,
                                 format="json").json()["token"]

        self.client.credentials(HTTP_AUTHORIZATION="Token " + token)

        # critic cannot create movie
        status_code = self.client.post("/api/movies/",
                                       self.movie_data,
                                       format="json").status_code
        self.assertEqual(status_code, 403)

        # create user
        self.client.post("/api/accounts/", self.user_data, format="json")

        # login
        token = self.client.post("/api/login/",
                                 self.user_login_data,
                                 format="json").json()["token"]

        self.client.credentials(HTTP_AUTHORIZATION="Token " + token)

        # user cannot create movie
        status_code = self.client.post("/api/movies/",
                                       self.movie_data,
                                       format="json").status_code

        self.assertEqual(status_code, 403)

    def anonymous_can_list_movies(self):
        # create admin user
        self.client.post("/api/accounts/", self.admin_data, format="json")

        # login
        token = self.client.post("/api/login/",
                                 self.admin_login_data,
                                 format="json").json()["token"]

        self.client.credentials(HTTP_AUTHORIZATION="Token " + token)

        # create movie
        movie = self.client.post("/api/movies/",
                                 self.movie_data,
                                 format="json")

        # reset client -> no login
        client = APIClient()

        # list movies
        movies_list = client.get("/api/movies/", format="json").json()
        self.assertEqual(len(movies_list), 1)

    def test_genre_or_classification_cannot_repet(self):
        # create admin user
        self.client.post("/api/accounts/", self.admin_data, format="json")

        # login
        token = self.client.post("/api/login/",
                                 self.admin_login_data,
                                 format="json").json()["token"]

        self.client.credentials(HTTP_AUTHORIZATION="Token " + token)

        # create movie 1
        movie_1 = self.client.post("/api/movies/",
                                   self.movie_data,
                                   format="json").json()

        # create movie 2
        movie_2 = self.client.post("/api/movies/",
                                   self.movie_data_2,
                                   format="json").json()
        # testa se os ids do gênero drama são os mesmos
        self.assertEqual(movie_1["genres"][1]["id"],
                         movie_2["genres"][0]["id"])

    def test_filter_movies_with_the_filter_request(self):
        # create admin user
        self.client.post("/api/accounts/", self.admin_data, format="json")

        # login
        token = self.client.post("/api/login/",
                                 self.admin_login_data,
                                 format="json").json()["token"]

        self.client.credentials(HTTP_AUTHORIZATION="Token " + token)

        # create movie 1
        movie_1 = self.client.post("/api/movies/",
                                   self.movie_data,
                                   format="json").json()

        # create movie 2
        movie_2 = self.client.post("/api/movies/",
                                   self.movie_data_2,
                                   format="json").json()

        # create movie 3
        movie_2 = self.client.post("/api/movies/",
                                   self.movie_data_3,
                                   format="json").json()

        # filter movies
        filter_movies = self.client.generic(
            method="GET",
            path="/api/movies/",
            data=json.dumps({"title": "liberdade"}),
            content_type="application/json",
        )

        self.assertEqual(len(filter_movies.json()), 2)
        self.assertEqual(filter_movies.status_code, 200)

    def test_output_format_data(self):
        # create admin user
        self.client.post("/api/accounts/", self.admin_data, format="json")

        # login
        token = self.client.post("/api/login/",
                                 self.admin_login_data,
                                 format="json").json()["token"]

        self.client.credentials(HTTP_AUTHORIZATION="Token " + token)

        # create movie 1
        movie_1 = self.client.post("/api/movies/",
                                   self.movie_data,
                                   format="json").json()

        output_format_movie_data = {
            "id": 1,
            "title": "O Poderoso Chefão",
            "duration": "175m",
            "genres": [{
                "id": 1,
                "name": "Crime"
            }, {
                "id": 2,
                "name": "Drama"
            }],
            "launch": "1972-09-10",
            "classification": 14,
            "synopsis":
            "Don Vito Corleone (Marlon Brando) é o chefe de uma 'família' de Nova York que está feliz, pois Connie (Talia Shire), sua filha,se casou com Carlo (Gianni Russo). Por ser seu padrinho Vito foi procurar o líder da banda e ofereceu 10 mil dólares para deixar Johnny sair, mas teve o pedido recusado.",
            "criticism_set": [],
            "comment_set": [],
        }

        self.assertEqual(movie_1, output_format_movie_data)
Пример #7
0
class TestViews(APITestCase):
    def setUp(self):
        self.client = APIClient()
        """Define url"""
        self.login_url = reverse('login')
        self.leaderboard_url = reverse('leaderboard')
        self.students_url = reverse('students')
        self.questions_url = reverse('questions')
        self.questions_submit_url = reverse('questions_submit')
        self.create_questions_url = reverse('create-questions')
        self.game_summary_url = reverse('gameSummary')
        """create a user"""
        self.credentials = {
            'email': '*****@*****.**',
            'password': '******',
            'name': 'testuser',
        }
        self.user = User.objects.create_user(**self.credentials)
        """create World"""
        world1 = World.objects.create(name="1")
        world2 = World.objects.create(name="2")
        """create section"""
        section1 = Section.objects.create(name="1")
        section2 = Section.objects.create(name="2")
        """create questions"""
        question1 = Questions_teacher.objects.create(questionBody="1+1 = ?",
                                                     worldID=world1,
                                                     sectionID=section1,
                                                     role="frontend",
                                                     questionLevel=1)
        """ create question answers for the question"""
        Questions_answer.objects.create(questionID=question1,
                                        questionText="1",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question1,
                                        questionText="2",
                                        isCorrect=True)
        Questions_answer.objects.create(questionID=question1,
                                        questionText="3",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question1,
                                        questionText="4",
                                        isCorrect=False)

        self.question = question1
        """create questions"""
        question2 = Questions_teacher.objects.create(questionBody="2+2 = ?",
                                                     worldID=world1,
                                                     sectionID=section1,
                                                     role="frontend",
                                                     questionLevel=1)
        """ create question answers for the question"""
        Questions_answer.objects.create(questionID=question2,
                                        questionText="1",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question2,
                                        questionText="2",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question2,
                                        questionText="3",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question2,
                                        questionText="4",
                                        isCorrect=True)
        """create question History for the questions"""
        questionHistory.objects.create(worldID=question2.worldID,
                                       sectionID=question2.sectionID,
                                       questionID=question2,
                                       studentID=self.user,
                                       isAnsweredCorrect=True,
                                       studentAnswer='4')
        """ create a question """
        question3 = Questions_teacher.objects.create(questionBody="1*1 = ?",
                                                     worldID=world1,
                                                     sectionID=section2,
                                                     role="frontend",
                                                     questionLevel=1)
        """ create question answer for question """
        Questions_answer.objects.create(questionID=question3,
                                        questionText="1",
                                        isCorrect=True)
        Questions_answer.objects.create(questionID=question3,
                                        questionText="2",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question3,
                                        questionText="3",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question3,
                                        questionText="4",
                                        isCorrect=False)
        """ create question History for question"""
        questionHistory.objects.create(worldID=question3.worldID,
                                       sectionID=question3.sectionID,
                                       questionID=question3,
                                       studentID=self.user,
                                       isAnsweredCorrect=False,
                                       studentAnswer='4')
        """ create a question """
        question4 = Questions_teacher.objects.create(questionBody="2*2 = ?",
                                                     worldID=world1,
                                                     sectionID=section2,
                                                     role="frontend",
                                                     questionLevel=1)
        """ create question answer for question """
        Questions_answer.objects.create(questionID=question4,
                                        questionText="1",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question4,
                                        questionText="2",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question4,
                                        questionText="3",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question4,
                                        questionText="4",
                                        isCorrect=True)
        """ create question history for the question """
        questionHistory.objects.create(worldID=question4.worldID,
                                       sectionID=question4.sectionID,
                                       questionID=question4,
                                       studentID=self.user,
                                       isAnsweredCorrect=True,
                                       studentAnswer='4')
        """ create question """
        question5 = Questions_teacher.objects.create(questionBody="10+10 = ?",
                                                     worldID=world1,
                                                     sectionID=section1,
                                                     role="frontend",
                                                     questionLevel=2)
        """ create question answer for question"""
        Questions_answer.objects.create(questionID=question5,
                                        questionText="10",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question5,
                                        questionText="20",
                                        isCorrect=True)
        Questions_answer.objects.create(questionID=question5,
                                        questionText="30",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question5,
                                        questionText="40",
                                        isCorrect=False)
        """ create question history for question"""
        questionHistory.objects.create(worldID=question5.worldID,
                                       sectionID=question5.sectionID,
                                       questionID=question5,
                                       studentID=self.user,
                                       isAnsweredCorrect=False,
                                       studentAnswer='40')
        """ create question """
        question6 = Questions_teacher.objects.create(questionBody="10+20 = ?",
                                                     worldID=world1,
                                                     sectionID=section1,
                                                     role="frontend",
                                                     questionLevel=2)
        """ create question answer for question """
        Questions_answer.objects.create(questionID=question6,
                                        questionText="10",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question6,
                                        questionText="20",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question6,
                                        questionText="30",
                                        isCorrect=True)
        Questions_answer.objects.create(questionID=question6,
                                        questionText="40",
                                        isCorrect=False)
        """ create question history for question"""
        questionHistory.objects.create(worldID=question6.worldID,
                                       sectionID=question6.sectionID,
                                       questionID=question6,
                                       studentID=self.user,
                                       isAnsweredCorrect=True,
                                       studentAnswer='30')
        """ create question """
        question7 = Questions_teacher.objects.create(questionBody="10*10 = ?",
                                                     worldID=world1,
                                                     sectionID=section2,
                                                     role="frontend",
                                                     questionLevel=2)
        """ create question answer for question"""
        Questions_answer.objects.create(questionID=question7,
                                        questionText="100",
                                        isCorrect=True)
        Questions_answer.objects.create(questionID=question7,
                                        questionText="200",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question7,
                                        questionText="300",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question7,
                                        questionText="400",
                                        isCorrect=False)
        """ create question history for question"""
        questionHistory.objects.create(worldID=question7.worldID,
                                       sectionID=question7.sectionID,
                                       questionID=question7,
                                       studentID=self.user,
                                       isAnsweredCorrect=True,
                                       studentAnswer='100')
        """ create question """
        question8 = Questions_teacher.objects.create(questionBody="20*10 = ?",
                                                     worldID=world1,
                                                     sectionID=section1,
                                                     role="frontend",
                                                     questionLevel=2)
        """ create question answer for question"""
        Questions_answer.objects.create(questionID=question8,
                                        questionText="100",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question8,
                                        questionText="200",
                                        isCorrect=True)
        Questions_answer.objects.create(questionID=question8,
                                        questionText="300",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question8,
                                        questionText="400",
                                        isCorrect=False)
        """ create question histroy for question"""
        questionHistory.objects.create(worldID=question8.worldID,
                                       sectionID=question8.sectionID,
                                       questionID=question8,
                                       studentID=self.user,
                                       isAnsweredCorrect=True,
                                       studentAnswer='200')
        """ create question """
        question9 = Questions_teacher.objects.create(questionBody=" x + y = ?",
                                                     worldID=world2,
                                                     sectionID=section1,
                                                     role="frontend",
                                                     questionLevel=1)
        """ create question answer for question """
        Questions_answer.objects.create(questionID=question9,
                                        questionText="x",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question9,
                                        questionText="x+y",
                                        isCorrect=True)
        Questions_answer.objects.create(questionID=question9,
                                        questionText="y",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question9,
                                        questionText="y",
                                        isCorrect=False)
        """ create question history for question """
        questionHistory.objects.create(worldID=question9.worldID,
                                       sectionID=question9.sectionID,
                                       questionID=question9,
                                       studentID=self.user,
                                       isAnsweredCorrect=False,
                                       studentAnswer='x')
        """ create question"""
        question10 = Questions_teacher.objects.create(questionBody="y+x = ?",
                                                      worldID=world2,
                                                      sectionID=section1,
                                                      role="frontend",
                                                      questionLevel=2)
        """ create question answer """

        Questions_answer.objects.create(questionID=question10,
                                        questionText="x",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question10,
                                        questionText="x+y",
                                        isCorrect=True)
        Questions_answer.objects.create(questionID=question10,
                                        questionText="y",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question10,
                                        questionText="x",
                                        isCorrect=False)
        """ create question history for question """
        questionHistory.objects.create(worldID=question10.worldID,
                                       sectionID=question10.sectionID,
                                       questionID=question10,
                                       studentID=self.user,
                                       isAnsweredCorrect=False,
                                       studentAnswer='x')

    def test_user_login_with_no_data(self):
        """test user login with no input is not successful """
        res = self.client.post(self.login_url)
        self.assertEqual(res.status_code, 401)

    def test_user_login_with_correct_data(self):
        """ test user login with correct username/password is succsessful"""
        res = self.client.post(self.login_url, self.credentials, format='json')
        token, created = Token.objects.get_or_create(user=self.user)
        res_data = json.loads(res.content)
        self.assertEqual(
            res_data,
            {
                'user': StudentAccountSerializer(self.user).data,
                'token': token.key
            },
        )
        self.assertEqual(res.status_code, 200)

    def test_user_login_with_wrong_data(self):
        """ test user login with incorect username/password is not successful"""
        res = self.client.post(self.login_url, {
            'email': '*****@*****.**',
            'password': '******'
        },
                               format='json')
        self.assertEqual(res.status_code, 401)

    def test_get_student_withoutQuery(self):
        """ test get student list is successful"""
        self.client.force_authenticate(user=self.user)
        res = self.client.get(self.students_url)
        res_data = json.loads(res.content)

        students = User.objects.filter(is_staff=False)

        self.assertEqual(res.status_code, 200)
        self.assertEqual(res_data,
                         StudentAccountSerializer(students, many=True).data)

    def test_get_student_withQuery(self):
        """ test get student data with id is successful"""
        self.client.force_authenticate(user=self.user)
        res = self.client.get(self.students_url, {'id': self.user.id},
                              content_type='application/json')
        res_data = json.loads(res.content)

        student = User.objects.get(id=self.user.id)

        self.assertEqual(res.status_code, 200)
        self.assertEqual(res_data, StudentAccountSerializer(student).data)

    def test_get_leaderboard(self):
        """ test get student data to display leader is successful """
        self.client.force_authenticate(user=self.user)
        res = self.client.get(self.leaderboard_url)
        res_data = json.loads(res.content)
        user = User.objects.filter(is_staff=False)
        self.assertEqual(res_data, LeaderBoardSerializer(user, many=True).data)
        self.assertEqual(res.status_code, 200)

    def test_post_question_list_withoutQuery(self):
        """ test get question without data is unsccessful """
        self.client.force_authenticate(user=self.user)
        #res = self.client.get(self.questions_url)
        res = self.client.post(self.questions_url)
        res_data = json.loads(res.content)
        self.assertEqual(res.status_code, 400)

    def test_post_question_list_withQuery(self):
        """ test get question with corect data input is successful """
        self.client.force_authenticate(user=self.user)
        data = {"world": "1", "section": "1", "role": "2", "questionLevel": 1}
        #res = self.client.generic(method="GET", path=self.questions_url, data=json.dumps(
        #    data), content_type='application/json')
        res = self.client.post(self.questions_url, data=data, format='json')
        res_data = json.loads(res.content)

        world = World.objects.get(name='1')
        section = Section.objects.get(name='1')
        questions = Questions_teacher.objects.filter(
            worldID=world, sectionID=section, role='frontend',
            questionLevel=1).order_by('?')[:5]

        self.assertEqual(res.status_code, 200)
        self.assertEqual(res_data,
                         QuestionTeacherSerializer(questions, many=True).data)

    # Post Question Answer
    def test_post_questionAns(self):
        """ test post question answer with data is successful """
        self.client.force_authenticate(user=self.user)
        data = {
            'world': self.question.worldID.name,
            'section': self.question.sectionID.name,
            'questionID': self.question.id,
            'studentID': self.user.id,
            'studentAnswer': '2',
            'isAnsweredCorrect': True,
            'pointGain': 1
        }
        res = self.client.post(self.questions_submit_url,
                               data=data,
                               format='json')
        res_data = json.loads(res.content)

        self.assertEqual(res_data, {'pass': True})
        self.assertEqual(res.status_code, 201)

    def test_post_questionAns_Without_Data(self):
        """ test post question answer without data is unsuccessful"""
        self.client.force_authenticate(user=self.user)
        res = self.client.post(self.questions_submit_url)
        res_data = json.loads(res.content)

        self.assertEqual(res_data, {'pass': False})
        self.assertEqual(res.status_code, 400)

    # Student Post new Question
    def test_post_create_StudentQuestion_Without_Data(self):
        """ test post create new question by student without data is unsucessful """
        self.client.force_authenticate(user=self.user)
        res = self.client.post(self.create_questions_url)
        res_data = json.loads(res.content)

        self.assertEqual(res_data, {'submitted': False})
        self.assertEqual(res.status_code, 400)

    def test_post_create_StudentQuestion_With_Data(self):
        """ test post create new question by student with correct data is successful """
        self.client.force_authenticate(user=self.user)
        data = {
            'Proposer':
            '*****@*****.**',
            'questionBody':
            '10*10 = ?',
            'questionAns': [{
                'questionText': '1',
                'isCorrect': False
            }, {
                'questionText': '10',
                'isCorrect': False
            }, {
                'questionText': '10',
                'isCorrect': False
            }, {
                'questionText': '100',
                'isCorrect': True
            }]
        }
        res = self.client.post(self.create_questions_url,
                               data=data,
                               format='json')
        res_data = json.loads(res.content)

        self.assertEqual(res_data, {'submitted': True})
        self.assertEqual(res.status_code, 201)

    def test_get_game_summary(self):
        """ test get game summary based on correct username is successful """
        self.client.force_authenticate(user=self.user)
        data = {'email': self.user.email}
        res = self.client.generic(method="GET",
                                  path=self.game_summary_url,
                                  data=json.dumps(data),
                                  content_type='application/json')
        res_data = json.loads(res.content)
        student = User.objects.get(email=self.user.email)
        self.assertEqual(res_data, gameSummarySerializer(student).data)
        self.assertEqual(res.status_code, 200)

    def test_game_summary_with_no_input(self):
        """ test get game summary based on no input is successful """
        self.client.force_authenticate(user=self.user)
        res = self.client.generic(method="GET",
                                  path=self.game_summary_url,
                                  content_type='application/json')
        res_data = json.loads(res.content)
        self.assertEqual(res_data, {'Error Message': 'record not found'})
        self.assertEqual(res.status_code, 400)