Beispiel #1
0
    def test_disconnect_with_partial_pipeline(self):
        self.strategy.set_settings({
            'SOCIAL_AUTH_DISCONNECT_PIPELINE': (
                'social.pipeline.partial.save_status_to_session',
                'social.tests.pipeline.ask_for_password',
                'social.tests.pipeline.set_password',
                'social.pipeline.disconnect.allowed_to_disconnect',
                'social.pipeline.disconnect.get_entries',
                'social.pipeline.disconnect.revoke_tokens',
                'social.pipeline.disconnect.disconnect'
            )
        })
        self.do_login()
        user = User.get(self.expected_username)
        redirect = do_disconnect(self.backend, user)

        url = self.strategy.build_absolute_uri('/password')
        expect(redirect.url).to.equal(url)
        HTTPretty.register_uri(HTTPretty.GET, redirect.url, status=200,
                               body='foobar')
        HTTPretty.register_uri(HTTPretty.POST, redirect.url, status=200)

        password = 'foobar'
        requests.get(url)
        requests.post(url, data={'password': password})
        data = parse_qs(HTTPretty.last_request.body)
        expect(data['password']).to.equal(password)
        self.strategy.session_set('password', data['password'])

        redirect = do_disconnect(self.backend, user)
        expect(len(user.social)).to.equal(0)
Beispiel #2
0
    def test_no_tags(self):
        HTTPretty.register_uri(HTTPretty.POST, 'https://api.tumblr.com/v2/blog/seejohnrun.tumblr.com/post',
                               body='{"meta": {"status": 201, "msg": "OK"}, "response": []}')

        response = self.client.create_link('seejohnrun.tumblr.com', tags=[])
        experimental_body = parse_qs(HTTPretty.last_request.body)
        assert 'tags' not in experimental_body
Beispiel #3
0
    def test_new_from_url(self):
        HTTPretty.register_uri(HTTPretty.GET, 'http://example.com/',
                               body='snerble')

        webpage = WebPage.new_from_url('http://example.com/')

        self.assertEquals(webpage.html, 'snerble')
def test_callback_setting_headers_and_status_response(now):
    ("HTTPretty should call a callback function and uses it retur tuple as status code, headers and body"
     " requests")

    def request_callback(request, uri, headers):
        headers.update({'a': 'b'})
        return [418, headers, "The {} response from {}".format(decode_utf8(request.method), uri)]

    HTTPretty.register_uri(
        HTTPretty.GET, "https://api.yahoo.com/test",
        body=request_callback)

    response = requests.get('https://api.yahoo.com/test')
    expect(response.text).to.equal("The GET response from https://api.yahoo.com/test")
    expect(response.headers).to.have.key('a').being.equal("b")
    expect(response.status_code).to.equal(418)

    HTTPretty.register_uri(
        HTTPretty.POST, "https://api.yahoo.com/test_post",
        body=request_callback)

    response = requests.post(
        "https://api.yahoo.com/test_post",
        {"username": "gabrielfalcao"}
    )

    expect(response.text).to.equal("The POST response from https://api.yahoo.com/test_post")
    expect(response.headers).to.have.key('a').being.equal("b")
    expect(response.status_code).to.equal(418)
def test_httpretty_should_allow_multiple_responses_with_multiple_methods():
    "HTTPretty should allow multiple responses when binding multiple methods to the same uri"

    url = 'http://test.com/list'

    # add get responses
    HTTPretty.register_uri(
        HTTPretty.GET, url,
        responses=[
            HTTPretty.Response(body='a'),
            HTTPretty.Response(body='b'),
        ]
    )

    # add post responses
    HTTPretty.register_uri(
        HTTPretty.POST, url,
        responses=[
            HTTPretty.Response(body='c'),
            HTTPretty.Response(body='d'),
        ]
    )

    expect(requests.get(url).text).to.equal('a')
    expect(requests.post(url).text).to.equal('c')

    expect(requests.get(url).text).to.equal('b')
    expect(requests.get(url).text).to.equal('b')
    expect(requests.get(url).text).to.equal('b')

    expect(requests.post(url).text).to.equal('d')
    expect(requests.post(url).text).to.equal('d')
    expect(requests.post(url).text).to.equal('d')
def test_httpretty_should_allow_adding_and_overwritting_by_kwargs_u2(now):
    u"HTTPretty should allow adding and overwritting headers by keyword args " \
        "with httplib2"

    HTTPretty.register_uri(HTTPretty.GET, "http://github.com/foo",
                           body="this is supposed to be the response",
                           server='Apache',
                           content_length='27',
                           content_type='application/json')

    headers, _ = httplib2.Http().request('http://github.com/foo', 'GET')

    expect(dict(headers)).to.equal({
        'content-type': 'application/json',
        'content-location': 'http://github.com/foo',  # httplib2 FORCES
                                                   # content-location
                                                   # even if the
                                                   # server does not
                                                   # provide it
        'connection': 'close',
        'content-length': '27',
        'status': '200',
        'server': 'Apache',
        'date': now.strftime('%a, %d %b %Y %H:%M:%S GMT'),
    })
def test_rotating_responses_with_requests(now):
    "HTTPretty should support rotating responses with requests"

    HTTPretty.register_uri(
        HTTPretty.GET, "https://api.yahoo.com/test",
        responses=[
            HTTPretty.Response(body=b"first response", status=201),
            HTTPretty.Response(body=b'second and last response', status=202),
        ])

    response1 = requests.get(
        'https://api.yahoo.com/test')

    expect(response1.status_code).to.equal(201)
    expect(response1.text).to.equal('first response')

    response2 = requests.get(
        'https://api.yahoo.com/test')

    expect(response2.status_code).to.equal(202)
    expect(response2.text).to.equal('second and last response')

    response3 = requests.get(
        'https://api.yahoo.com/test')

    expect(response3.status_code).to.equal(202)
    expect(response3.text).to.equal('second and last response')
    def __init__(self):
        """
        Constructor
        """
        self.api_endpoint = current_app.config['FEEDBACK_SLACK_END_POINT']

        def request_callback(request, uri, headers):
            """
            Callback
            :param request: HTTP request
            :param uri: URI/URL to send the request
            :param headers: header of the HTTP request
            :return: httpretty response
            """
            if 'text' in request.body:
                resp = json.dumps(dict(
                    msg='success'
                ))
                return 200, headers, resp
            else:
                resp = json.dumps(dict(
                    msg='fail'
                ))
                return 400, headers, resp

        HTTPretty.register_uri(
            method=HTTPretty.POST,
            uri=self.api_endpoint,
            body=request_callback,
            content_type="application/json"
        )
Beispiel #9
0
def test_second_authentication_step_takes_code_and_makes_a_request(context):
    "github.API's second authentication step is a redirect"

    class MyStore(github.TokenStore):
        data = {}

        def set(self, k, v):
            self.data[k] = v

        def get(self, k):
            return self.data.get(k)

    simple = MyStore()
    api = github.API("app-id-here", "app-secret-here", store=simple)

    HTTPretty.register_uri(
        HTTPretty.POST,
        "https://github.com/login/oauth/access_token",
        body='{"access_token": "this-is-the-access-token"}',
        status=200,
    )

    result = api.authenticate(code="visitor-code")
    assert that(result).is_a(github.API)

    last_request = HTTPretty.last_request
    assert that(last_request.headers).has("Authentication")
    def __init__(self, api_endpoint):
        """
        Constructor

        :param api_endpoint: name of the API end point
        """

        self.api_endpoint = api_endpoint

        def request_callback(request, uri, headers):
            """

            :param request: HTTP request
            :param uri: URI/URL to send the request
            :param headers: header of the HTTP request
            :return: httpretty response
            """
            resp = json.dumps(
                {
                    'api-response': 'success',
                    'token': request.headers.get(
                        'Authorization', 'No Authorization header passed!'
                    )
                }
            )
            return 200, headers, resp

        HTTPretty.register_uri(
            HTTPretty.GET,
            self.api_endpoint,
            body=request_callback,
            content_type="application/json"
        )
    def __init__(self):
        """
        Constructor
        """
        self.api_endpoint = current_app.config['GOOGLE_RECAPTCHA_ENDPOINT']

        def request_callback(request, uri, headers):
            """
            Callback
            :param request: HTTP request
            :param uri: URI/URL to send the request
            :param headers: header of the HTTP request
            :return: httpretty response
            """
            data = request.parsed_body

            if data['response'][0] == 'correct_response':
                res = {'success': True}
            elif data['response'][0] == 'incorrect_response':
                res = {'success': False}
            elif data['response'][0] == 'dont_return_200':
                return 503, headers, "Service Unavailable"
            else:
                raise Exception(
                    "This case is not expected by the tests: {0}".format(data)
                )

            return 200, headers, json.dumps(res)

        HTTPretty.register_uri(
            method=HTTPretty.POST,
            uri=self.api_endpoint,
            body=request_callback,
            content_type="application/json"
        )
 def tearDown(self):
     HTTPretty.disable()
     HTTPretty.reset()
     self.backend = None
     self.strategy = None
     self.name = None
     self.complete_url = None
Beispiel #13
0
    def test_connection_close(self):
        """Check connection re-use after close header is received"""
        HTTPretty.register_uri(HTTPretty.POST,
                               'https://%s/' % self.region.endpoint,
                               json.dumps({'test': 'secure'}),
                               content_type='application/json',
                               connection='close')

        conn = self.region.connect(aws_access_key_id='access_key',
                                   aws_secret_access_key='secret')

        def mock_put_conn(*args, **kwargs):
            raise Exception('put_http_connection should not be called!')

        conn.put_http_connection = mock_put_conn

        resp1 = conn.make_request('myCmd1',
                                  {'par1': 'foo', 'par2': 'baz'},
                                  "/",
                                  "POST")

        # If we've gotten this far then no exception was raised
        # by attempting to put the connection back into the pool
        # Now let's just confirm the close header was actually
        # set or we have another problem.
        self.assertEqual(resp1.getheader('connection'), 'close')
Beispiel #14
0
    def test_multi_commands(self):
        """Check connection re-use"""
        HTTPretty.register_uri(HTTPretty.POST,
                               'https://%s/' % self.region.endpoint,
                               json.dumps({'test': 'secure'}),
                               content_type='application/json')

        conn = self.region.connect(aws_access_key_id='access_key',
                                   aws_secret_access_key='secret')

        resp1 = conn.make_request('myCmd1',
                                  {'par1': 'foo', 'par2': 'baz'},
                                  "/",
                                  "POST")
        body1 = urlparse.parse_qs(HTTPretty.last_request.body)

        resp2 = conn.make_request('myCmd2',
                                  {'par3': 'bar', 'par4': 'narf'},
                                  "/",
                                  "POST")
        body2 = urlparse.parse_qs(HTTPretty.last_request.body)

        self.assertEqual(body1['par1'], ['foo'])
        self.assertEqual(body1['par2'], ['baz'])
        with self.assertRaises(KeyError):
            body1['par3']

        self.assertEqual(body2['par3'], ['bar'])
        self.assertEqual(body2['par4'], ['narf'])
        with self.assertRaises(KeyError):
            body2['par1']

        self.assertEqual(resp1.read(), '{"test": "secure"}')
        self.assertEqual(resp2.read(), '{"test": "secure"}')
Beispiel #15
0
def test_fake_socket_passes_through_gettimeout():
    import socket
    HTTPretty.enable()
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.truesock = MagicMock()
    expect(s.gettimeout).called_with().should_not.throw(AttributeError)
    s.truesock.gettimeout.assert_called_with()
Beispiel #16
0
 def test_methods(self):
     client = Hammock(self.BASE_URL)
     for method in ['GET', 'POST', 'PUT', 'DELETE', 'PATCH']:
         HTTPretty.register_uri(getattr(HTTPretty, method), self.URL)
         request = getattr(client, method)
         resp = request('sample', 'path', 'to', 'resource')
         self.assertEqual(HTTPretty.last_request.method, method)
Beispiel #17
0
def test_fake_socket_passes_through_shutdown():
    import socket
    HTTPretty.enable()
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.truesock = MagicMock()
    expect(s.shutdown).called_with(socket.SHUT_RD).should_not.throw(AttributeError)
    s.truesock.shutdown.assert_called_with(socket.SHUT_RD)
Beispiel #18
0
def test_httpretty_should_support_a_list_of_successive_responses_urllib2(now):
    "HTTPretty should support adding a list of successive " \
    "responses with urllib2"

    HTTPretty.register_uri(
        HTTPretty.GET, "https://api.yahoo.com/test",
        responses=[
            HTTPretty.Response(body="first response", status=201),
            HTTPretty.Response(body='second and last response', status=202),
        ])

    request1 = urlopen('https://api.yahoo.com/test')
    body1 = request1.read()
    request1.close()

    expect(request1.code).to.equal(201)
    expect(body1).to.equal(b'first response')

    request2 = urlopen('https://api.yahoo.com/test')
    body2 = request2.read()
    request2.close()
    expect(request2.code).to.equal(202)
    expect(body2).to.equal(b'second and last response')

    request3 = urlopen('https://api.yahoo.com/test')
    body3 = request3.read()
    request3.close()
    expect(request3.code).to.equal(202)
    expect(body3).to.equal(b'second and last response')
Beispiel #19
0
def test_rotating_responses_with_httplib2(now):
    u"HTTPretty should support rotating responses with httplib2"

    HTTPretty.register_uri(
        HTTPretty.GET, "https://api.yahoo.com/test",
        responses=[
            HTTPretty.Response(body="first response", status=201),
            HTTPretty.Response(body='second and last response', status=202),
        ])

    headers1, body1 = httplib2.Http().request(
        'https://api.yahoo.com/test', 'GET')

    expect(headers1['status']).to.equal('201')
    expect(body1).to.equal(b'first response')

    headers2, body2 = httplib2.Http().request(
        'https://api.yahoo.com/test', 'GET')

    expect(headers2['status']).to.equal('202')
    expect(body2).to.equal(b'second and last response')

    headers3, body3 = httplib2.Http().request(
        'https://api.yahoo.com/test', 'GET')

    expect(headers3['status']).to.equal('202')
    expect(body3).to.equal(b'second and last response')
Beispiel #20
0
def test_can_inspect_last_request(now):
    "HTTPretty.last_request is a mimetools.Message request from last match"

    HTTPretty.register_uri(HTTPretty.POST, "http://api.github.com/",
                           body='{"repositories": ["HTTPretty", "lettuce"]}')

    request = urllib2.Request(
        'http://api.github.com',
        b'{"username": "gabrielfalcao"}',
        {
            'content-type': 'text/json',
        },
    )
    fd = urlopen(request)
    got = fd.read()
    fd.close()

    expect(HTTPretty.last_request.method).to.equal('POST')
    expect(HTTPretty.last_request.body).to.equal(
        b'{"username": "gabrielfalcao"}',
    )
    expect(HTTPretty.last_request.headers['content-type']).to.equal(
        'text/json',
    )
    expect(got).to.equal(b'{"repositories": ["HTTPretty", "lettuce"]}')
def test_callback_response(now):
    ("HTTPretty should call a callback function and set its return value as the body of the response"
     " requests")

    def request_callback(request, uri, headers):
        return [200, headers, "The {} response from {}".format(decode_utf8(request.method), uri)]

    HTTPretty.register_uri(
        HTTPretty.GET, "https://api.yahoo.com/test",
        body=request_callback)

    response = requests.get('https://api.yahoo.com/test')

    expect(response.text).to.equal("The GET response from https://api.yahoo.com/test")

    HTTPretty.register_uri(
        HTTPretty.POST, "https://api.yahoo.com/test_post",
        body=request_callback)

    response = requests.post(
        "https://api.yahoo.com/test_post",
        {"username": "gabrielfalcao"}
    )

    expect(response.text).to.equal("The POST response from https://api.yahoo.com/test_post")
Beispiel #22
0
def test_can_inspect_last_request_with_ssl(now):
    "HTTPretty.last_request is recorded even when mocking 'https' (SSL)"

    HTTPretty.register_uri(HTTPretty.POST, "https://secure.github.com/",
                           body='{"repositories": ["HTTPretty", "lettuce"]}')

    request = urllib2.Request(
        'https://secure.github.com',
        b'{"username": "gabrielfalcao"}',
        {
            'content-type': 'text/json',
        },
    )
    fd = urlopen(request)
    got = fd.read()
    fd.close()

    expect(HTTPretty.last_request.method).to.equal('POST')
    expect(HTTPretty.last_request.body).to.equal(
        b'{"username": "gabrielfalcao"}',
    )
    expect(HTTPretty.last_request.headers['content-type']).to.equal(
        'text/json',
    )
    expect(got).to.equal(b'{"repositories": ["HTTPretty", "lettuce"]}')
def test_httpretty_should_allow_registering_regexes_with_streaming_responses():
    "HTTPretty should allow registering regexes with streaming responses"
    import os
    os.environ['DEBUG'] = 'true'

    def my_callback(request, url, headers):
        request.body.should.equal(b'hithere')
        return 200, headers, "Received"

    HTTPretty.register_uri(
        HTTPretty.POST,
        re.compile("https://api.yipit.com/v1/deal;brand=(?P<brand_name>\w+)"),
        body=my_callback,
    )

    def gen():
        yield b'hi'
        yield b'there'

    response = requests.post(
        'https://api.yipit.com/v1/deal;brand=gap?first_name=chuck&last_name=norris',
        data=gen(),
    )
    expect(response.content).to.equal(b"Received")
    expect(HTTPretty.last_request.method).to.equal('POST')
    expect(HTTPretty.last_request.path).to.equal('/v1/deal;brand=gap?first_name=chuck&last_name=norris')
Beispiel #24
0
def test_callback_response(now):
    ("HTTPretty should all a callback function to be set as the body with"
      " urllib2")

    def request_callback(request, uri, headers):
        return [200, headers, "The {0} response from {1}".format(decode_utf8(request.method), uri)]

    HTTPretty.register_uri(
        HTTPretty.GET, "https://api.yahoo.com/test",
        body=request_callback)

    fd = urllib2.urlopen('https://api.yahoo.com/test')
    got = fd.read()
    fd.close()

    expect(got).to.equal(b"The GET response from https://api.yahoo.com/test")

    HTTPretty.register_uri(
        HTTPretty.POST, "https://api.yahoo.com/test_post",
        body=request_callback)

    request = urllib2.Request(
        "https://api.yahoo.com/test_post",
        b'{"username": "gabrielfalcao"}',
        {
            'content-type': 'text/json',
        },
    )
    fd = urllib2.urlopen(request)
    got = fd.read()
    fd.close()

    expect(got).to.equal(b"The POST response from https://api.yahoo.com/test_post")
def test_httpretty_should_work_with_non_standard_ports():
    "HTTPretty should work with a non-standard port number"

    HTTPretty.register_uri(
        HTTPretty.GET,
        re.compile("https://api.yipit.com:1234/v1/deal;brand=(?P<brand_name>\w+)"),
        body=lambda method, uri, headers: [200, headers, uri]
    )
    HTTPretty.register_uri(
        HTTPretty.POST,
        "https://asdf.com:666/meow",
        body=lambda method, uri, headers: [200, headers, uri]
    )

    response = requests.get('https://api.yipit.com:1234/v1/deal;brand=gap?first_name=chuck&last_name=norris')

    expect(response.text).to.equal('https://api.yipit.com:1234/v1/deal;brand=gap?first_name=chuck&last_name=norris')
    expect(HTTPretty.last_request.method).to.equal('GET')
    expect(HTTPretty.last_request.path).to.equal('/v1/deal;brand=gap?first_name=chuck&last_name=norris')

    response = requests.post('https://asdf.com:666/meow')

    expect(response.text).to.equal('https://asdf.com:666/meow')
    expect(HTTPretty.last_request.method).to.equal('POST')
    expect(HTTPretty.last_request.path).to.equal('/meow')
Beispiel #26
0
def test_recording_calls(port):
    ("HTTPretty should be able to record calls")
    # Given a destination path:
    destination = FIXTURE_FILE("recording-1.json")

    # When I record some calls
    with HTTPretty.record(destination):
        requests.get(server_url("/foobar?name=Gabriel&age=25", port))
        requests.post(server_url("/foobar", port),
                      data=json.dumps({'test': '123'}),
                      headers={"Test": "foobar"})

    # Then the destination path should exist
    os.path.exists(destination).should.be.true

    # And the contents should be json
    raw = open(destination).read()
    json.loads.when.called_with(raw).should_not.throw(ValueError)

    # And the contents should be expected
    data = json.loads(raw)
    data.should.be.a(list)
    data.should.have.length_of(2)

    # And the responses should have the expected keys
    response = data[0]
    response.should.have.key("request").being.length_of(5)
    response.should.have.key("response").being.length_of(3)

    response['request'].should.have.key("method").being.equal("GET")
    response['request'].should.have.key("headers").being.a(dict)
    response['request'].should.have.key("querystring").being.equal({
        "age": [
            "25"
        ],
        "name": [
            "Gabriel"
        ]
    })
    response['response'].should.have.key("status").being.equal(200)
    response['response'].should.have.key("body").being.an(text_type)
    response['response'].should.have.key("headers").being.a(dict)
    response['response']["headers"].should.have.key("Server").being.equal("TornadoServer/" + tornado_version)

    # And When I playback the previously recorded calls
    with HTTPretty.playback(destination):
        # And make the expected requests
        response1 = requests.get(server_url("/foobar?name=Gabriel&age=25", port))
        response2 = requests.post(
            server_url("/foobar", port),
            data=json.dumps({'test': '123'}),
            headers={"Test": "foobar"},
        )

    # Then the responses should be the expected
    response1.json().should.equal({"foobar": {"age": "25", "name": "Gabriel"}})
    response2.json()["foobar"].should.equal({})
    response2.json()["req_body"].should.equal(json.dumps({"test": "123"}))
    response2.json()["req_headers"].should.have.key("Test")
    response2.json()["req_headers"]["Test"].should.equal("foobar")
Beispiel #27
0
    def test_posts_with_type_and_arg(self):
        HTTPretty.register_uri(HTTPretty.GET, 'https://api.tumblr.com/v2/blog/seejohnrun.tumblr.com/posts/photo?limit=1',
                               body='{"meta": {"status": 200, "msg": "OK"}, "response": {"posts": [] } }')

        args = { 'limit': 1 }
        response = self.client.posts('seejohnrun', 'photo', **args)
        assert response['posts'] == []
Beispiel #28
0
 def test_file_exists_no_duplicate(self):
     HTTPretty.register_uri(HTTPretty.GET, "http://foo.net/foo.pdf",
                        body="foo")
     rg = ResourceGrabber("http://foo.net/foo.pdf")
     with open(os.path.join(self.directory, 'foo.pdf'), 'wb') as f:
         f.write('foo')
     self.assertEqual(rg.download(self.directory, duplicate_check=True), None)
def _mock_fetch_uris(endpoint, resource_uri):
    raw_values = _get_raw_values()
    values = iter(raw_values)

    rest = islice(values, 20)
    rest_data = list(rest)
    offset = 0
    while rest_data:
        if offset == 0:
            # Match every request without "offset" in it.
            regexp_txt = "(?!.*offset)"
        else:
            regexp_txt = ".*&offset=%d.*" % offset
        regexp = re.compile(endpoint + regexp_txt)

        offset += 20

        if offset == 80:
            next_uri = None
        else:
            query = '/?limit=20&key=install&offset=%d'
            next_uri = resource_uri + query % offset

        HTTPretty.register_uri(
            HTTPretty.GET,
            regexp,
            body=json_dumps({'meta': {"limit": 20,
                                      "next": next_uri,
                                      "offset": 0,
                                      "previous": None,
                                      "total_count": len(raw_values)},
                             'objects': rest_data}))

        rest = islice(values, 20)
        rest_data = list(rest)
Beispiel #30
0
    def render(self, template, json_mocks):
        if type(json_mocks) is not list:
            json_mocks = [json_mocks]
        responses = [HTTPretty.Response(get_json(_)) for _ in json_mocks]

        HTTPretty.register_uri(HTTPretty.GET, self.api_url, responses=responses, content_type='application/json')
        return render_template(template=template)