Python httpretty 模块,enable() 实例源码

我们从Python开源项目中,提取了以下43个代码示例,用于说明如何使用httpretty.enable()

项目:girlfriend    作者:chihongze    | 项目源码 | 文件源码
def setUp(self):
        httpretty.enable()
        httpretty.register_uri(
            httpretty.GET, "http://test.gf/users",
            body=ujson.dumps([
                sam_profile,
                jack_profile,
            ]),
            content_type="application/json"
        )
        httpretty.register_uri(
            httpretty.GET, "http://test.gf/blog/sam",
            body=ujson.dumps(sams_articles),
            content_type="application/json"
        )
        httpretty.register_uri(
            httpretty.GET, "http://test.gf/blog/jack",
            body=ujson.dumps(jacks_articles),
            content_type="application/json"
        )
项目:desec-stack    作者:desec-io    | 项目源码 | 文件源码
def testCanDeleteOwnedDomain(self):
        httpretty.enable()
        httpretty.register_uri(httpretty.DELETE, settings.NSLORD_PDNS_API + '/zones/' + self.ownedDomains[1].name + '.')
        httpretty.register_uri(httpretty.DELETE, settings.NSMASTER_PDNS_API + '/zones/' + self.ownedDomains[1].name+ '.')

        url = reverse('domain-detail', args=(self.ownedDomains[1].pk,))
        response = self.client.delete(url)
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
        self.assertEqual(httpretty.last_request().method, 'DELETE')
        self.assertEqual(httpretty.last_request().headers['Host'], 'nsmaster:8081')

        httpretty.reset()
        httpretty.register_uri(httpretty.DELETE, settings.NSLORD_PDNS_API + '/zones/' + self.ownedDomains[1].name + '.')
        httpretty.register_uri(httpretty.DELETE, settings.NSMASTER_PDNS_API + '/zones/' + self.ownedDomains[1].name+ '.')

        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
        self.assertTrue(isinstance(httpretty.last_request(), httpretty.core.HTTPrettyRequestEmpty))
项目:desec-stack    作者:desec-io    | 项目源码 | 文件源码
def testCanPostReverseDomains(self):
        name = '0.8.0.0.0.1.c.a.2.4.6.0.c.e.e.d.4.4.0.1.a.0.1.0.8.f.4.0.1.0.a.2.ip6.arpa'

        httpretty.enable()
        httpretty.register_uri(httpretty.POST, settings.NSLORD_PDNS_API + '/zones', status=201)
        httpretty.register_uri(httpretty.GET,
                               settings.NSLORD_PDNS_API + '/zones/' + name + '.',
                               body='{"rrsets": []}',
                               content_type="application/json")
        httpretty.register_uri(httpretty.GET,
                               settings.NSLORD_PDNS_API + '/zones/' + name + './cryptokeys',
                               body='[]',
                               content_type="application/json")

        url = reverse('domain-list')
        data = {'name': name}
        response = self.client.post(url, data)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(len(mail.outbox), 0)
项目:desec-stack    作者:desec-io    | 项目源码 | 文件源码
def testCanDeleteOwnedDynDomain(self):
        httpretty.enable()
        httpretty.register_uri(httpretty.DELETE, settings.NSLORD_PDNS_API + '/zones/' + self.ownedDomains[1].name + '.')
        httpretty.register_uri(httpretty.DELETE, settings.NSMASTER_PDNS_API + '/zones/' + self.ownedDomains[1].name + '.')

        url = reverse('domain-detail', args=(self.ownedDomains[1].pk,))
        response = self.client.delete(url)
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)

        # FIXME In this testing scenario, the parent domain dedyn.io does not
        # have the proper NS and DS records set up, so we cannot test their
        # deletion.

        httpretty.reset()
        httpretty.register_uri(httpretty.DELETE, settings.NSLORD_PDNS_API + '/zones/' + self.ownedDomains[1].name + '.')
        httpretty.register_uri(httpretty.DELETE, settings.NSMASTER_PDNS_API + '/zones/' + self.ownedDomains[1].name+ '.')

        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
        self.assertTrue(isinstance(httpretty.last_request(), httpretty.core.HTTPrettyRequestEmpty))
项目:desec-stack    作者:desec-io    | 项目源码 | 文件源码
def setUp(self):
        if not hasattr(self, 'owner'):
            self.username = utils.generateRandomString(12)
            self.password = utils.generateRandomString(12)
            self.user = utils.createUser(self.username, self.password)
            self.token = utils.createToken(user=self.user)
            self.setCredentials(self.username, self.password)
            self.url = reverse('dyndns12update')

            self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token)
            self.domain = utils.generateDynDomainname()
            url = reverse('domain-list')
            data = {'name': self.domain}
            response = self.client.post(url, data)
            self.assertEqual(response.status_code, status.HTTP_201_CREATED)

            httpretty.enable()
            httpretty.register_uri(httpretty.POST, settings.NSLORD_PDNS_API + '/zones')
            httpretty.register_uri(httpretty.GET,
                                   settings.NSLORD_PDNS_API + '/zones/' + self.domain + '.',
                                   body='{"rrsets": []}',
                                   content_type="application/json")
            httpretty.register_uri(httpretty.PATCH, settings.NSLORD_PDNS_API + '/zones/' + self.domain + '.')
            httpretty.register_uri(httpretty.PUT, settings.NSLORD_PDNS_API + '/zones/' + self.domain + './notify')
项目:deb-python-httpretty    作者:openstack    | 项目源码 | 文件源码
def start_http_server(context):
    httpretty.disable()
    context.http_port = get_free_tcp_port()
    context.server = TornadoServer(context.http_port)
    context.server.start()
    ready = False
    timeout = 2
    started_at = time.time()
    while not ready:
        httpretty.disable()
        time.sleep(.1)
        try:
            requests.get('http://localhost:{0}/'.format(context.http_port))
            ready = True
        except:
            if time.time() - started_at >= timeout:
                break

    httpretty.enable()
项目:lecli    作者:rapid7    | 项目源码 | 文件源码
def setup_httpretty():
    httpretty.enable()
项目:presto-python-client    作者:prestodb    | 项目源码 | 文件源码
def test_request_timeout():
    timeout = 0.1
    http_scheme = 'http'
    host = 'coordinator'
    port = 8080
    url = http_scheme + '://' + host + ':' + str(port) + constants.URL_STATEMENT_PATH

    def long_call(request, uri, headers):
        time.sleep(timeout * 2)
        return (200, headers, "delayed success")

    httpretty.enable()
    for method in [httpretty.POST, httpretty.GET]:
        httpretty.register_uri(method, url, body=long_call)

    # timeout without retry
    for request_timeout in [timeout, (timeout, timeout)]:
        req = PrestoRequest(
            host=host,
            port=port,
            user='test',
            http_scheme=http_scheme,
            max_attempts=1,
            request_timeout=request_timeout,
        )

        with pytest.raises(requests.exceptions.Timeout):
            req.get(url)

        with pytest.raises(requests.exceptions.Timeout):
            req.post('select 1')

    httpretty.disable()
    httpretty.reset()
项目:girlfriend    作者:chihongze    | 项目源码 | 文件源码
def setUp(self):
        with open("line_file.json", "w") as f:
            f.write(JSON_LINE_CONTENT)
        with open("array_file.json", "w") as f:
            f.write(JSON_ARRAY_CONTENT)
        with open("object_file.json", "w") as f:
            f.write(JSON_OBJECT_CONTENT)
        with open("block_file.json", "w") as f:
            f.write(JSON_BLOCK_CONTENT)

        httpretty.enable()

        httpretty.register_uri(
            httpretty.GET,
            "http://test.gf/line",
            body=JSON_LINE_CONTENT,
            content_type="text/plain"
        )

        httpretty.register_uri(
            httpretty.GET,
            "http://test.gf/array",
            body=JSON_ARRAY_CONTENT,
            content_type="application/json"
        )

        httpretty.register_uri(
            httpretty.GET,
            "http://test.gf/object",
            body=JSON_OBJECT_CONTENT,
            content_type="application/json"
        )
项目:girlfriend    作者:chihongze    | 项目源码 | 文件源码
def setUp(self):
        self.records = [
            {"id": 1, "name": "Sam", "gender": 1},
            {"id": 2, "name": "Jack", "gender": 1},
            {"id": 3, "name": "Betty", "gender": 0},
        ]
        httpretty.enable()
项目:girlfriend    作者:chihongze    | 项目源码 | 文件源码
def setUp(self):
        with open("test.csv", "w") as f:
            f.write(CSV_CONTENT)

        httpretty.enable()

        httpretty.register_uri(
            httpretty.GET,
            "http://test.gf/csv",
            body=CSV_CONTENT,
            content_type="text/plain"
        )
项目:desec-stack    作者:desec-io    | 项目源码 | 文件源码
def testCantDeleteOtherDomains(self):
        httpretty.enable()
        httpretty.register_uri(httpretty.DELETE, settings.NSLORD_PDNS_API + '/zones/' + self.otherDomains[1].name + '.')
        httpretty.register_uri(httpretty.DELETE, settings.NSMASTER_PDNS_API + '/zones/' + self.otherDomains[1].name+ '.')

        url = reverse('domain-detail', args=(self.otherDomains[1].pk,))
        response = self.client.delete(url)
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
        self.assertTrue(isinstance(httpretty.last_request(), httpretty.core.HTTPrettyRequestEmpty))
        self.assertTrue(Domain.objects.filter(pk=self.otherDomains[1].pk).exists())
项目:desec-stack    作者:desec-io    | 项目源码 | 文件源码
def testCanGetOwnedDomains(self):
        httpretty.enable()
        httpretty.register_uri(httpretty.GET,
                               settings.NSLORD_PDNS_API + '/zones/' + self.ownedDomains[1].name + './cryptokeys',
                               body='[]',
                               content_type="application/json")

        url = reverse('domain-detail', args=(self.ownedDomains[1].pk,))
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data['name'], self.ownedDomains[1].name)
        self.assertTrue(isinstance(response.data['keys'], list))
项目:desec-stack    作者:desec-io    | 项目源码 | 文件源码
def testCantPostDomainAlreadyTakenInPdns(self):
        name = utils.generateDomainname()

        httpretty.enable()
        httpretty.register_uri(httpretty.POST, settings.NSLORD_PDNS_API + '/zones',
                               body='{"error": "Domain \'' + name + '.\' already exists"}', status=422)

        url = reverse('domain-list')
        data = {'name': name}
        response = self.client.post(url, data)
        self.assertEqual(response.status_code, status.HTTP_409_CONFLICT)
项目:desec-stack    作者:desec-io    | 项目源码 | 文件源码
def testRollback(self):
        name = utils.generateDomainname()

        httpretty.enable()
        httpretty.register_uri(httpretty.POST, settings.NSLORD_PDNS_API + '/zones', body="some error", status=500)

        url = reverse('domain-list')
        data = {'name': name}
        self.client.post(url, data)

        self.assertFalse(Domain.objects.filter(name=name).exists())
项目:desec-stack    作者:desec-io    | 项目源码 | 文件源码
def testCantDeleteOtherDynDomains(self):
        httpretty.enable()
        httpretty.register_uri(httpretty.DELETE, settings.NSLORD_PDNS_API + '/zones/' + self.otherDomains[1].name + '.')
        httpretty.register_uri(httpretty.DELETE, settings.NSMASTER_PDNS_API + '/zones/' + self.otherDomains[1].name+ '.')

        url = reverse('domain-detail', args=(self.otherDomains[1].pk,))
        response = self.client.delete(url)
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
        self.assertTrue(isinstance(httpretty.last_request(), httpretty.core.HTTPrettyRequestEmpty))
        self.assertTrue(Domain.objects.filter(pk=self.otherDomains[1].pk).exists())
项目:desec-stack    作者:desec-io    | 项目源码 | 文件源码
def testLimitDynDomains(self):
        httpretty.enable()
        httpretty.register_uri(httpretty.POST, settings.NSLORD_PDNS_API + '/zones')

        outboxlen = len(mail.outbox)

        url = reverse('domain-list')
        for i in range(settings.LIMIT_USER_DOMAIN_COUNT_DEFAULT-2):
            name = utils.generateDynDomainname()

            httpretty.register_uri(httpretty.GET,
                                   settings.NSLORD_PDNS_API + '/zones/' + name + '.',
                                   body='{"rrsets": []}',
                                   content_type="application/json")
            httpretty.register_uri(httpretty.GET,
                                   settings.NSLORD_PDNS_API + '/zones/' + name + './cryptokeys',
                                   body='[]',
                                   content_type="application/json")

            response = self.client.post(url, {'name': name})
            self.assertEqual(response.status_code, status.HTTP_201_CREATED)
            self.assertEqual(len(mail.outbox), outboxlen+i+1)

        data = {'name': utils.generateDynDomainname()}
        response = self.client.post(url, data)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        self.assertEqual(len(mail.outbox), outboxlen + settings.LIMIT_USER_DOMAIN_COUNT_DEFAULT-2)
项目:desec-stack    作者:desec-io    | 项目源码 | 文件源码
def testDeleteCausesPdnsAPICall(self):
        httpretty.enable()
        httpretty.register_uri(httpretty.PATCH, settings.NSLORD_PDNS_API + '/zones/' + self.ownedDomains[1].name + '.')
        httpretty.register_uri(httpretty.PUT, settings.NSLORD_PDNS_API + '/zones/' + self.ownedDomains[1].name + './notify')

        # Create record, should cause a pdns PATCH request and a notify
        url = reverse('rrsets', args=(self.ownedDomains[1].name,))
        data = {'records': ['1.2.3.4'], 'ttl': 60, 'type': 'A'}
        self.client.post(url, json.dumps(data), content_type='application/json')

        # Delete record, should cause a pdns PATCH request and a notify
        url = reverse('rrset', args=(self.ownedDomains[1].name, '', 'A',))
        response = self.client.delete(url)
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)

        # Check pdns requests from creation
        result = json.loads(httpretty.httpretty.latest_requests[-4].parsed_body)
        self.assertEqual(result['rrsets'][0]['name'], self.ownedDomains[1].name + '.')
        self.assertEqual(result['rrsets'][0]['records'][0]['content'], '1.2.3.4')
        self.assertEqual(httpretty.httpretty.latest_requests[-3].method, 'PUT')

        # Check pdns requests from deletion
        result = json.loads(httpretty.httpretty.latest_requests[-2].parsed_body)
        self.assertEqual(result['rrsets'][0]['name'], self.ownedDomains[1].name + '.')
        self.assertEqual(result['rrsets'][0]['records'], [])
        self.assertEqual(httpretty.httpretty.latest_requests[-1].method, 'PUT')
项目:desec-stack    作者:desec-io    | 项目源码 | 文件源码
def setUp(self):
        self.owner = utils.createUser()
        self.token = utils.createToken(user=self.owner)
        self.domain = utils.generateDynDomainname()
        self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token)

        url = reverse('domain-list')
        data = {'name': self.domain}
        response = self.client.post(url, data)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

        self.username = response.data['name']
        self.password = self.token
        self.client.credentials(HTTP_AUTHORIZATION='Basic ' + base64.b64encode((self.username + ':' + self.password).encode()).decode())

        httpretty.enable()
        httpretty.HTTPretty.allow_net_connect = False
        httpretty.register_uri(httpretty.POST, settings.NSLORD_PDNS_API + '/zones')
        httpretty.register_uri(httpretty.PATCH, settings.NSLORD_PDNS_API + '/zones/' + self.domain + '.')
        httpretty.register_uri(httpretty.GET,
                               settings.NSLORD_PDNS_API + '/zones/' + self.domain + '.',
                               body='{"rrsets": []}',
                               content_type="application/json")
        httpretty.register_uri(httpretty.GET,
                               settings.NSLORD_PDNS_API + '/zones/' + self.domain + './cryptokeys',
                               body='[]',
                               content_type="application/json")
        httpretty.register_uri(httpretty.PUT, settings.NSLORD_PDNS_API + '/zones/' + self.domain + './notify')
项目:dati-ckan-docker    作者:italia    | 项目源码 | 文件源码
def _patched_get_content_and_type(self, url, harvest_job, page=1, content_type=None):

    httpretty.enable()

    value1, value2 = original_get_content_and_type(self, url, harvest_job, page, content_type)

    httpretty.disable()

    return value1, value2
项目:cloudstrype    作者:btimby    | 项目源码 | 文件源码
def setUp(self):
        httpretty.enable()
        httpretty.register_uri(
            httpretty.POST, self.oauth2_client.ACCESS_TOKEN_URL,
            body=json.dumps(ACCESS_TOKEN),
            content_type='application/json')
项目:cloudstrype    作者:btimby    | 项目源码 | 文件源码
def setUp(self):
        httpretty.enable()
        httpretty.register_uri(
            httpretty.POST, self.oauth2_client.ACCESS_TOKEN_URL,
            body=json.dumps(ACCESS_TOKEN),
            content_type='application/json')
项目:cloudstrype    作者:btimby    | 项目源码 | 文件源码
def setUp(self):
        httpretty.enable()
        httpretty.register_uri(
            httpretty.POST, self.oauth2_client.ACCESS_TOKEN_URL,
            body=json.dumps(ACCESS_TOKEN),
            content_type='application/json')
项目:simple-environment-monitor-system    作者:diegorubin    | 项目源码 | 文件源码
def setUp(self):
        httpretty.enable()
        httpretty.register_uri(httpretty.GET, SERVICE_URL, body="LIVE")
项目:simple-environment-monitor-system    作者:diegorubin    | 项目源码 | 文件源码
def test_alive(self):
        httpretty.enable()
        httpretty.register_uri(httpretty.GET, SERVICE_URL, body="LIVE")

        monitor = SocketPortMonitor(SERVICE_HOST, port=SERVICE_PORT);
        self.assertTrue(monitor.alive())

        httpretty.disable()
        httpretty.reset()
项目:simple-environment-monitor-system    作者:diegorubin    | 项目源码 | 文件源码
def test_check_alive(self):
        httpretty.enable()
        httpretty.register_uri(httpretty.GET, SERVICE_URL, body="LIVE")

        self.assertTrue(check_alive('SocketPortMonitor', SERVICE_HOST, port='8888'))

        httpretty.disable()
        httpretty.reset()
项目:simple-environment-monitor-system    作者:diegorubin    | 项目源码 | 文件源码
def setUp(self):
        httpretty.enable()
项目:postman-audit    作者:tylrd    | 项目源码 | 文件源码
def setup_function(function):
    httpretty.enable()
    register_collections_meta()
    register_collections()
项目:postman-audit    作者:tylrd    | 项目源码 | 文件源码
def setup_function(function):
    httpretty.enable()
    register_collections_meta()
    register_collections()
项目:rakuten-ws    作者:alexandriagroup    | 项目源码 | 文件源码
def httpretty():
    httpretty_module.reset()
    httpretty_module.enable()
    yield httpretty_module
    httpretty_module.disable()
项目:concourse-resource-bitbucket    作者:Karunamon    | 项目源码 | 文件源码
def step_impl(context):
    d = context.bad_login
    assert d['source']['username'] != 'ValidUser'
    httpretty.enable()
    httpretty.register_uri(
            httpretty.POST,
            context.good_build_url,
            body='{"errors":[{"context":null,"message":"Authentication failed. Please check your credentials and try again.","exceptionName":"com.atlassian.bitbucket.auth.IncorrectPasswordAuthenticationException"}]}',
            status=401
    )
    from scripts.bitbucket import post_result, err
    result = post_result(context.good_build_url, d['source']['username'], d['source']['password'], False, good_status_dict(), True)
    assert result.status_code == 401
    httpretty.disable()
    httpretty.reset()
项目:concourse-resource-bitbucket    作者:Karunamon    | 项目源码 | 文件源码
def step_impl(context):
    d = context.good_login
    assert context.good_login['source']['username'] == 'ValidUser'
    httpretty.enable()
    httpretty.register_uri(
            httpretty.POST,
            context.bad_build_url,
            body='{"errors":[{"context":null,"message":"You are not permitted to access this resource","exceptionName":"com.atlassian.bitbucket.AuthorisationException"}]}',
            status=403
    )
    from scripts.bitbucket import post_result, err
    result = post_result(context.bad_build_url, d['source']['username'], d['source']['password'], False, good_status_dict(), True)
    assert result.status_code == 403
    httpretty.disable()
    httpretty.reset()
项目:concourse-resource-bitbucket    作者:Karunamon    | 项目源码 | 文件源码
def step_impl(context):
    d = context.good_login
    assert context.good_login['source']['username'] == 'ValidUser'
    assert 'somethingicantaccess' not in context.good_build_url
    httpretty.enable()
    httpretty.register_uri(
            httpretty.POST,
            context.good_build_url,
            status=204
    )
    from scripts.bitbucket import post_result, err
    result = post_result(context.good_build_url, d['source']['username'], d['source']['password'], False, good_status_dict(), True)
    assert result.status_code == 204
    context.goodresult = result
项目:evologger    作者:freeranger    | 项目源码 | 文件源码
def setUp(self):
        with open('mock_data/account_info.json') as data_file:
            raw_account_info = data_file.read()
        self.account_info = json.loads(raw_account_info)

        with open('mock_data/' + self.installation_file_name) as data_file:
            raw_installation_data = data_file.read()
        self.installation_info = json.loads(raw_installation_data)

        with open('mock_data/location_1_status.json') as data_file:
            raw_location_1_status = data_file.read()
        self.location_1_status = json.loads(raw_location_1_status)

        with open('mock_data/location_2_status.json') as data_file:
            raw_location_2_status = data_file.read()
        self.location_2_status = json.loads(raw_location_2_status)

        httpretty.enable()
        httpretty.register_uri(httpretty.POST, "https://tccna.honeywell.com/Auth/OAuth/Token",
                               body='{"access_token": "TEST_TOKEN"}',
                               content_type="application/json")
        httpretty.register_uri(httpretty.GET, "https://tccna.honeywell.com/WebAPI/emea/api/v1/userAccount",
                               body=raw_account_info,
                               content_type="application/json")
        httpretty.register_uri(httpretty.GET,
                               "https://tccna.honeywell.com/WebAPI/emea/api/v1/location/installationInfo?userId=%s&includeTemperatureControlSystems=True" %
                               self.account_info["userId"],
                               body=raw_installation_data,
                               content_type="application/json")
        httpretty.register_uri(httpretty.GET,
                               "https://tccna.honeywell.com/WebAPI/emea/api/v1/location/1/status?includeTemperatureControlSystems=True",
                               body=raw_location_1_status)

        httpretty.register_uri(httpretty.GET,
                              "https://tccna.honeywell.com/WebAPI/emea/api/v1/location/2/status?includeTemperatureControlSystems=True",
                              body=raw_location_2_status)
项目:Startup-Fairy    作者:cs373gc-fall-2016    | 项目源码 | 文件源码
def setUp(self):
        """About tests have no database component"""

        httpretty.enable()  # enable HTTPretty so that it will monkey patch the socket module
        httpretty.register_uri(httpretty.GET, "http://yipit.com/",
                               body="Find the best daily deals")
项目:ouroboros    作者:madedotcom    | 项目源码 | 文件源码
def start_mocking_http(self):
        self.host = "fake-eventstore.com"
        self.port = 12345
        self.client = Client(self.host, self.port, "admin", "changeit", no_ssl=True)
        httpretty.enable()
项目:deb-python-httpretty    作者:openstack    | 项目源码 | 文件源码
def stop_http_server(context):
    context.server.stop()
    httpretty.enable()
项目:deb-python-httpretty    作者:openstack    | 项目源码 | 文件源码
def start_tcp_server(context):
    context.tcp_port = get_free_tcp_port()
    context.server = TCPServer(context.tcp_port)
    context.server.start()
    context.client = TCPClient(context.tcp_port)
    httpretty.enable()
项目:deb-python-httpretty    作者:openstack    | 项目源码 | 文件源码
def stop_tcp_server(context):
    context.server.stop()
    context.client.close()
    httpretty.enable()
项目:deb-python-httpretty    作者:openstack    | 项目源码 | 文件源码
def test_httpretty_bypasses_when_disabled(context):
    "httpretty should bypass all requests by disabling it"

    httpretty.register_uri(
        httpretty.GET, "http://localhost:{0}/go-for-bubbles/".format(context.http_port),
        body="glub glub")

    httpretty.disable()

    fd = urllib2.urlopen('http://localhost:{0}/go-for-bubbles/'.format(context.http_port))
    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:{0}/come-again/'.format(context.http_port))
    got2 = fd.read()
    fd.close()

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

    httpretty.enable()

    fd = urllib2.urlopen('http://localhost:{0}/go-for-bubbles/'.format(context.http_port))
    got3 = fd.read()
    fd.close()

    expect(got3).to.equal(b'glub glub')
    core.POTENTIAL_HTTP_PORTS.remove(context.http_port)
项目:quizlet    作者:s-alexey    | 项目源码 | 文件源码
def setUp(self):
        httpretty.enable()
项目:swagger-stub    作者:Trax-air    | 项目源码 | 文件源码
def swagger_stub(swagger_files_url):
    """Fixture to stub a microservice from swagger files.

    To use this fixture you need to define a swagger fixture named
    swagger_files_url with the path to your swagger files, and the url to stub.
    Then just add this fixture to your tests and your request pointing to the
    urls in swagger_files_url will be managed by the stub.

    Example:
        @pytest.fixture
        def swagger_files_url():
            return [('tests/swagger.yaml', 'http://localhost:8000')]
    """
    httpretty.enable()

    for i in swagger_files_url:  # Get all given swagger files and url
        base_url = i[1]
        s = SwaggerParser(i[0])
        swagger_url[base_url] = s

        # Register all urls
        httpretty.register_uri(
            httpretty.GET, re.compile(base_url + r'/.*'),
            body=get_data_from_request)

        httpretty.register_uri(
            httpretty.POST, re.compile(base_url + r'/.*'),
            body=get_data_from_request)

        httpretty.register_uri(
            httpretty.PUT, re.compile(base_url + r'/.*'),
            body=get_data_from_request)

        httpretty.register_uri(
            httpretty.PATCH, re.compile(base_url + r'/.*'),
            body=get_data_from_request)

        httpretty.register_uri(
            httpretty.DELETE, re.compile(base_url + r'/.*'),
            body=get_data_from_request)

        memory[base_url] = StubMemory(s)
        yield memory[base_url]

    # Close httpretty
    httpretty.disable()
    httpretty.reset()
项目:egasub    作者:icgc-dcc    | 项目源码 | 文件源码
def mock_server(ctx):
    httpretty.enable()

    httpretty.register_uri(httpretty.POST,"%slogin" % (ctx.obj['SETTINGS']['apiUrl']),
                       body='{"header":{"code" : "200"},"response" : {"result" : [ { "session" : { "sessionToken":"abcdefg" }}]}}',
                       content_type="application/json")

    httpretty.register_uri(httpretty.POST,"%ssubmissions" % (ctx.obj['SETTINGS']['apiUrl']),
                       body='{"header" : {"code" : "200"}, "response" : {"result" : [{ "id":"12345" }]}}',
                       content_type="application/json")

    httpretty.register_uri(httpretty.DELETE, "%slogout" % (ctx.obj['SETTINGS']['apiUrl']),
                       content_type="application/json")

    httpretty.register_uri(httpretty.POST, "%ssubmissions/12345/studies" % (ctx.obj['SETTINGS']['apiUrl']),
                           body='{"header" : {"code" : "200"}, "response" : {"result" : [{ "id":"6789" }]}}',
                   content_type="application/json")

    httpretty.register_uri(httpretty.PUT, "%sstudies/6789?action=VALIDATE" % (ctx.obj['SETTINGS']['apiUrl']),
                           body='{"header" : {"code" : "200"}, "response" : {"result" : [{ "id":"12345" }]}}',
                   content_type="application/json")

    httpretty.register_uri(httpretty.GET, "%sstudies/test_alias?idType=ALIAS" % (ctx.obj['SETTINGS']['apiUrl']),
                           body='{"header" : {"code" : "200"}, "response" : {"result" : [{ "id":"12345" }]}}',
                   content_type="application/json")

    httpretty.register_uri(httpretty.GET, "%ssamples/sample_alias?idType=ALIAS&skip=0&limit=0" % (ctx.obj['SETTINGS']['apiUrl']),
                            body='{"header" : {"code" : "200"}, "response" : {"result" : [{ "id":"12345" }]}}',
                   content_type="application/json")

    httpretty.register_uri(httpretty.GET, "%sdatasets/dataset_alias?idType=ALIAS&skip=0&limit=0" % (ctx.obj['SETTINGS']['apiUrl']),
                            body='{"header" : {"code" : "200"}, "response" : {"result" : [{ "id":"12345" }]}}',
                   content_type="application/json")

    httpretty.register_uri(httpretty.GET, "%spolicies/policy_alias?idType=ALIAS&skip=0&limit=0" % (ctx.obj['SETTINGS']['apiUrl']),
                            body='{"header" : {"code" : "200"}, "response" : {"result" : [{ "id":"12345" }]}}',
                   content_type="application/json")

    httpretty.register_uri(httpretty.GET, "%ssamples?status=SUBMITTED&skip=0&limit=0" % (ctx.obj['SETTINGS']['apiUrl']),
                            body='{"header" : {"code" : "200"}, "response" : {"result" : [{ "id":"12345" }]}}',
                   content_type="application/json")

    httpretty.register_uri(httpretty.GET, "%sstudies?status=SUBMITTED&skip=0&limit=0" % (ctx.obj['SETTINGS']['apiUrl']),
                            body='{"header" : {"code" : "200"}, "response" : {"result" : [{ "id":"12345" }]}}',
                   content_type="application/json")

    httpretty.register_uri(httpretty.GET, "%sstudies?status=SUBMITTED&skip=0&limit=0" % (ctx.obj['SETTINGS']['apiUrl']),
                            body='{"header" : {"code" : "200"}, "response" : {"result" : [{ "id":"12345" }]}}',
                   content_type="application/json")

    httpretty.register_uri(httpretty.GET, "%spolicies?status=SUBMITTED&skip=0&limit=0" % (ctx.obj['SETTINGS']['apiUrl']),
                            body='{"header" : {"code" : "200"}, "response" : {"result" : [{ "id":"12345" }]}}',
                   content_type="application/json")

    httpretty.register_uri(httpretty.GET, "%sdatasets?status=SUBMITTED&skip=0&limit=0" % (ctx.obj['SETTINGS']['apiUrl']),
                            body='{"header" : {"code" : "200"}, "response" : {"result" : [{ "id":"12345" }]}}',
                   content_type="application/json")

    httpretty.register_uri(httpretty.DELETE, "%ssamples?status=SUBMITTED&skip=0&limit=0" % (ctx.obj['SETTINGS']['apiUrl']),
                            body='{"header" : {"code" : "200"}, "response" : {"result" : [{ "id":"12345" }]}}',
                   content_type="application/json")