Пример #1
0
    def test_get_product_get_image(self, requests_mock):
        response_mock = Mock()
        response_mock.status_code = 200
        response_mock.content = json.dumps({'id': 991, 'name': 'test prod'})
        requests_mock.get.return_value = response_mock
        cli = APIClient('test_api_key', 'test user agent')
        p = ProductResource(cli, '46')


        res = p.get(991)

        self.assertEqual(991, res.id)

        requests_mock.get.assert_called_with(
            url='https://api.tiendanube.com/v1/46/products/991',
            headers={'Authentication': 'bearer test_api_key', 'User-Agent': 'test user agent'},
            params=None
        )
        response_mock.content = json.dumps({'id': 1, 'name': 'test prod image'})
        res = res.images.get(1)
        self.assertEqual(bunchify({'id': 1, 'name': 'test prod image'}), res)

        requests_mock.get.assert_called_with(
            url='https://api.tiendanube.com/v1/46/products/991/images/1',
            headers={'Authentication': 'bearer test_api_key', 'User-Agent': 'test user agent'},
            params=None
        )
Пример #2
0
    def test_validate_package(self):
        maint = self.get_maintainer()
        pack = Package(filename='foo',
                       name='bar_2go',
                       package_format='1',
                       version='0.0.0',
                       description='pdesc',
                       licenses=['BSD'],
                       maintainers=[maint])
        pack.validate()
        # check invalid names
        pack.name = '2bar'
        self.assertRaises(InvalidPackage, Package.validate, pack)
        pack.name = 'bar bza'
        self.assertRaises(InvalidPackage, Package.validate, pack)
        pack.name = 'BAR'
        self.assertRaises(InvalidPackage, Package.validate, pack)
        # dashes should be acceptable in packages other than catkin or
        # ament*.
        # no build_type, so catkin is assumed per REP-140.
        pack.name = 'bar-bza'
        self.assertRaises(InvalidPackage, Package.validate, pack)
        # check explicit catkin and ament_* build_types
        build_type = Mock(tagname='build_type', attributes={}, content='catkin')
        pack.exports = [build_type]
        self.assertRaises(InvalidPackage, Package.validate, pack)
        build_type.content = 'ament_cmake'
        self.assertRaises(InvalidPackage, Package.validate, pack)
        build_type.content = 'ament_python'
        self.assertRaises(InvalidPackage, Package.validate, pack)
        # check non ament/catkin build type is valid
        build_type.content = 'cmake'
        pack.validate()
        # check authors emails
        pack.name = 'bar'
        auth1 = Mock()
        auth2 = Mock()
        auth2.validate.side_effect = InvalidPackage('foo')
        pack.authors = [auth1, auth2]
        self.assertRaises(InvalidPackage, Package.validate, pack)
        pack.authors = []
        pack.validate()
        # check maintainer required with email
        pack.maintainers = []
        self.assertRaises(InvalidPackage, Package.validate, pack)
        pack.maintainers = [maint]
        maint.email = None
        self.assertRaises(InvalidPackage, Package.validate, pack)
        maint.email = 'foo@bar.com'

        for dep_type in [
                pack.build_depends, pack.buildtool_depends,
                pack.build_export_depends, pack.buildtool_export_depends,
                pack.exec_depends, pack.test_depends, pack.doc_depends]:
            pack.validate()
            depend = Dependency(pack.name)
            dep_type.append(depend)
            self.assertRaises(InvalidPackage, Package.validate, pack)
            dep_type.remove(depend)
Пример #3
0
 def __init__(self):
     ticket_mock = Mock()
     ticket_mock.content = json.dumps(_get_ticket('Test'))
     ticket_mock.status_code = 200
     child_mock = Mock()
     child_mock.content = json.dumps([_get_ticket('Child'),
                                      _get_ticket('Child2')])
     child_mock.status_code = 200
     self.mocks = [ticket_mock, child_mock]
Пример #4
0
def mock_response(fixture=None, status=200):
    response = Mock()
    if fixture is None:
        response.content = ''
    elif isinstance(fixture, dict):
        response.content = str(fixture)
    else:
        response.content = load_fixture(fixture)
    response.status_code = status
    return response
Пример #5
0
 def inner(status_code=200, response_ok=True, response=None, content=None):
     mock_box_response = Mock(BoxResponse)
     mock_network_response = Mock(DefaultNetworkResponse)
     mock_box_response.network_response = mock_network_response
     mock_box_response.status_code = status_code
     mock_box_response.ok = response_ok
     if response is not None:
         mock_box_response.json.return_value = response
         mock_box_response.content = json.dumps(response).encode()
     else:
         mock_box_response.content = content
     return mock_box_response, mock_network_response
Пример #6
0
 def side_effect(*args, **kwargs):
     response = Mock()
     data = json.loads(kwargs.get('data', "{}"))
     for param in required_post_params:
         if param not in data:
             response.status_code = 400
             response.content = '%r is required'
             return response
         
     response.status_code = 200
     response.content = json.dumps({'s':1})
     return response
Пример #7
0
    def test_internal_message_list(self):
        msg = {
            "status": "queued",
            "messages": []
        }

        response = Mock()
        response.status_code = 200
        response.content = json.dumps(msg)

        self.mock_requests.request.return_value = response

        lbh = LogBookHandler('uuid')

        # The logbook starts off with no messages
        eq_(0, len(lbh.messages))

        msg['messages'].append(
        {
            "asctime": "2012-02-08T11:15:04",
            "message": "message1",
        })

        response.content = json.dumps(msg)
        self.mock_requests.request.return_value = response

        new_msg = lbh.fetch()

        # The logbook has one message now
        eq_(1, len(lbh.messages))
        eq_(new_msg, lbh.messages)

        messages = [
        {
            "asctime": "2012-02-08T11:15:05",
            "message": "message2",
        },
        {
            "asctime": "2012-02-08T11:15:06",
            "message": "message3",
        }]

        msg['messages'].extend(messages)

        response.content = json.dumps(msg)
        self.mock_requests.request.return_value = response

        new_msg = lbh.fetch()

        # The logbook has one message now
        eq_(3, len(lbh.messages))
        eq_(new_msg, messages)
 def setUp(self):
     response = Mock()
     response.content = self.response_body
     response.status_code = 200
     with patch('requests.post') as post:
         post.return_value = response
         self.perform_action()
Пример #9
0
 def request(*args, **kwargs):
     response = Mock()
     response.status_code = status
     if fixture:
         fixture_path = os.path.join(FIXTURES, fixture)
         response.content = open(fixture_path).read()
     return response
Пример #10
0
    def it_can_fetch_resources_from_a_remote_endpoint(self):
        mock_resp = Mock(name="mock_response")
        expected = {'id': 1}
        mock_resp.content = json.dumps(expected)
        mock_resp.status_code = 200

        self.mock_request.get.return_value = mock_resp

        manager = BackendManager('http')

        class Doc(Document):
            id = fields.NumberField()

            class Meta:
                backend_type = 'http'

            def uri(self):
                return 'http://location'

        doc = Doc({'id': 1})

        # the http manager returns the response as python dict
        content = manager.fetch(doc)

        # make sure we are working with correct expectations
        eq_(HttpBackendManager, type(manager))
        eq_(mock_resp, manager.response)
        ok_(isinstance(content, dict))
        eq_([('get', {'url': doc.uri()})],
                self.mock_request.method_calls)
Пример #11
0
    def setUp(self):
        # mock request object
        request = Request()
        request.method = 'GET'
        request.url = 'http://example.com/'
        request.params = {}
        request.data = {}
        request.params_and_data = {}
        self.request = request

        # mock response object
        response = Mock()
        response.content = 'access_token=321'
        response.headers = {'content-type': 'text/html; charset=UTF-8'}
        response.ok = True
        response.status_code = 200
        self.response = response

        # mock raise_for_status with an error
        def raise_for_status():
            raise Exception('Response not OK!')

        self.raise_for_status = raise_for_status

        # mock hook object
        hook = Mock()
        hook.consumer_key = '123'
        hook.consumer_secret = '456'
        hook.access_token = '321'
        hook.access_token_secret = '654'
        self.hook = hook
Пример #12
0
 def test_list_objects_with_invalid_content_length(self):
     http_response = Mock()
     http_response.encoding = 'utf-8'
     http_response.headers = CaseInsensitiveDict(
         {'Date': 'Thu, 22 Aug 2013 02:11:57 GMT',
          # We say we have 265 bytes but we're returning 0,
          # this should raise an exception because this is not
          # a HEAD request.
          'Content-Length': '265',
          'x-amz-request-id': '2B74ECB010FF029E',
          'ETag': '"40d06eb6194712ac1c915783004ef730"',
          'Server': 'AmazonS3',
          'content-type': 'binary/octet-stream',
          'Content-Type': 'binary/octet-stream',
          'accept-ranges': 'bytes',
          'Last-Modified': 'Tue, 20 Aug 2013 18:33:25 GMT',
          'x-amz-server-side-encryption': 'AES256'
          })
     http_response.content = ''
     http_response.request.method = 'GET'
     list_objects = self.s3.get_operation('ListObjects')
     expected = {"AcceptRanges": "bytes",
                 "ContentType": "binary/octet-stream",
                 "LastModified": "Tue, 20 Aug 2013 18:33:25 GMT",
                 "ContentLength": "265",
                 "ETag": '"40d06eb6194712ac1c915783004ef730"',
                 "ServerSideEncryption": "AES256"
                 }
     with self.assertRaises(IncompleteReadError):
         response_data = get_response(self.session, list_objects,
                                      http_response)[1]
Пример #13
0
    def test_unexpected_response_without_error_message(self):

        response = Mock()
        response.status_code = 422
        response.content = 'no processable response'
        exception = UnexpectedResponse(response)
        self.assertEqual("%s" % exception, "Unexpected response from server (422 error code)")
Пример #14
0
def build_response_mock(status_code, json_body=None, headers=None,
                        add_content_length=True, **kwargs):
    real_response = requests.Response()
    real_response.status_code = status_code

    text = None
    if json_body is not None:
        text = json.dumps(json_body)
        if add_content_length and headers is not {}:
            real_response.headers['content-length'] = len(text)

    if headers is not None:
        for k, v in headers.items():
            real_response.headers[k] = v

    for k, v in kwargs.items():
        setattr(real_response, k, v)

    response = Mock(wraps=real_response, autospec=True)
    if text:
        response.text = text

    # for some reason, wraps cannot handle attributes which are dicts
    # and accessed by key
    response.headers = real_response.headers
    response.content = text

    return response
Пример #15
0
    def test_success(self):
        # Setting up valid ticket
        valid_ticket = "valid_ticket"
        LoginEmailSentCertified(ticket=valid_ticket).put()

        # setting user data return
        rpc = Mock()
        result = Mock()
        result.status_code = 200
        result.content = '{"id":"123456","email":"foo@bar.com"}'
        rpc.get_result = Mock(return_value=result)
        pswdless.urlfetch.create_rpc = Mock(return_value=rpc)
        fetch = Mock()
        pswdless.urlfetch.make_fetch_call = fetch
        post_params = {"app_id": "1", "token": "2", "ticket": valid_ticket}
        url_detail = "https://pswdless.appspot.com/rest/detail"
        params = {"url_detail": url_detail}
        params.update(post_params)
        response = Mock()
        response.set_cookie = Mock()
        cmd = LogUserIn(cookie_name="user", response=response, **params)
        cmd.execute()
        self.assertDictEqual({"id": "123456", "email": "foo@bar.com"}, cmd.result)
        fetch.assert_called_once_with(
            rpc, url_detail, urllib.urlencode(post_params), method=urlfetch.POST, validate_certificate=True
        )
        self.assertIsNone(LoginEmailSentCertified.find_by_ticket(valid_ticket).get())
        response.set_cookie.assert_called_once_with("user", cmd._signed, httponly=True)
Пример #16
0
    def it_can_delete_resources_from_a_remote_endpoint(self):
        mock_resp = Mock(name="mock_response")
        expected = {'id': 1}
        mock_resp.content = json.dumps(expected)
        mock_resp.status_code = 204

        self.mock_request.delete.return_value = mock_resp

        manager = BackendManager('http')

        class Doc(Document):
            id = fields.NumberField()

            class Meta:
                backend_type = 'http'

            def uri(self):
                return 'http://location'

        doc = Doc({'id': 1})

        manager.delete(doc)

        # make sure we are working with correct expectations
        eq_(HttpBackendManager, type(manager))
        eq_([
            ('delete', {'url': doc.uri()})
            ],
                self.mock_request.method_calls)
Пример #17
0
    def it_can_construct_a_special_uri_for_delete_operations(self):
        class Doc(Document):
            id = fields.NumberField()

            class Meta:
                backend_type = 'http'

            def uri(self):
                return 'get'

            def delete_uri(self):
                return 'delete'

        manager = BackendManager('http')
        doc = Doc({'id': 1})

        expected = {'id': 1}

        response = Mock(name='mock_http_response')
        response.status_code = 200

        # set the return value of the GET request and the DELETE request
        self.mock_request.delete.return_value = response
        response.content = json.dumps(expected)
        self.mock_request.get.return_value = response

        # now make the fetch operation
        manager.delete(doc)

        # we should have made one GET and one PUT request
        eq_([('delete', {'url': 'delete'})],
                self.mock_request.method_calls)
Пример #18
0
    def it_can_update_the_document_on_the_remote_backend(self):
        class Doc(Document):
            id = fields.NumberField()
            name = fields.StringField()

            class Meta:
                backend_type = 'http'

            def uri(self):
                return 'http://location'

        doc = Doc({'id': 1})

        expected = {
                'id': 1,
                'name': 'other',
                }

        response = Mock(name='mock_http_response')
        response.content = json.dumps(expected)
        response.status_code = 200

        # set the return value of the GET request
        self.mock_request.get.return_value = response
        self.mock_request.put.return_value = response

        doc.update({'name': 'other'})

        # we should have made one GET and one PUT request
        eq_([('get', {'url': 'http://location'}),
            ('put', {'url': 'http://location', 'data': json.dumps(expected)})],
                self.mock_request.method_calls)
        eq_('other', doc.name)
Пример #19
0
def non_json_response():
    mock_network_response = Mock(DefaultNetworkResponse)
    mock_network_response.content = b''
    mock_network_response.ok = True
    mock_network_response.status_code = 200
    mock_network_response.json.side_effect = ValueError('No JSON object could be decoded')
    return mock_network_response
Пример #20
0
 def test_arbitrary_member(self, mock_request):
     mock_response = Mock()
     mock_response.ok = True
     mock_response.content = json.dumps({"short_codes": []})
     mock_request.return_value = mock_response
     self.assertEqual([], self.client.sms.short_codes.list())
     mock_request.assert_called_once_with("GET", ANY, params=ANY, auth=AUTH, timeout=sentinel.timeout)
Пример #21
0
    def test_unexpected_response(self):

        response = Mock()
        response.status_code = 422
        response.content = '{"message": "Unprocessable Entity"}'
        exception = UnexpectedResponse(response)
        self.assertEqual("%s" % exception, "Unexpected response from server (Error code: 422, Message: Unprocessable Entity)")
Пример #22
0
    def test_fail_max_retry(self):
        # this tests the read function when HTTP requests keep returning 503s
        # read call fails when it reaches the maximum number of retries, in
        # this case set to 2

        # mock the 503 responses
        mock_resp = Mock(name="503 resp")
        mock_resp.status_code = 503
        mock_resp.content = "Testing"

        headers = {'Content-Length': 10,
                   'X-CADC-Content-Length': 5, 'Retry-After': 4}

        def getheader(name, default):
            return headers[name]

        mock_resp.headers = MagicMock()
        mock_resp.headers.get.side_effect = getheader

        conn = Connection()
        conn.session.send = Mock(return_value=mock_resp)
        vofile = vos.VOFile(["Some URL"], conn, "GET")
        req = requests.Request("GET", "http://some/url")
        vofile.request = req.prepare()

        # set number of retries to 1 and check the OSError was thrown
        vofile.maxRetries = 1
        with self.assertRaises(OSError) as cm:
            vofile.read()
        mock_resp.headers.get.assert_called_with('Retry-After', 5)
Пример #23
0
 def test_get_response_size_from_content(self):
     parser = HTMLParser('', False)
     mock_response = Mock()
     mock_response.headers = {}
     mock_response.content = '1234567890'
     parser.response = mock_response
     assert parser.get_response_size() == 10
Пример #24
0
    def test_success(self):
        rpc = Mock()
        result = Mock()
        result.status_code = 200
        result.content = '{"ticket":"123456"}'
        rpc.get_result = Mock(return_value=result)
        pswdless.urlfetch.create_rpc = Mock(return_value=rpc)
        fetch = Mock()
        pswdless.urlfetch.make_fetch_call = fetch
        post_params = {
            "app_id": 1,
            "token": "2",
            "hook": "http://yourhooke.com",
            "email": "foo@bar.com",
            "lang": "pt_BR",
        }
        url = "https://pswdless.appspot.com/rest/login"
        send_login_params = {"url_login": url}
        send_login_params.update(post_params)

        send_login = facade.send_login_email(**send_login_params)
        send_login.execute()
        self.assertDictEqual({"ticket": "123456"}, send_login.result)
        les_model = LoginEmailSentCertified.find_by_ticket("123456").get()
        self.assertEqual("123456", les_model.ticket)
        fetch.assert_called_once_with(
            rpc, url, urllib.urlencode(post_params), method=urlfetch.POST, validate_certificate=True
        )
Пример #25
0
 def test_head_object_with_json(self):
     http_response = Mock()
     http_response.encoding = 'utf-8'
     http_response.headers = CaseInsensitiveDict(
         {'Date': 'Thu, 22 Aug 2013 02:11:57 GMT',
          'Content-Length': '0',
          'x-amz-request-id': '2B74ECB010FF029E',
          'ETag': '"40d06eb6194712ac1c915783004ef730"',
          'Server': 'AmazonS3',
          'content-type': 'application/json',
          'Content-Type': 'application/json',
          'accept-ranges': 'bytes',
          'Last-Modified': 'Tue, 20 Aug 2013 18:33:25 GMT',
          'x-amz-server-side-encryption': 'AES256'})
     http_response.content = ''
     put_object = self.s3.get_operation('HeadObject')
     expected = {"AcceptRanges": "bytes",
                 "ContentType": "application/json",
                 "LastModified": "Tue, 20 Aug 2013 18:33:25 GMT",
                 "ContentLength": "0",
                 "ETag": '"40d06eb6194712ac1c915783004ef730"',
                 "ServerSideEncryption": "AES256"
                 }
     response_data = get_response(self.session, put_object,
                                  http_response)[1]
     self.assertEqual(response_data, expected)
Пример #26
0
def create_mock_json(path, status_code=200):
    with open(path) as f:
        resp = Mock()
        resp.content = f.read()
        resp.json.return_value = json.loads(resp.content)
        resp.status_code = status_code
        return resp
Пример #27
0
    def setUp(self):
        # mock request object
        request = Request()
        request.method = "GET"
        request.url = "http://example.com/"
        request.params = {}
        request.data = {}
        request.params_and_data = {}
        self.request = request

        # mock response object
        response = Mock()
        response.content = "access_token=321"
        response.headers = {"content-type": "text/html; charset=UTF-8"}
        response.ok = True
        response.status_code = 200
        self.response = response

        # mock raise_for_status with an error
        def raise_for_status():
            raise Exception("Response not OK!")

        self.raise_for_status = raise_for_status

        # mock hook object
        hook = Mock()
        hook.consumer_key = "123"
        hook.consumer_secret = "456"
        hook.access_token = "321"
        hook.access_token_secret = "654"
        self.hook = hook
Пример #28
0
def generic_successful_response():
    mock_network_response = Mock(DefaultNetworkResponse)
    mock_network_response.content = b'{"message": "success"}'
    mock_network_response.status_code = 200
    mock_network_response.ok = True
    mock_network_response.raw = Mock()
    return mock_network_response
Пример #29
0
 def setUp(self):
     response = Mock()
     response.content = json.dumps({'status': 'ok'})
     response.headers = {'Content-Type': 'application/json'}
     response.ok = True
     response.status_code = requests.codes.ok
     self.response = response
Пример #30
0
    def test_parse_fedora_access(self):
        TEMPLATE_TEXT = """
            {% load fedora %}
            {% fedora_access %}
                {{ test_obj.value }}
            {% permission_denied %}
                permission fallback
            {% fedora_failed %}
                connection fallback
            {% end_fedora_access %}
        """
        t = Template(TEMPLATE_TEXT)
        test_obj = MockFedoraObject()
        ctx = Context({'test_obj': test_obj})

        val = t.render(ctx)
        self.assertEqual(val.strip(), 'sample text')

        response = Mock()
        response.status_code = 401
        response.headers = {'content-type': 'text/plain'}
        response.content = ''
        test_obj._value = PermissionDenied(response)  # force test_obj.value to fail
        val = t.render(ctx)
        self.assertEqual(val.strip(), 'permission fallback')

        response.status_code = 500
        test_obj._value = RequestFailed(response)  # force test_obj.value to fail
        val = t.render(ctx)
        self.assertEqual(val.strip(), 'connection fallback')