Esempio n. 1
0
def test_search_on_github_cache_terraform_releases_200(
    tmp_working_dir,
    terraform_releases_html_after_v0_13_0,  # noqa: F811
):  # noqa: D103
    with mock.patch("io.BytesIO", AutoclosingBytesIO):
        with pook.use():
            repo = "hashicorp/terraform"
            releases_url = "https://github.com/{}/releases?after=v0.13.0".format(repo)

            # A volatile mock that can only be invoked once
            pook.get(
                releases_url,
                reply=200,
                response_type="text/plain",
                response_body=terraform_releases_html_after_v0_13_0,
                response_headers={
                    "Status": "200 OK",
                    "ETag": 'W/"df0474ebd25f223a95926ba58e11e77b"',
                    "Cache-Control": "max-age=0, private, must-revalidate",
                    "Date": formatdate(usegmt=True),
                },
                times=1,
            )

            patch_regex = r"[0-9]+(((-alpha|-beta|-rc)[0-9]+)|(?P<dev>-dev))?"

            patch = tfwrapper.search_on_github(repo, "0.12", patch_regex, "14")
            assert patch == "14"

            patch = tfwrapper.search_on_github(repo, "0.12", patch_regex, "")
            assert patch == "19"

            assert pook.isdone()
            assert not pook.pending_mocks()
            assert not pook.unmatched_requests()
Esempio n. 2
0
    def testDoesNotInterceptRequestWhenNoAuthorizationHeader(self):
        (pook.get('https://example.com/api/v1/valid/url').times(1).reply(
            200).type('json').json({'status': 'ok'}))

        header_params_without_authorization = {'Accept': 'application/json'}
        res = self.a_get_request(header_params_without_authorization)

        self.assertTrue(pook.isdone())
        self.assertEqual(res, {'status': 'ok'})
Esempio n. 3
0
def test_requests_match_url(mock):
    body = {'foo': 'bar'}
    mock.get('http://foo.com').reply(200).json(body)

    res = requests.get('http://foo.com')
    assert res.status_code == 200
    assert res.headers == {'Content-Type': 'application/json'}
    assert res.json() == body
    assert pook.isdone() is True
Esempio n. 4
0
def test_requests_get(mock):
    body = {'error': 'not found'}
    mock.get('http://foo.com').reply(404).json(body)

    res = requests.get('http://foo.com')
    assert res.status_code == 404
    assert res.headers == {'Content-Type': 'application/json'}
    assert res.json() == body
    assert pook.isdone() is True
Esempio n. 5
0
    def test_sends_slack_invite(self, rf):
        request = rf.post(self.url, data={
            'email': '*****@*****.**',
            'accept_tos': True,
        })
        SessionMiddleware().process_request(request)
        MessageMiddleware().process_request(request)

        response = SlackInvite.as_view()(request)
        assert response.status_code == 302
        assert pook.isdone()
        assert len(request._messages) == 1  # don't really care about the text
Esempio n. 6
0
    def test_sends_slack_invite(self, rf, settings):
        settings.CELERY_ALWAYS_EAGER = True

        request = rf.post(self.url,
                          data={
                              'email': '*****@*****.**',
                              'accept_tos': True,
                          })
        response = SlackInvite.as_view()(request)
        assert response.status_code == 200
        assert 'task_id' in json.loads(response.content)
        assert pook.isdone()
Esempio n. 7
0
def run():
    pook.get('httpbin.org/ip',
             reply=403,
             response_headers={'pepe': 'lopez'},
             response_json={'error': 'not found'})

    res = requests.get('http://httpbin.org/ip')
    print('Status:', res.status_code)
    print('Headers:', res.headers)
    print('Body:', res.json())

    print('Is done:', pook.isdone())
    print('Pending mocks:', pook.pending_mocks())
    print('Unmatched requests:', pook.unmatched_requests())
Esempio n. 8
0
def test_search_on_github_cache_terraform_releases_does_not_cache_error_429(
        tmp_working_dir,
        terraform_releases_html_after_v0_13_0,  # noqa: F811
):  # noqa: D103
    with mock.patch("io.BytesIO", AutoclosingBytesIO):
        with pook.use():
            repo = "hashicorp/terraform"
            releases_url = "https://github.com/{}/releases?after=v0.13.0".format(
                repo)

            # volatile mocks that can only be invoked once each
            pook.get(
                releases_url,
                reply=429,
                response_headers={
                    "Status": "429 Too Many Requests",
                    "Date": formatdate(usegmt=True),
                    "Retry-After": "120"
                },
                times=1,
            )
            pook.get(
                releases_url,
                reply=200,
                response_type="text/plain",
                response_body=terraform_releases_html_after_v0_13_0,
                response_headers={
                    "Status": "200 OK",
                    "ETag": 'W/"df0474ebd25f223a95926ba58e11e77b"',
                    "Cache-Control": "max-age=0, private, must-revalidate",
                    "Date": formatdate(usegmt=True),
                },
                times=1,
            )

            patch_regex = r"[0-9]+(((-alpha|-beta|-rc)[0-9]+)|(?P<dev>-dev))?"

            # pook does not implement urllib3's retry logic so this first request will always return None during tests
            patch = tfwrapper.search_on_github(repo, "0.12", patch_regex, "14")
            assert patch is None

            patch = tfwrapper.search_on_github(repo, "0.12", patch_regex, "14")
            assert patch == "14"

            patch = tfwrapper.search_on_github(repo, "0.12", patch_regex, "")
            assert patch == "19"

            assert pook.isdone()
            assert not pook.pending_mocks()
            assert not pook.unmatched_requests()
Esempio n. 9
0
async def run():
    pook.get('httpbin.org/ip',
             reply=403,
             response_headers={'pepe': 'lopez'},
             response_json={'error': 'not found'})

    async with aiohttp.ClientSession(loop=loop) as session:
        async with session.get('http://httpbin.org/ip') as res:
            print('Status:', res.status)
            print('Headers:', res.headers)
            print('Body:', await res.text())

            print('Is done:', pook.isdone())
            print('Pending mocks:', pook.pending_mocks())
            print('Unmatched requests:', pook.unmatched_requests())
Esempio n. 10
0
    def testShouldThrowErrorWhenCannotRefreshToken(self):
        expired_token = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVC"

        (pook.post(self.configuration.host +
                   '/oauth2/token').times(1).reply(500).type('json').json(
                       {'Error': "Unknown Error"}))

        (pook.get(self.configuration.host + '/v1/valid/url').header(
            'Authorization', "Bearer " + expired_token
        ).times(0).reply(200).type('json').json({
            'message':
            "can't make this call since client could not refresh expired token"
        }))

        with self.assertRaises(ApiException) as cm:
            self.get_with_expired_token(expired_token)

        self.assertEqual(cm.exception.status, 500)
        self.assertIn("Cannot refresh token by calling",
                      cm.exception.body["token_error"])
        self.assertTrue(pook.isdone())
Esempio n. 11
0
    def testAlwaysSendValidBearerToken(self):
        expired_token = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJjdHg6dXNlcjp1bXNJZCI6IjIyNjQyMSIsImN0eDp1c2VyOnVp"
        fresh_token = "kltTjBlKHAxYzJWIiwiY3"

        (pook.post(self.configuration.host + '/oauth2/token').header(
            "Content-Type", "application/x-www-form-urlencoded").body(
                'client_id=%s&client_secret=%s&grant_type=client_credentials' %
                (self.configuration.username, self.configuration.password)).
         times(1).reply(200).type('json').json(
             dict(access_token=fresh_token,
                  expires_in=299,
                  token_type="bearer")))

        (pook.get(self.configuration.host + '/v1/valid/url').header(
            'Authorization',
            "Bearer " + fresh_token).times(1).reply(200).type('json').json(
                {'status': 'ok'}))

        res = self.get_with_expired_token(expired_token)

        self.assertTrue(pook.isdone())
        self.assertEqual(res, {'status': 'ok'})
Esempio n. 12
0
 def test_members_list_on_ok(self, slack_client: SlackClient):
     assert isinstance(slack_client.members(), list)
     assert pook.isdone()
Esempio n. 13
0
 def test_invite_raises_on_bad_response(self, slack_client: SlackClient):
     with pytest.raises(HTTPError):
         slack_client.invite('*****@*****.**', [])
     assert pook.isdone()
Esempio n. 14
0
 def test_invite_raises_on_not_ok(self, slack_client: SlackClient):
     with pytest.raises(SlackException):
         slack_client.invite('*****@*****.**', [])
     assert pook.isdone()
Esempio n. 15
0
 def test_channels_list_on_ok(self, slack_client: SlackClient):
     assert isinstance(slack_client.channels(), list)
     assert pook.isdone()
Esempio n. 16
0
 def test_channels_raises_on_not_ok(self, slack_client: SlackClient):
     with pytest.raises(SlackException):
         slack_client.channels()
     assert pook.isdone()
Esempio n. 17
0
 def test_invite_returns_true_on_ok(self, slack_client: SlackClient):
     assert slack_client.invite('*****@*****.**', [])
     assert pook.isdone()
Esempio n. 18
0
import json
import pook
import requests


# Enable mock engine
pook.on()

(pook.post('httpbin.org/post')
    .json({'foo': 'bar'})
    .type('json')
    .header('Client', 'requests')
    .reply(204)
    .headers({'server': 'pook'})
    .json({'error': 'simulated'}))

res = requests.post('http://httpbin.org/post',
                    data=json.dumps({'foo': 'bar'}),
                    headers={'Client': 'requests',
                             'Content-Type': 'application/json'})

print('Status:', res.status_code)
print('Body:', res.json())

print('Is done:', pook.isdone())
print('Pending mocks:', pook.pending_mocks())
Esempio n. 19
0
 def test_channels_raises_on_bad_response(self, slack_client: SlackClient):
     with pytest.raises(HTTPError):
         slack_client.channels()
     assert pook.isdone()