コード例 #1
0
ファイル: test_conversations.py プロジェクト: UPCnet/maxbunny
    def test_invalid_message_missing_username(self):
        """
            Given a message with missing username
            When the message is processed
            Then an exception is raised
            And the push message is not queued
        """
        from maxbunny.consumers.conversations import __consumer__
        from maxbunny.tests.mockers.conversations import MISSING_USERNAME_MESSAGE as message

        self.set_server({}, None)

        httpretty.enable()
        http_mock_info()

        runner = MockRunner('conversations', 'maxbunny.ini', 'instances2.ini')
        consumer = __consumer__(runner)

        self.assertRaisesWithMessage(
            BunnyMessageCancel,
            'Missing username in message',
            consumer.process,
            message
        )

        httpretty.disable()
        httpretty.reset()

        sleep(0.1)  # Leave a minimum time to message to reach rabbitmq
        messages = self.server.get_all('push')
        self.assertEqual(len(messages), 0)
コード例 #2
0
ファイル: helper.py プロジェクト: carriercomm/w3af_analyse
    def tearDown(self):
        self.w3afcore.quit()
        self.kb.cleanup()

        if self.MOCK_RESPONSES:
            httpretty.disable()
            httpretty.reset()
コード例 #3
0
ファイル: test_common.py プロジェクト: EclecticIQ/cabby
def test_timeout(version):
    httpretty.reset()
    httpretty.enable()

    timeout_in_sec = 1

    client = make_client(version)
    #
    # configure to raise the error before the timeout
    #
    client.timeout = timeout_in_sec / 2.0

    def timeout_request_callback(request, uri, headers):
        sleep(timeout_in_sec)
        return (200, headers, "All good!")

    uri = get_fix(version).DISCOVERY_URI_HTTP

    httpretty.register_uri(
        httpretty.POST,
        uri,
        body=timeout_request_callback,
        content_type='application/json'
    )

    with pytest.raises(requests.exceptions.Timeout):
        client.discover_services(uri=uri)

    httpretty.disable()
    httpretty.reset()
コード例 #4
0
ファイル: __init__.py プロジェクト: fevers/tinify-python
    def tearDown(self):
        httpretty.disable()
        httpretty.reset()

        tinify.app_identifier = None
        tinify.key = None
        tinify.compression_count
コード例 #5
0
ファイル: test_common.py プロジェクト: EclecticIQ/cabby
def test_set_headers(version):
    httpretty.reset()
    httpretty.enable()

    uri = get_fix(version).DISCOVERY_URI_HTTP
    response = get_fix(version).DISCOVERY_RESPONSE

    register_uri(uri, response, version)

    client = make_client(
        version,
        headers={CUSTOM_HEADER_NAME: CUSTOM_HEADER_VALUE})

    services = client.discover_services(uri=uri)

    assert len(services) == 4

    message = get_sent_message(version)
    assert type(message) == (tm11 if version == 11 else tm10).DiscoveryRequest

    last_request = httpretty.last_request()

    assert CUSTOM_HEADER_NAME in last_request.headers
    assert last_request.headers[CUSTOM_HEADER_NAME] == CUSTOM_HEADER_VALUE

    httpretty.disable()
    httpretty.reset()
コード例 #6
0
 def test_expired(self):
     httpretty.disable()
     req = webob.Request.blank('/')
     token = self.token_dict['signed_token_scoped_expired']
     req.headers['X-Auth-Token'] = token
     self.middleware(req.environ, self.start_fake_response)
     self.assertEqual(self.response_status, 401)
コード例 #7
0
def test_known_pull_request_task(app, owner, repository, session):
    """Task pull_request /pulls/1 that already exists."""
    httpretty.reset()
    cs1 = CommitStatus(repository,
                       "1",
                       "https://github.com/pulls/1",
                       {"message": [], "files": {}})
    cs2 = CommitStatus(repository,
                       "2",
                       "https://github.com/pulls/2",
                       {"message": [], "files": {}})
    session.add(cs1)
    session.add(cs2)
    session.commit()

    bs = BranchStatus(cs2,
                      "test:my-branch",
                      "https://github.com/pulls/1",
                      {"commits": [cs1, cs2], "files": {}})
    session.add(bs)
    session.commit()
    assert_that(bs.is_pending(), equal_to(False))

    httpretty.enable()
    pull_request(bs.id,
                 "https://api.github.com/pulls/1",
                 "http://kwalitee.invenio-software.org/status/2",
                 {"ACCESS_TOKEN": "deadbeef"})
    httpretty.disable()

    latest_requests = httpretty.HTTPretty.latest_requests
    assert_that(len(latest_requests), equal_to(0),
                "No requests are expected")
コード例 #8
0
    def test_bad_verification_code(self):
        # Test redirect
        resp = self.client.get(
            url_for("oauthclient.login", remote_app='github')
        )
        self.assertStatus(resp, 302)
        assert resp.location.startswith(
            "https://github.com/login/oauth/authorize"
        )

        httpretty.enable()
        fixtures.register_github_api()

        # Test restart of auth flow when getting a bad_verification_code
        resp = self.client.get(
            url_for(
                "oauthclient.authorized",
                remote_app='github',
                code='bad_verification_code'
            )
        )

        assert resp.status_code == 302
        assert resp.location.endswith(
            url_for('oauthclient.login', remote_app='github')
        )

        httpretty.disable()
        httpretty.reset()
コード例 #9
0
def test_bad_verification_code(app, db):
    with app.test_request_context():
        # Test redirect
        client = app.test_client()
        resp = client.get(
            url_for('invenio_oauthclient.login', remote_app='github')
        )
        assert resp.status_code == 302
        assert resp.location.startswith(
            'https://github.com/login/oauth/authorize'
        )
        state = get_state(resp.location)

        httpretty.enable()
        fixtures.register_github_api()

        # Test restart of auth flow when getting a bad_verification_code
        resp = client.get(
            url_for(
                'invenio_oauthclient.authorized',
                remote_app='github',
                code='bad_verification_code',
                state=state,
            )
        )

        assert resp.status_code == 302
        # assert resp.location.endswith(
        #     url_for('invenio_oauthclient.login', remote_app='github')
        # )

    httpretty.disable()
    httpretty.reset()
コード例 #10
0
ファイル: test_bypass.py プロジェクト: Charlesdong/HTTPretty
def test_httpretty_bypasses_when_disabled(context):
    "httpretty should bypass all requests by disabling it"

    httpretty.register_uri(
        httpretty.GET, "http://localhost:9999/go-for-bubbles/",
        body="glub glub")

    httpretty.disable()

    fd = urllib2.urlopen('http://localhost:9999/go-for-bubbles/')
    got1 = fd.read()
    fd.close()

    expect(got1).to.equal(
        b'. o O 0 O o . o O 0 O o . o O 0 O o . o O 0 O o . o O 0 O o .')

    fd = urllib2.urlopen('http://localhost:9999/come-again/')
    got2 = fd.read()
    fd.close()

    expect(got2).to.equal(b'<- HELLO WORLD ->')

    httpretty.enable()

    fd = urllib2.urlopen('http://localhost:9999/go-for-bubbles/')
    got3 = fd.read()
    fd.close()

    expect(got3).to.equal(b'glub glub')
    core.POTENTIAL_HTTP_PORTS.remove(9999)
コード例 #11
0
ファイル: test_conversations.py プロジェクト: UPCnet/maxbunny
    def test_missing_domain_missing_default(self):
        """
            Given a message with no domain specified
            And there is no default domain specified
            When the message is processed
            Then an exception is raised
            And the push message is not queued
        """
        from maxbunny.consumers.conversations import __consumer__
        from maxbunny.tests.mockers.conversations import MISSING_DOMAIN_MESSAGE as message

        self.set_server({}, None)

        httpretty.enable()
        http_mock_info()

        runner = MockRunner('conversations', 'maxbunny.ini', 'instances.ini')
        consumer = __consumer__(runner)

        self.assertRaisesWithMessage(
            BunnyMessageCancel,
            'Missing domain, and default could not be loaded',
            consumer.process,
            message
        )

        httpretty.disable()
        httpretty.reset()

        sleep(0.1)  # Leave a minimum time to message to reach rabbitmq
        messages = self.server.get_all('push')
        self.assertEqual(len(messages), 0)
コード例 #12
0
ファイル: test_conversations.py プロジェクト: UPCnet/maxbunny
    def test_message_with_domain(self):
        """
            Given a message with a domain specified
            And that domain exists in the list of known domains
            When the message is processed
            Then the message is posted
            And the push message is queued
        """
        from maxbunny.consumers.conversations import __consumer__
        from maxbunny.tests.mockers.conversations import CONVERSATION_MESSAGE as message
        message_id = '00000000001'

        self.set_server(message, message_id)

        httpretty.enable()

        http_mock_info()
        http_mock_post_user_message(uri='tests.local', message_id=message_id)

        runner = MockRunner('conversations', 'maxbunny.ini', 'instances2.ini')
        consumer = __consumer__(runner)

        consumer.process(message)

        httpretty.disable()
        httpretty.reset()

        sleep(0.1)  # Leave a minimum time to message to reach rabbitmq
        messages = self.server.get_all('push')
        self.assertEqual(len(messages), 1)

        self.assertEqual(messages[0][0]['a'], 'k')
        self.assertEqual(messages[0][0]['o'], 'm')
        self.assertEqual(messages[0][0]['s'], 'b')
        self.assertEqual(messages[0][0]['d']['id'], '00000000001')
コード例 #13
0
ファイル: json.py プロジェクト: chihongze/girlfriend
 def tearDown(self):
     os.remove("line_file.json")
     os.remove("array_file.json")
     os.remove("object_file.json")
     os.remove("block_file.json")
     httpretty.disable()
     httpretty.reset()
コード例 #14
0
ファイル: test_conversations.py プロジェクト: UPCnet/maxbunny
    def test_invalid_message_unknown_domain(self):
        """
            Given a message with a domain specified
            And that domain doesn't match any of the known domains
            When the message is processed
            Then an exception is raised
            And the push message is not queued
        """

        from maxbunny.consumers.conversations import __consumer__
        from maxbunny.tests.mockers.conversations import UNKNOWN_DOMAIN_MESSAGE as message

        self.set_server({}, None)

        httpretty.enable()
        http_mock_info()

        runner = MockRunner('conversations', 'maxbunny.ini', 'instances2.ini')
        consumer = __consumer__(runner)

        self.assertRaisesWithMessage(
            BunnyMessageCancel,
            'Unknown domain "unknown"',
            consumer.process,
            message
        )

        httpretty.disable()
        httpretty.reset()

        sleep(0.1)  # Leave a minimum time to message to reach rabbitmq
        messages = self.server.get_all('push')
        self.assertEqual(len(messages), 0)
コード例 #15
0
def test_for_name_similarity_required_parameters(api, json_response):
    httpretty.enable()
    httpretty.register_uri(httpretty.POST, "https://api.rosette.com/rest/v1/info",
                           body=json_response, status=200, content_type="application/json")
    httpretty.register_uri(httpretty.POST, "https://api.rosette.com/rest/v1/name-similarity",
                           body=json_response, status=200, content_type="application/json")

    matched_name_data1 = "Michael Jackson"
    matched_name_data2 = "迈克尔·杰克逊"
    params = NameSimilarityParameters()

    with pytest.raises(RosetteException) as e_rosette:
        result = api.name_similarity(params)

    assert e_rosette.value.status == 'missingParameter'
    assert e_rosette.value.message == 'Required Name Similarity parameter not supplied'

    params["name1"] = {
        "text": matched_name_data1,
        "language": "eng",
        "entityType": "PERSON"}
    with pytest.raises(RosetteException) as e_rosette:
        result = api.name_similarity(params)

    assert e_rosette.value.status == 'missingParameter'
    assert e_rosette.value.message == 'Required Name Similarity parameter not supplied'

    params["name2"] = {"text": matched_name_data2, "entityType": "PERSON"}

    result = api.name_similarity(params)
    assert result["name"] == "Rosette API"
    httpretty.disable()
    httpretty.reset()
コード例 #16
0
def test_for_name_translation_required_parameters(api, json_response):
    httpretty.enable()
    httpretty.register_uri(httpretty.POST, "https://api.rosette.com/rest/v1/info",
                           body=json_response, status=200, content_type="application/json")
    httpretty.register_uri(httpretty.POST, "https://api.rosette.com/rest/v1/name-translation",
                           body=json_response, status=200, content_type="application/json")

    params = NameTranslationParameters()
    params["entityType"] = "PERSON"
    params["targetScript"] = "Latn"

    with pytest.raises(RosetteException) as e_rosette:
        result = api.name_translation(params)

    assert e_rosette.value.status == 'missingParameter'
    assert e_rosette.value.message == 'Required Name Translation parameter not supplied'

    params["name"] = "some data to translate"

    with pytest.raises(RosetteException) as e_rosette:
        result = api.name_translation(params)

    assert e_rosette.value.status == 'missingParameter'
    assert e_rosette.value.message == 'Required Name Translation parameter not supplied'

    params["targetLanguage"] = "eng"

    result = api.name_translation(params)
    assert result["name"] == "Rosette API"

    httpretty.disable()
    httpretty.reset()
コード例 #17
0
    def test_is_referenced(self):
        uri = 'http://id.erfgoed.net/foobar/2'
        url = 'http://localhost:6543'
        from pyramid_urireferencer.renderers import registry_adapter
        reg_response_success_ref1 = registry_adapter(RegistryResponse(uri, True, False, 0, []), {})

        referencer = TestReferencer(url)
        self.assertIsNone(referencer.references(uri, 'test'))
        response = referencer.is_referenced(uri)
        self.assertIsInstance(response, RegistryResponse)
        self.assertEqual(response.success, False)

        httpretty.enable()  # enable HTTPretty so that it will monkey patch the socket module
        httpretty.register_uri(
            httpretty.GET,
            '{0}/references?{1}'.format(url, urlencode({'uri': uri})),
            body=json.dumps(reg_response_success_ref1),
            content_type="application/json"
        )

        response = referencer.is_referenced(uri)
        self.assertIsInstance(response, RegistryResponse)
        self.assertTrue(response.success)

        httpretty.disable()  # disable afterwards, so that you will have no problems in code that uses that socket module
        httpretty.reset()
コード例 #18
0
def httpretty():
    """Prepares the httpretty module for the HTTP tests in this suite"""
    import httpretty

    httpretty.enable()
    yield httpretty
    httpretty.disable()
コード例 #19
0
ファイル: protocol_test.py プロジェクト: robcza/gglsbl3
    def test_retrieve_missing_chunks(self):
        httpretty.enable()  # enable HTTPretty so that it will monkey patch the socket module
        try:
            existing_chunks = {'goog-malware-shavar': {'add': '160929-173975', 'sub': '151695-152051,152053-153220,153222-154217,154219-154240,154242-154260,154262-154638,154640-155042,155044-155415,155417-155505,155507-155706,155708-155768,155770-155781,155783-157480,157482-157623,157625-157836,157838-159256,159258-160279,160281-160909,160911-165040'}, 'googpub-phish-shavar': {'add': '325243-336324', 'sub': '20232-20239,20241-20251,20253-20254,20257-20258,20262-20264,20266,20268-20269,20272-20273,20275,20277-20278,20280,20282-20284,20286-20291,20293-20297,20300,20302-20309,20311,20314-20320,20322-20324,20326,20328-20330,20332-20333,20335-20336,20339-20341,20343-20344,20347,20349-20352,20354-20356,20358-20359,20361-20364,20366,20368-20375,20377-20378,20380-20381,20383-20384,20386-20396,20399-20404,20407-20411,20413-20416,20418-20429,20431-20438,20442-20459,20462-20479,20481-20490,20492-20494,20496-20500,20502-20506,20509,20511-20521,20523-20531,20533-20583,20585-20591,20593-20613,20615-20647,20649-20900,20902-20947,20949-20991,20993-21052,21054,21056-21176'}}
            url = "https://safebrowsing.google.com/safebrowsing/downloads"
            body = b'n:1704\ni:goog-malware-shavar\nu:safebrowsing-cache.google.com/safebrowsing/rd/ChNnb29nLW1hbHdhcmUtc2hhdmFyOAFAAkoMCAEQsYkKGLGJCiABSgwIABCYzwoYmM8KIAE\ni:googpub-phish-shavar\nu:safebrowsing-cache.google.com/safebrowsing/rd/ChRnb29ncHViLXBoaXNoLXNoYXZhcjgBQAJKDAgAEMXDFBjFwxQgAQ\n'
            httpretty.register_uri(httpretty.POST, url, body=body, status=200)

            mockchunks = [{"url": "https://safebrowsing-cache.google.com/safebrowsing/rd/ChNnb29nLW1hbHdhcmUtc2hhdmFyOAFAAkoMCAEQsYkKGLGJCiABSgwIABCYzwoYmM8KIAE", "body": b'\x00\x00\x004\x08\xb1\x89\n\x10\x01"\x18\xcc\xbdS\xfa:\xb7\x1d\xa3\xd1R&\xde\xca\x1a\x92\xfb\x84Wy\x7fI5\xba\xe0*\x12\x97\xcd\n\xec\x8f\n\xf5\x9a\n\xe3\xf8\t\xc8\xfe\t\xb9\xb6\n\x00\x00\x00\x0e\x08\x98\xcf\n"\x08\xca\x8eoj$\x19ro'},
                      {"url": "https://safebrowsing-cache.google.com/safebrowsing/rd/ChRnb29ncHViLXBoaXNoLXNoYXZhcjgBQAJKDAgAEMXDFBjFwxQgAQ", "body": b'\x00\x00\x00Z\x08\xc5\xc3\x14"T\xa3p\xda\x91l\xa9\xa5\xa89SOl\x12,\x0bXB0\xed\x1f\x114b2\xf2\x8b\x9a\xeb\xf4\xb6\xc1f\xe6\x80!\x81\xdd\xc4\xb5O\xfa\xfdKS\x03<\x97\xfb\x83\xb6\r\xfa\xfe\x15$\xa0\xa7C\xd4W\xd8\x029\xad\x03\xf9r\x0c/d\xb8jz\xc6\xaf4qQ\xccQ/1\xb3\xc3'}
                      ]
            for mockchunk in mockchunks:
                log.debug("adding url {url} and body {body}".format(url=mockchunk['url'][:10], body=mockchunk['body'][:10]))
                httpretty.register_uri(httpretty.POST, mockchunk['url'], body=mockchunk['body'], status=200)
                httpretty.register_uri(httpretty.GET, mockchunk['url'], body=mockchunk['body'], status=200)
            response = self.client.retrieve_missing_chunks(existing_chunks)
            log.debug("RESPONSE: {res}".format(res=response))
            log.debug("chunks: {res}".format(res=response.chunks))
            chunks = []
            for chunk in response.chunks:
                log.debug("--- CHUNK --- {chunktype} {chunk}".format(chunktype=chunk.chunk_type, chunk=chunk.chunk_number))
                chunks.append({"number": chunk.chunk_number, "type": chunk.chunk_type})
            assert_in({'type': 'add', 'number': 336325}, chunks)
            assert_in({'type': 'sub', 'number': 165041}, chunks)
            assert_in({'type': 'add', 'number': 173976}, chunks)
            log.info("got chunks: {chunks}".format(chunks=chunks))
            log.debug("response: {res}".format(res=response))
        except Exception:
            raise
        finally:
            httpretty.disable()
            httpretty.reset()
コード例 #20
0
ファイル: test_baseapi.py プロジェクト: butangero/pypuppetdb
 def test_metric(self, baseapi):
     httpretty.enable()
     stub_request('http://localhost:8080/v3/metrics/mbean/test')
     baseapi.metric('test')
     assert httpretty.last_request().path == '/v3/metrics/mbean/test'
     httpretty.disable()
     httpretty.reset()
コード例 #21
0
def test_create_badge(app):
    """Test create_badge method."""
    badge_url = "%sDOI-10.1234%%2Ffoo.bar-blue.svg?style=flat" % \
        app.config["GITHUB_SHIELDSIO_BASE_URL"]

    httpretty.enable()
    httpretty.register_uri(
        httpretty.GET,
        badge_url,
        body=SVG,
        content_type="image/svg+xml",
    )

    output = os.path.join(app.instance_path, "test.svg")

    create_badge(
        "DOI",
        "10.1234/foo.bar",
        "blue",
        output,
        style="flat",
    )

    assert os.path.exists(output)
    httpretty.disable()
コード例 #22
0
ファイル: test_baseapi.py プロジェクト: butangero/pypuppetdb
 def test_with_path(self, baseapi):
     httpretty.enable()
     stub_request('http://localhost:8080/v3/nodes/node1')
     baseapi._query('nodes', path='node1')
     assert httpretty.last_request().path == '/v3/nodes/node1'
     httpretty.disable()
     httpretty.reset()
コード例 #23
0
ファイル: test_baseapi.py プロジェクト: bootc/pypuppetdb
 def test_environments(self, baseapi):
     httpretty.enable()
     stub_request('http://localhost:8080/pdb/query/v4/environments')
     baseapi.environments()
     assert httpretty.last_request().path == '/pdb/query/v4/environments'
     httpretty.disable()
     httpretty.reset()
コード例 #24
0
ファイル: test_core.py プロジェクト: vsudilov/flask-consulate
    def test_session(self):
        """
        Ensures that the session has the expected connectivity
        """
        httpretty.enable()

        httpretty.register_uri(
            httpretty.GET,
            'http://consul.internal:8501/v1/status/leader',
            body="localhost:8300",
        )
        app = self.create_app()
        consul = Consul(
            app,
            consul_host='consul.internal',
            consul_port='8501',
            test_connection=True
        )
        self.assertIsNotNone(consul)

        httpretty.disable()
        httpretty.reset()

        app = self.create_app()
        self.assertRaises(
            ConsulConnectionError,
            lambda: Consul(
                app,
                consul_host='consul.internal',
                consul_port='8501',
                test_connection=True
            ),
        )
コード例 #25
0
def mock_icon_urls():
    httpretty.enable()
    httpretty.HTTPretty.allow_net_connect = False

    # smallest valid png, from https://github.com/mathiasbynens/small/blob/master/png-transparent.png
    httpretty.register_uri(
        httpretty.GET,
        PROPER_ICON_URL,
        body=b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00\x1f\x15\xc4\x89\x00\x00\x00\nIDATx\x9cc\x00\x01\x00\x00\x05\x00\x01\r\n-\xb4\x00\x00\x00\x00IEND\xaeB`\x82',
        content_type='image/png'
    )
    httpretty.register_uri(
        httpretty.GET,
        IMPROPER_ICON_URL,
        body=b'\n\n\n\n\n\n<!DOCTYPE html>\n<html lang="en">\n  <head>\n',
        content_type='text/html'
    )
    httpretty.register_uri(
        httpretty.GET,
        INVALID_URL
    )
    httpretty.register_uri(
        httpretty.GET,
        TIMEOUT_URL,
        body=exceptionCallback
    )
    yield
    httpretty.disable()
コード例 #26
0
ファイル: test_baseapi.py プロジェクト: bootc/pypuppetdb
 def test_fact_names(self, baseapi):
     httpretty.enable()
     stub_request('http://localhost:8080/pdb/query/v4/fact-names')
     baseapi.fact_names()
     assert httpretty.last_request().path == '/pdb/query/v4/fact-names'
     httpretty.disable()
     httpretty.reset()
コード例 #27
0
ファイル: fixtures.py プロジェクト: EnTeQuAk/doit
def moves_auth():
    httpretty.enable()

    def _method(method):
        return {"GET": httpretty.GET, "POST": httpretty.POST}[method]

    strategy = DjangoStrategy(MovesOAuth2, DjangoStorage)

    start_url = strategy.start().url

    target_url = handle_state(MovesOAuth2, start_url, strategy.build_absolute_uri("/complete/{0}/?code=foobar"))

    httpretty.register_uri(httpretty.GET, start_url, status=301, location=target_url)

    httpretty.register_uri(httpretty.GET, target_url, status=200, body="foobar")

    httpretty.register_uri(
        _method(MovesOAuth2.ACCESS_TOKEN_METHOD),
        uri=MovesOAuth2.ACCESS_TOKEN_URL,
        status=200,
        body=json.dumps({"access_token": "foobar", "token_type": "bearer"}),
        content_type="text/json",
    )

    user_data_url = "https://api.moves-app.com.com/oauth2/v1/user/profile"

    if user_data_url:
        httpretty.register_uri(
            httpretty.GET, user_data_url, body=json.dumps({"userId": "1010101010011"}), content_type="application/json"
        )

    yield

    httpretty.disable()
    httpretty.reset()
コード例 #28
0
 def tearDown(self):
     """ Tear down test.
     """
     httpretty.disable()
     httpretty.reset()
     if os.path.exists('output_test'):
         shutil.rmtree('output_test')
コード例 #29
0
def test_query_api_timeout_connection_error(monkeypatch, request, app, timeout):
    """Test if API is unresponsive.

    Asserting line number of: response = requests.get(url, headers=headers, timeout=timeout)

    :param monkeypatch: pytest fixture.
    :param request: pytest fixture.
    :param app: conftest fixture.
    :param bool timeout: Test timeout instead of connection error.
    """
    # Listen on a random port.
    httpretty.disable()
    server = socket.socket()
    server.bind(('127.0.0.1', 0))
    server.listen(1)
    api_url = 'https://%s/{type}/{id}' % '{}:{}'.format(*server.getsockname())
    if timeout:
        request.addfinalizer(lambda: server.close())
    else:
        server.close()  # Opened just to get unused port number.
    monkeypatch.setattr('sphinxcontrib.imgur.imgur_api.API_URL', api_url)

    # Test.
    with pytest.raises(APIError):
        query_api(app, 'client_id', 'imgur_id', False)

    # Verify log.
    if timeout:
        assert app.messages[-1][1].startswith('timed out waiting for reply from http')
    else:
        assert app.messages[-1][1].startswith('unable to connect to http')
    assert re.search(r'sphinxcontrib[/\\]imgur[/\\]imgur_api\.pyc?:51', app.messages[-1][2])
コード例 #30
0
 def callback(http_request, uri, headers):
     httpretty.disable()
     response = testypie.get_response(uri, http_request.headers)
     headers.update({key.lower(): value for key, value in
                     response['headers'].iteritems()})
     httpretty.enable()
     return response['code'], headers, response['body'].encode('utf-8')
コード例 #31
0
def patch_get():
    httpretty.enable()
    yield partial(httpretty.register_uri, httpretty.GET)
    httpretty.disable()
    httpretty.reset()
コード例 #32
0
 def tearDown(self):
     httpretty.disable()
     super(TestImageCache, self).tearDown()
コード例 #33
0
 def tearDown(self):
     httpretty.disable()
     self.processor.cleanup()
コード例 #34
0
 def tearDown(self):
     httpretty.disable()
     httpretty.reset()
コード例 #35
0
 def tearDown(self):
     super().tearDown()
     URLLibInstrumentor().uninstrument()
     httpretty.disable()
コード例 #36
0
    def test_upsert_dataset_nama_10_fcs(self):

        # nosetests -s -v dlstats.tests.fetchers.test_eurostat:FetcherTestCase.test_upsert_dataset_nama_10_fcs

        httpretty.enable()

        dataset_code = "nama_10_fcs"
        self.DATASETS[dataset_code]["DSD"].update(
            LOCAL_DATASETS_UPDATE[dataset_code])
        self._load_files_datatree(TOC_FP)
        self._load_files(dataset_code)

        self.assertProvider()
        self.assertDataset(dataset_code)
        self.assertSeries(dataset_code)
        '''Reload upsert_dataset for normal fail'''
        with self.assertRaises(RejectUpdatedDataset) as err:
            self.fetcher.upsert_dataset(dataset_code)
        self.assertEqual(err.exception.comments,
                         "update-date[2015-10-26 00:00:00]")
        '''Verify last_update in category for this dataset'''
        category = Categories.search_category_for_dataset(
            self.fetcher.provider_name, dataset_code, self.db)
        self.assertIsNotNone(category)
        last_update = None
        for d in category["datasets"]:
            if d["dataset_code"] == dataset_code:
                last_update = d["last_update"]
        self.assertIsNotNone(last_update)
        self.assertEqual(str(last_update), "2015-10-26 00:00:00")
        last_update = None

        httpretty.reset()
        httpretty.disable()
        httpretty.enable()
        self._load_files(dataset_code)
        '''Change last_update in catalog.xml for force update dataset'''
        with open(TOC_FP, 'rb') as fp:
            toc = fp.read()
        self.assertFalse(b'27.10.2015' in toc)
        toc = toc.replace(b'26.10.2015', b'27.10.2015')
        self.assertTrue(b'27.10.2015' in toc)
        self._load_files_datatree(toc=toc)
        self.fetcher.provider.metadata["creation_date"] = datetime.datetime(
            1900, 1, 1)
        results = self.fetcher.upsert_data_tree(force_update=True)
        self.assertIsNotNone(results)
        self.fetcher.get_selected_datasets(force=True)

        query = {
            'provider_name': self.fetcher.provider_name,
            "dataset_code": dataset_code
        }
        _id = self.db[constants.COL_SERIES].find_one()["_id"]
        deleted = self.db[constants.COL_SERIES].delete_one({"_id": _id})
        self.assertEqual(deleted.deleted_count, 1)

        dataset_settings = self.fetcher.selected_datasets[dataset_code]
        self.assertEqual(dataset_settings["last_update"],
                         datetime.datetime(2015, 10, 27, 0, 0))

        result = self.fetcher.upsert_dataset(dataset_code)
        self.assertIsNotNone(result)  #_id du dataset
        dataset = self.db[constants.COL_DATASETS].find_one(query)
        self.assertIsNotNone(dataset)

        self.assertEqual(dataset["last_update"],
                         datetime.datetime(2015, 10, 27, 0, 0))

        #self.assertEqual(dataset["download_last"],
        #                 datetime.datetime(2015, 10, 27, 0, 0))

        httpretty.disable()
コード例 #37
0
 def tearDown(self):
     super(UserTests, self).tearDown()
     httpretty.disable()
     httpretty.reset()
コード例 #38
0
ファイル: helper.py プロジェクト: fooying/w3af
    def tearDown(self):
        self.w3afcore.quit()
        self.kb.cleanup()

        if self.MOCK_RESPONSES:
            httpretty.disable()
コード例 #39
0
def i_should_see_a_200_status_code_from_the_search_page(step):
    httpretty.disable()
    httpretty.reset()
    assert_equal(world.response_status_code, world.expected)
コード例 #40
0
 def httpretty_enabled():
     httpretty.HTTPretty.allow_net_connect = False
     httpretty.enable()
     yield
     httpretty.disable()
コード例 #41
0
def i_should_see_the_fake_content_i_created_in_the_response(step):
    httpretty.disable()
    httpretty.reset()
    assert_in('Hop on Pop', world.response_content)
コード例 #42
0
 def tearDown(self):
     super(ProgramsApiClientTests, self).tearDown()
     httpretty.disable()
     httpretty.reset()