Example #1
0
 def setUp(self):
     self._client = Client()
     self.user_login = '******'
     self.user_password = '******'
     self.office = Office(name='Kyiv1', address='someaddr')
     self.user = None
     self.office.save()
Example #2
0
 def setUpClass(cls):
     super().setUpClass()
     office = Office(name='Kyiv1', address='someaddr')
     office.save()
     floor = Floor(plan='media/floor_image/linux.png',
                   office=office,
                   number=4)
     floor.save()
     room = Room(floor=floor, number='421', coordinates='[]')
     room.save()
     workplace1 = Workplace(
         coordinates=[[[1, 2], [3, 4], [5, 6], [7, 8]]],
         room=room,
         number=5,
         is_occupied=True
     )
     workplace1.save()
     workplace2 = Workplace(
         coordinates=[[[11, 12], [13, 14], [15, 16], [17, 18]]],
         room=room,
         number=666,
         is_occupied=True
     )
     workplace2.save()
Example #3
0
    def setUp(self):
        """
        Initialize data before tests.
        Create variables of office, client, user credentials, url for api,
        path to image and path to temporary directory for ImageField media data.
        Save 'Kyiv1' office to database.
        """
        self._office = Office(pk=1, name='Kyiv1',
                              address='Dehtiarivska St, 33В')
        self._client = Client()
        self._user_login = '******'
        self._user_password = '******'
        self._api_url = '/api/v1/floors/'
        self._img_path = os.path.join(BASE_DIR,
                                      'carcassonne/tests/static/linux.jpg')
        self._tmp_dir_path = os.path.join(BASE_DIR, 'api/tests/tmp_dir')
        self.user = None

        self._office.save()
Example #4
0
class GetOfficesTestCase(TestCase):
    def setUp(self):
        self._client = Client()
        self.user_login = '******'
        self.user_password = '******'
        self.office = Office(name='Kyiv1', address='someaddr')
        self.user = None
        self.office.save()

    def tearDown(self):
        self._client.cookies.clear()
        if self.user is not None:
            self.user.delete()

    def logging(self):
        """Log in user."""
        if self.user is None:
            u = User(username=self.user_login,
                     email='{}@example.com'.format(self.user_login))
            u.set_password('bar')
            u.save()

        auth = {'username': self.user_login, 'password': self.user_password}
        request = self._client.post('/login/', auth)
        self.assertRegex(request.client.session.session_key, r'\w+')

    def test_valid_data(self):
        """Check valid data status_code."""
        self.logging()
        request = self._client.get('/api/v1/offices/')
        self.assertEqual(
            request.status_code, 200,
            msg="Expected code is 200, we got {}, contents:\n{}".format(
                request.status_code, request.content))

    def test_unauthorized(self):
        """Check request from unauthorization users

        The code status must be 302 - redirect to login page"""
        request = self._client.get('/api/v1/offices/')
        self.assertRegex(request.url, r'^http://.*/login/\?.+')
        self.assertEqual(
            request.status_code, 302,
            msg="Expected code is 302, we got {}, contents:\n{}".format(
                request.status_code, request.content))

    def test_unacceptable(self):
        """Check request with incorrect query users

        The code status must be 422"""
        self.logging()
        request = self._client.get('/api/v1/offices/?offFice=Kyiv1')
        self.assertEqual(
            request.status_code, 422,
            msg="Expected code is 422, we got {}, contents:\n{}".format(
                request.status_code, request.content))

    def test_wrong_method(self):
        """Check request with incorrect method

        The code status must be 405"""
        self.logging()
        request = self._client.put('/api/v1/offices/?office=Kyiv1')
        self.assertEqual(
            request.status_code, 405,
            msg="Expected code is 405, we got {}, contents:\n{}".format(
                request.status_code, request.content))

    def test_office_save(self):
        """Test correct POST request.

        Test POST request in case when all the required data is
        provided and Office and Floor instances exist in DB."""
        self.logging()
        json_data = {
            "office": "Test",
            "address": "Test Address",
        }

        response = self._client.post('/api/v1/offices/', json.dumps(json_data),
                                     content_type='application/json')
        self.assertEqual(
            response.status_code, 201,
            msg="Expected code is 201, we got {}, contents:\n{}".format(
                response.status_code, response.content))

        # It will fail if instance was not created in DB
        Office.objects.get(address="Test Address")

    def test_incorrect_json(self):
        """Test request with missing data.

        Test POST request in case when JSON in request body is
        missing one of the required parameters: office or address, or both of them."""
        self.logging()
        json_data = {
            "office": "Kyiv1",
        }

        response = self._client.post('/api/v1/offices/',
                                     json.dumps(json_data),
                                     content_type='application/json')
        self.assertEqual(
            response.status_code, 422,
            msg="Expected code is 422, we got {}, contents:\n{}".format(
                response.status_code, response.content))
Example #5
0
class AddFloorTestCase(TestCase):
    """
    Class for testing add_floor method.
    """

    def setUp(self):
        """
        Initialize data before tests.
        Create variables of office, client, user credentials, url for api,
        path to image and path to temporary directory for ImageField media data.
        Save 'Kyiv1' office to database.
        """
        self._office = Office(pk=1, name='Kyiv1',
                              address='Dehtiarivska St, 33В')
        self._client = Client()
        self._user_login = '******'
        self._user_password = '******'
        self._api_url = '/api/v1/floors/'
        self._img_path = os.path.join(BASE_DIR,
                                      'carcassonne/tests/static/linux.jpg')
        self._tmp_dir_path = os.path.join(BASE_DIR, 'api/tests/tmp_dir')
        self.user = None

        self._office.save()

    def tearDown(self):
        """
        Clear data after tests.
        Clear cookies, delete user object if exists. Remove directory which
        was created by Django to store files form ImageField.
        """
        self._client.cookies.clear()
        if self.user is not None:
            self.user.delete()

        if os.path.exists(self._tmp_dir_path):
            shutil.rmtree(self._tmp_dir_path)

    def logging(self):
        """Log in user."""
        if self.user is None:
            u = User(username=self._user_login,
                     email='{}@example.com'.format(self._user_login))
            u.set_password('bar')
            u.save()

        auth = {'username': self._user_login, 'password': self._user_password}
        request = self._client.post('/login/', auth)
        self.assertRegex(request.client.session.session_key, r'\w+')

    def test_correct_request(self):
        """Check correct post request for authorized user."""
        self.logging()

        with open(self._img_path, 'rb') as f:
            response = self._client.post(self._api_url, {
                'office': 1,
                'number': 2,
                'plan': f
            })

        self.assertEqual(response.status_code, 201,
                         'Response status: {}. Status code should be 201. {}'
                         .format(response.status_code,
                                 response.content.decode('utf-8')))
        self.assertEqual(len(Floor.objects.filter(office_id=1, number=2)), 1)

    def test_unauthorized(self):
        """Check correct response for unauthorized user."""
        response = self._client.post(self._api_url, follow=True)
        self.assertRedirects(response, '/login/?next=%2Fapi%2Fv1%2Ffloors%2F',
                             status_code=302, target_status_code=200)

    def test_wrong_number(self):
        """Check correct response for wrong floor number."""
        self.logging()

        with open(self._img_path, 'rb') as f:
            response = self._client.post(self._api_url, {
                'office': 1,
                'number': 'abc',
                'plan': f
            })

        response_json = json.loads(response.content.decode('utf-8'))
        self.assertEqual(
            response_json['error']['type'],
            'Unprocessable Entity')
        self.assertEqual(
            response_json['error']['message'],
            "Error for field 'number': 'Floor number should be "
            "numerical value.'."
        )
        self.assertEqual(response.status_code, 422)

    def test_wrong_office(self):
        """Check correct response for non-existent office id."""
        self.logging()

        with open(self._img_path, 'rb') as f:
            response = self._client.post(self._api_url, {
                'office': 10,
                'number': 2,
                'plan': f
            })

        response_json = json.loads(response.content.decode('utf-8'))
        self.assertEqual(
            response_json['error']['type'],
            'Unprocessable Entity')
        self.assertEqual(
            response_json['error']['message'],
            "Error for field 'office': 'Specified office does not "
            "exist in database.'."
        )
        self.assertEqual(response.status_code, 422)

    def test_wrong_office_and_floor_number(self):
        """
        Check correct response for non-existent office id and wrong
        floor number.
        """
        self.logging()

        with open(self._img_path, 'rb') as f:
            response = self._client.post(self._api_url, {
                'office': 10,
                'number': 'abc',
                'plan': f
            })

        response_json = json.loads(response.content.decode('utf-8'))
        self.assertEqual(
            response_json['error']['type'],
            'Unprocessable Entity')
        self.assertIn("Error for field 'number': "
                      "'Floor number should be numerical value.'",
                      response_json['error']['message'])
        self.assertIn("Error for field 'office': "
                      "'Specified office does not exist in database.'.",
                      response_json['error']['message'])
        self.assertEqual(response.status_code, 422)

    def test_wrong_method(self):
        """Check correct response for wrong http method."""
        self.logging()
        response = self._client.get(self._api_url)
        self.assertEqual(response.status_code, 405)