def test_auto_loading_generator(self):
        session = requests.Session()
        session.auth = Auth(self.base_url, self.client_id, self.secret,
                            self.username, self.password)
        session.headers.update({'Content-Type': 'application/json'})
        pool = BasicResourcePool(
            urljoin(self.base_url, '/api/rest/v1/', 'products/'), session)
        c = pool.fetch_list()

        self.assertEqual(len(c._items), 10)
        i = 0
        generator = c
        previousLink = generator.get_self_link()
        for item in generator:
            i += 1
            self.assertNotEqual(generator.get_self_link(),
                                generator.get_next_link())
            if i + 5 % 10 == 0:
                self.assertNotEqual(generator.get_self_link(), previousLink)
                previousLink = generator.get_self_link()
            if i == 25:
                break
        # check that it iterated over 25 elements, but did not store them:
        self.assertEqual(len(c._items), 10)
        self.assertEqual(i, 25)
    def test_auto_loading(self):
        session = requests.Session()
        session.auth = Auth(self.base_url, self.client_id, self.secret,
                            self.username, self.password)
        session.headers.update({'Content-Type': 'application/json'})
        pool = BasicResourcePool(
            urljoin(self.base_url, '/api/rest/v1/', 'products/'), session)

        c = pool.fetch_list()
        firstElement = c.get_page_items()[0]
        self.assertEqual(len(c.get_page_items()), 10)
        for i in range(12):
            next(c)
        eleventhElement = c.get_page_items()[0]
        self.assertNotEqual(eleventhElement["identifier"],
                            firstElement["identifier"])
        self.assertEqual(len(c.get_page_items()), 10)
        for i in range(12):
            next(c)
        twentyonethElement = c.get_page_items()[0]
        self.assertNotEqual(twentyonethElement["identifier"],
                            firstElement["identifier"])
        self.assertNotEqual(twentyonethElement["identifier"],
                            eleventhElement["identifier"])
        self.assertEqual(len(c.get_page_items()), 10)
예제 #3
0
    def _request_a_token(self, grant_type="password"):
        """Requests a token. Throws in case of error"""
        authorization = "Basic {0}".format(
            base64.b64encode("{0}:{1}".format(
                self._client_id,
                self._secret).encode('ascii')).decode('utf-8'))
        headers = {
            'Content-Type': 'application/json',
            'Authorization': authorization
        }
        if grant_type == 'password':
            data = json.dumps({
                'grant_type': "password",
                'username': self._username,
                'password': self._password
            })
        elif grant_type == 'refresh_token':
            data = json.dumps({
                "grant_type": "refresh_token",
                "refresh_token": self._refresh_token
            })
        else:
            raise ValueError('grant_type parameter is expected to be either ' +
                             '"password" or "refresh_token". {0} provided'.
                             format(grant_type))
        logger.debug(data)
        url = urljoin(self._base_url, self.TOKEN_PATH)
        r = requests.post(url, data=data, headers=headers)
        if r.status_code != 200:
            raise requests.HTTPError("Status code: {0}".format(r.status_code))

        try:
            json_data = json.loads(r.text)
        except json.decoder.JSONDecodeError as e:
            raise SyntaxError(
                "The server did not return expected json: {0}".format(r.text))
        logger.debug(r.status_code)
        logger.debug(r.encoding)
        logger.debug(json.dumps(json_data, indent=4, sort_keys=True))
        try:
            self._token = json_data['access_token']
            self._refresh_token = json_data['refresh_token']
        except KeyError as e:
            raise SyntaxError(
                "The server did not return expected tokens: {0}".format(
                    json_data))

        try:
            self._expiry_date = time() + float(json_data['expires_in'])
        except KeyError as e:
            self._expiry_date = None
        except ValueError as e:
            raise SyntaxError(
                "The server did not return a valid expires_in: {0}".format(
                    json_data))
        logger.debug(self.authorization)
        logger.debug(self._refresh_token)
        logger.debug(self._expiry_date)
예제 #4
0
 def test_query_products_with_auth(self):
     auth = Auth(self.base_url, self.client_id, self.secret, self.username,
                 self.password)
     r = requests.get(urljoin(self.base_url, "/api/rest/v1/products"),
                      auth=auth)
     logger.debug(r)
     logger.debug(r.status_code)
     json_data = json.loads(r.text)
     logger.debug(json.dumps(json_data, indent=4, sort_keys=True))
 def test_create_delete_from_json(self):
     session = requests.Session()
     session.auth = Auth(self.base_url, self.client_id, self.secret,
                         self.username, self.password)
     session.headers.update({'Content-Type': 'application/json'})
     pool = BasicResourcePool(
         urljoin(self.base_url, '/api/rest/v1/', 'products/'), session)
     pool.create_item(json.loads(self.valid_product))
     pool.delete_item('myawesometshirt')
 def test_get_invalide_item(self):
     session = requests.Session()
     session.auth = Auth(self.base_url, self.client_id, self.secret,
                         self.username, self.password)
     session.headers.update({'Content-Type': 'application/json'})
     pool = BasicResourcePool(
         urljoin(self.base_url, '/api/rest/v1/', 'products/'), session)
     with self.assertRaises(requests.HTTPError):
         item = pool.fetch_item('1111111137asdfsdfgsdf')
 def test_create_delete_from_real_element(self):
     session = requests.Session()
     session.auth = Auth(self.base_url, self.client_id, self.secret,
                         self.username, self.password)
     session.headers.update({'Content-Type': 'application/json'})
     if False:
         session.auth._request_a_token()
         pool = BasicResourcePool(
             urljoin('http://localhost:8088', '/api/rest/v1/', 'products/'),
             session)
     else:
         pool = BasicResourcePool(
             urljoin(self.base_url, '/api/rest/v1/', 'products/'), session)
     initialItem = pool.fetch_item('Biker-jacket-polyester-xl')
     item = copy.deepcopy(initialItem)
     item['identifier'] = 'myawesometshirt'
     item['values']['ean'][0]['data'] = '1234567946367'
     item['values']['size'][0]['data'] = 'XS'
     pool.create_item(item)
     pool.delete_item('myawesometshirt')
 def test_fetch_item(self):
     session = requests.Session()
     session.auth = Auth(self.base_url, self.client_id, self.secret,
                         self.username, self.password)
     session.headers.update({'Content-Type': 'application/json'})
     pool = BasicResourcePool(
         urljoin(self.base_url, '/api/rest/v1/', 'products/'), session)
     item = pool.fetch_item('1111111137')
     logger.debug(item)
     self.assertEqual(item['identifier'], '1111111137')
     self.assertEqual(len(item['categories']), 3)
예제 #9
0
 def test_loading_fetch_next_page(self):
     session = requests.Session()
     session.auth = Auth(self.base_url, self.client_id, self.secret,
                         self.username, self.password)
     session.headers.update({'Content-Type': 'application/json'})
     pool = ResourcePool(
         urljoin(self.base_url, '/api/rest/v1/', 'products/'), session)
     c = pool.fetch_list()
     self.assertEqual(len(c._items), 10)
     c.fetch_next_page()
     self.assertEqual(len(c._items), 20)
     c.fetch_next_page()
     self.assertEqual(len(c._items), 30)
예제 #10
0
    def test_auto_loading_generator_ending(self):
        session = requests.Session()
        session.auth = Auth(self.base_url, self.client_id, self.secret,
                            self.username, self.password)
        session.headers.update({'Content-Type': 'application/json'})
        pool = BasicResourcePool(
            urljoin(self.base_url, '/api/rest/v1/', 'families/'), session)
        c = pool.fetch_list()

        self.assertEqual(len(c._items), 10)
        i = 0
        # for item in c.get_generator():
        for item in c:
            i += 1
        # checking that it did not raise any exception when trying to iterate
        # after the last element
        self.assertEqual(len(c._items), 7)
        self.assertEqual(i, 17)