def setup_method(self, method): httpretty.enable() httpretty.reset() httpretty.register_uri( httpretty.POST, 'http://%s:8181/api/osd/configure/' % INSTALL_HOST, body=self.post_request_callback, content_type='application/json') self.requests = []
def setUp(self): """ Set up test. """ self.url_queue = Queue.Queue() self.crawled_urls = set() self.mini_spider_thread = mini_spider.MiniSpiderThread(self.url_queue, self.crawled_urls, 6, 2, 5, '.*\.(gif|png|jpg|bmp)$', './output_test') self.url_obj = mini_spider.Url('http://example.com/iterate_next_urls/html_webpage', 0) httpretty.enable() httpretty.register_uri(httpretty.GET, 'http://example.com/graburl/success', body = 'Grab url success.') httpretty.register_uri(httpretty.GET, 'http://example.com/graburl/fail', status = 404) httpretty.register_uri(httpretty.GET, 'http://example.com/savewebpage/saved.txt', body = 'Saved webpage content.') httpretty.register_uri(httpretty.GET, 'http://example.com/iterate_next_urls/html_webpage', content_type = 'text/html', body = '<a href="/test/test1.html">Link</a>\ <img src="/test/test3.png" /><script src="/test/test4.js"></script>') httpretty.register_uri(httpretty.GET, 'http://example.com/iterate_next_urls/not_html_webpage', content_type = 'text/plain', body = '/test/not_html.txt')
def setup_mangle(cmd_args): if cmd_args.mangle_function is not None: # We need to verify that the user configured function exists try: mangle_module_funct = cmd_args.mangle_function mangle_module = '.'.join(mangle_module_funct.split('.')[:-1]) mangle_funct = mangle_module_funct.split('.')[-1] _temp = __import__(mangle_module, globals(), locals(), ['mangle_funct'], -1) mangle_funct = getattr(_temp, mangle_funct) except: msg = 'The user configured mangle function %s does not exist.' logging.critical(msg % mangle_funct) sys.exit(1) if VULN_URL is None: logging.critical('URL mangling to access remote instance meta-data'\ ' requires you to code your own mangle function'\ ' and configure it.') sys.exit(1) # enable HTTPretty so that it will monkey patch the socket module httpretty.enable() httpretty.register_uri(httpretty.GET, re.compile("http://169.254.169.254/(.*)"), body=mangle_funct)
def setUp(self): unittest.TestCase.setUp(self) self.__fileName = "" self.__file = None if self.recordMode: # pragma no cover (Branch useful only when recording new tests, not used during automated tests) github.Requester.Requester.injectConnectionClasses( lambda ignored, *args, **kwds: RecordingHttpConnection(self.__openFile("wb"), *args, **kwds), lambda ignored, *args, **kwds: RecordingHttpsConnection(self.__openFile("wb"), *args, **kwds) ) import GithubCredentials self.login = GithubCredentials.login self.password = GithubCredentials.password self.oauth_token = GithubCredentials.oauth_token self.jwt = GithubCredentials.jwt # @todo Remove client_id and client_secret from ReplayData (as we already remove login, password and oauth_token) # self.client_id = GithubCredentials.client_id # self.client_secret = GithubCredentials.client_secret else: github.Requester.Requester.injectConnectionClasses( lambda ignored, *args, **kwds: ReplayingHttpConnection(self, self.__openFile("rb"), *args, **kwds), lambda ignored, *args, **kwds: ReplayingHttpsConnection(self, self.__openFile("rb"), *args, **kwds) ) self.login = "******" self.password = "******" self.oauth_token = "oauth_token" self.client_id = "client_id" self.client_secret = "client_secret" self.jwt = "jwt" httpretty.enable(allow_net_connect=False)
def setUp(self): def _api_callback(request, uri, headers): code = 200 method = request.querystring['method'][0] if method == 'flickr.people.getPublicPhotos': body = fixtures.GET_PUBLIC_PHOTOS elif method == 'flickr.photos.getInfo': if request.querystring['photo_id'][0] == BAD_FILE_ID: body = fixtures.GET_PHOTO_NOT_FOUND else: body = fixtures.GET_PHOTO return (code, headers, body) def _upload_callback(request, uri, headers): code = 200 if request.querystring['title'][0] == 'EMPTY_FILE': body = fixtures.UPLOAD_FILESIZE_ERROR else: body = fixtures.UPLOAD_OK return (code, headers, body) httpretty.enable() httpretty.register_uri(httpretty.GET, FlickrStorage.API_ENDPOINT, body=_api_callback, content_type='text/json') httpretty.register_uri(httpretty.POST, FlickrStorage.API_POST_URL, body=_upload_callback) self.storage = FlickrStorage(api_key=API_KEY, api_secret=API_SECRET, oauth_token=OAUTH_TOKEN, oauth_token_secret=OAUTH_TOKEN_SECRET, user_id=USER_ID)
def setUp(self): super(SamlIntegrationTestUtilities, self).setUp() self.enable_saml( private_key=self._get_private_key(), public_key=self._get_public_key(), entity_id="https://saml.example.none", ) # Mock out HTTP requests that may be made to TestShib: httpretty.enable() def metadata_callback(_request, _uri, headers): """ Return a cached copy of TestShib's metadata by reading it from disk """ return (200, headers, self.read_data_file('testshib_metadata.xml')) httpretty.register_uri(httpretty.GET, TESTSHIB_METADATA_URL, content_type='text/xml', body=metadata_callback) def cache_duration_metadata_callback(_request, _uri, headers): """Return a cached copy of TestShib's metadata with a cacheDuration attribute""" return (200, headers, self.read_data_file('testshib_metadata_with_cache_duration.xml')) httpretty.register_uri( httpretty.GET, TESTSHIB_METADATA_URL_WITH_CACHE_DURATION, content_type='text/xml', body=cache_duration_metadata_callback ) self.addCleanup(httpretty.disable) self.addCleanup(httpretty.reset) # Configure the SAML library to use the same request ID for every request. # Doing this and freezing the time allows us to play back recorded request/response pairs uid_patch = patch('onelogin.saml2.utils.OneLogin_Saml2_Utils.generate_unique_id', return_value='TESTID') uid_patch.start() self.addCleanup(uid_patch.stop) self._freeze_time(timestamp=1434326820) # This is the time when the saved request/response was recorded.
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()
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()
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()
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()
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()
def i_have_imitated_a_working_search_service_from_pubs(step): world.search_url = search_url world.recent_pub = {'records': [ {'seriesTitle': {'text': 'Das Boot'}, 'publicationYear': '2021', 'seriesNumber': 14, 'chapter': 18, 'subChapter': 4, 'links': [ { "id": 5398296, "type": { "id": 24, "text": "Thumbnail" }, "url": "http://pubs.er.usgs.gov/thumbnails/usgs_thumb.jpg" } ] } ], 'recordCount': 1 } httpretty.enable() httpretty.register_uri(httpretty.GET, world.search_url, body=json.dumps(world.recent_pub), content_type='application/json', status_code=200 )
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()
def test_response_empty(self, baseapi): httpretty.enable() httpretty.register_uri(httpretty.GET, 'http://localhost:8080/pdb/query/v4/nodes', body=json.dumps(None)) with pytest.raises(pypuppetdb.errors.EmptyResponseError): baseapi._query('nodes')
def test_extract_metadata(self): from ..tasks import extract_metadata from ..helpers import get_api gh = get_api(user_id=self.user.id) # Mock up responses httpretty.enable() fixtures.register_endpoint( "/repos/auser/repo-2", fixtures.REPO('auser', 'repo-2'), ) fixtures.register_endpoint( "/repos/auser/repo-2/contents/.zenodo.json", fixtures.CONTENT( 'auser', 'repo-2', '.zenodo.json', 'v1.0', json.dumps(dict( upload_type='dataset', license='mit-license', creators=[ dict(name='Smith, Joe', affiliation='CERN'), dict(name='Smith, Joe', affiliation='CERN') ] )) ) ) metadata = extract_metadata( gh, fixtures.PAYLOAD('auser', 'repo-2', tag='v1.0'), ) assert metadata['upload_type'] == 'dataset'
def setUp(self): """Setup httpretty; create ARI client. """ super(AriTestCase, self).setUp() httpretty.enable() self.serve_api() self.uut = ari.connect('http://ari.py/', 'test', 'test')
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 ), )
def test_handle_payload(self): from zenodo.modules.github.tasks import handle_github_payload from invenio.modules.webhooks.models import Event httpretty.enable() extra_data = self.remote_token.remote_account.extra_data assert 'auser/repo-1' in extra_data['repos'] assert 'auser/repo-2' in extra_data['repos'] assert len(extra_data['repos']['auser/repo-1']['depositions']) == 0 assert len(extra_data['repos']['auser/repo-2']['depositions']) == 0 e = Event( user_id=self.user.id, payload=fixtures.PAYLOAD('auser', 'repo-1') ) handle_github_payload(e.__getstate__()) db.session.expire(self.remote_token.remote_account) extra_data = self.remote_token.remote_account.extra_data assert len(extra_data['repos']['auser/repo-1']['depositions']) == 1 assert len(extra_data['repos']['auser/repo-2']['depositions']) == 0 dep = extra_data['repos']['auser/repo-1']['depositions'][0] assert dep['doi'].endswith(six.text_type(dep['record_id'])) assert dep['errors'] is None assert dep['github_ref'] == "v1.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")
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()
def setUp(self): self.url = "http://m.sacrt.com/bdetails.aspx?stpid=1788&route=38" self.HTML = """blah blah blah <div>Vehicle 3815 arriving in 7 minutes </div> blah blah blah""" httpretty.enable() httpretty.register_uri(httpretty.GET, self.url, status=200, body=self.HTML)
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)
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()
def setUp(self): super(ThreadSerializerDeserializationTest, self).setUp() httpretty.reset() httpretty.enable() self.addCleanup(httpretty.reset) self.addCleanup(httpretty.disable) self.user = UserFactory.create() self.register_get_user_response(self.user) self.request = RequestFactory().get("/dummy") self.request.user = self.user self.minimal_data = { "course_id": unicode(self.course.id), "topic_id": "test_topic", "type": "discussion", "title": "Test Title", "raw_body": "Test body", } self.existing_thread = Thread(**make_minimal_cs_thread({ "id": "existing_thread", "course_id": unicode(self.course.id), "commentable_id": "original_topic", "thread_type": "discussion", "title": "Original Title", "body": "Original body", "user_id": str(self.user.id), "username": self.user.username, "read": "False", "endorsed": "False" }))
def setUp(self): super(TestMockedRequests, self).setUp() httpretty.enable() httpretty.register_uri(httpretty.GET, "https://pypi.python.org/pypi/Django/json", status=200, body='{"info": {"version": "1.9"}}', content_type="text/json") httpretty.register_uri(httpretty.GET, "https://pypi.python.org/pypi/djangorestframework/json", status=200, body='{"info": {"version": "3.3.2"}}', content_type="text/json") httpretty.register_uri(httpretty.GET, "https://pypi.python.org/pypi/drfdocs/json", status=200, body='{"info": {"version": "0.0.5"}}', content_type="text/json") httpretty.register_uri(httpretty.GET, "https://pypi.python.org/pypi/testing-errors-abc/json", status=404, body='Not found.', content_type="text/json")
def setUp(self): # pre-diablo only had Tenant ID, which was also the Name expected_env = { 'HTTP_X_TENANT_ID': 'tenant_id1', 'HTTP_X_TENANT_NAME': 'tenant_id1', # now deprecated (diablo-compat) 'HTTP_X_TENANT': 'tenant_id1', } super(DiabloAuthTokenMiddlewareTest, self).setUp( expected_env=expected_env) httpretty.httpretty.reset() httpretty.enable() httpretty.register_uri(httpretty.GET, "%s/" % BASE_URI, body=VERSION_LIST_v2, status=300) httpretty.register_uri(httpretty.POST, "%s/v2.0/tokens" % BASE_URI, body=FAKE_ADMIN_TOKEN) self.token_id = client_fixtures.VALID_DIABLO_TOKEN token_response = client_fixtures.JSON_TOKEN_RESPONSES[self.token_id] httpretty.register_uri(httpretty.GET, "%s/v2.0/tokens/%s" % (BASE_URI, self.token_id), body=token_response) self.set_middleware()
def httprettified(request): """ pytest style fixture to activate/deactive httpretty so that you get the benefit of the @httpretty.activate decoratator without having to use it. Basically, this won't work: @httpretty.activate def test_foo(some_pytest_fixture): pass Use this instead: def test_foo(httprettified, some_pytest_fixture): # interactions with httpretty occur as if you'd decorated # this function with @httpretty.activate httpretty.register_uri(...) If you're passing multiple fixtures to the test that rely on httpretty being activated, make sure that `httprettified` is before all the other fixtures that depend on it. :param request: This is a pytest (confusingly named) param. Don't worry about it. """ # TODO: move to test util package httpretty.reset() httpretty.enable() def fin(): httpretty.disable() request.addfinalizer(fin)
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()
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()
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()
def setUp(self): content_type = 'application/json; charset=utf-8' httpretty.enable() with open(FILE_POPULAR) as h: httpretty.register_uri(httpretty.GET, meme.POPULAR_URL, body=h.read(), content_type=content_type) with open(FILE_SEARCH) as h: httpretty.register_uri(httpretty.GET, meme.SEARCH_URL, body=h.read(), content_type=content_type) with open(FILE_ACTION_RESULT) as h: httpretty.register_uri(httpretty.GET, meme.ACTION_URL, body=h.read(), content_type=content_type) with open(FILE_INFO) as h: httpretty.register_uri(httpretty.GET, meme.INFO_URL, body=h.read(), content_type=content_type)
def setUp(self): """ Initialize the configuration """ Cache.last_updated[APIURL] = {'__oldest': '2016-12-18T11:49:37Z'} httpretty.reset() httpretty.enable() oscrc = os.path.join(FIXTURES, 'oscrc') osc.core.conf.get_config(override_conffile=oscrc, override_no_keyring=True, override_no_gnome_keyring=True) #osc.conf.config['debug'] = 1 logging.basicConfig() self.logger = logging.getLogger(__file__) self.logger.setLevel(logging.DEBUG) self.checker = FactorySourceChecker(apiurl = APIURL, \ user = '******', \ logger = self.logger) self.checker.override_allow = False # Test setup cannot handle.
def test_the_name_translation_endpoint(api, json_response): """Test the name translation endpoint""" 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["name"] = "some data to translate" params["entityType"] = "PERSON" params["targetLanguage"] = "eng" params["targetScript"] = "Latn" result = api.name_translation(params) assert result["name"] == "Rosette" httpretty.disable() httpretty.reset()
def setUp(self): super(TestShibIntegrationTest, self).setUp() self.enable_saml( private_key=self._get_private_key(), public_key=self._get_public_key(), entity_id="https://saml.example.none", ) # Mock out HTTP requests that may be made to TestShib: httpretty.enable() def metadata_callback(_request, _uri, headers): """ Return a cached copy of TestShib's metadata by reading it from disk """ return (200, headers, self.read_data_file('testshib_metadata.xml')) httpretty.register_uri(httpretty.GET, TESTSHIB_METADATA_URL, content_type='text/xml', body=metadata_callback) self.addCleanup(httpretty.disable) self.addCleanup(httpretty.reset) # Configure the SAML library to use the same request ID for every request. # Doing this and freezing the time allows us to play back recorded request/response pairs uid_patch = patch('onelogin.saml2.utils.OneLogin_Saml2_Utils.generate_unique_id', return_value='TESTID') uid_patch.start() self.addCleanup(uid_patch.stop) self._freeze_time(timestamp=1434326820) # This is the time when the saved request/response was recorded.
def setUp(self): super().setUp() httpretty.reset() httpretty.enable() self.addCleanup(httpretty.reset) self.addCleanup(httpretty.disable) self.user = UserFactory.create() self.register_get_user_response(self.user) self.request = RequestFactory().get("/dummy") self.request.user = self.user self.minimal_data = { "thread_id": "test_thread", "raw_body": "Test body", } self.existing_comment = Comment( **make_minimal_cs_comment({ "id": "existing_comment", "thread_id": "existing_thread", "body": "Original body", "user_id": str(self.user.id), "username": self.user.username, "course_id": str(self.course.id), }))
def test_post_cut(self): client = Client('https://httpbin.org/post', 'https://httpbin.org/post', directory) content = { "to_cut": { "start_time": "16/12/2018 00:51:54;16", "end_time": "16/12/2018 01:38:24;0", "title": "SUP - (DES)ENCONTRO PERFEITO - S", "duration": "00:46:29;15", "reconcile_key": "20181215234" } } path = {"video_path": client.video_path} content.update(path) httpretty.enable() httpretty.register_uri(httpretty.POST, "https://httpbin.org/post", body=json.dumps(content)) response = client.post_cut(json.dumps(content)) self.assertEqual(response.status_code, 200) self.assertEqual(response.json(), content) httpretty.disable() httpretty.reset()
def start_http_server(context): if httpretty.httpretty._is_enabled: allow_net_connect = httpretty.httpretty.allow_net_connect else: allow_net_connect = True 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:{}/'.format(context.http_port)) ready = True except (Exception, BaseException): if time.time() - started_at >= timeout: break httpretty.enable(allow_net_connect=allow_net_connect)
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()
def test_user__username_with_accents(self): httpretty.enable() from osmtm.models import User, DBSession import transaction userid = 12 username = u'new_user_éà' user = User(userid, username) DBSession.add(user) DBSession.flush() transaction.commit() httpretty.register_uri( httpretty.GET, "http://www.openstreetmap.org/api/0.6/user/%s" % userid, body='<?xml version="1.0" encoding="UTF-8"?>' + '<osm> <user display_name="%s"></user></osm>' % username, content_type='application/xml; charset=utf-8') headers = self.login_as_user(userid) self.testapp.get('/project/1/task/4/lock', status=200, headers=headers, xhr=True) self.testapp.get('/project/1/task/4/done', status=200, headers=headers, params={'comment': 'some_comment'}, xhr=True) self.testapp.get((u'/user/%s' % username).encode('utf8'), status=200) self.testapp.get('/project/1/task/4', status=200, headers=headers, xhr=True)
def test_rollback_templating_definition_inside(): """Test spintest with templating inside rollback.""" httpretty.enable() httpretty.register_uri(httpretty.POST, "http://test.com/test", status=500) httpretty.register_uri( httpretty.GET, "http://test.com/test", body=json.dumps({"foo": "bar"}), status=200, ) httpretty.register_uri(httpretty.DELETE, "http://test.com/bar", status=204) spintest( ["http://test.com"], [{ "method": "POST", "route": "/test", "rollback": [ { "method": "GET", "route": "/test", "output": "test" }, { "method": "DELETE", "route": "/{{ test['foo'] }}" }, ], }], ) assert httpretty.last_request().method == httpretty.DELETE httpretty.disable() httpretty.reset()
def test_task_with_fix_token_set_configuration(): """Test spintest with a strict match on custom body.""" httpretty.enable() httpretty.register_uri( httpretty.GET, "http://test.com/test", body=json.dumps({ "a": "a", "b": "b", "c": "c" }), status=200, ) result = spintest( ["http://test.com"], [{ "method": "GET", "route": "/test", "expected": { "code": 200, "body": { "a": "a", "b": "b", "c": "c" }, "expected_match": "strict", }, }], token="ABC", ) assert True is result httpretty.disable() httpretty.reset()
def setUp(self): super().setUp() self.__fileName = "" self.__file = None if ( self.recordMode ): # pragma no cover (Branch useful only when recording new tests, not used during automated tests) github.Requester.Requester.injectConnectionClasses( lambda ignored, *args, **kwds: RecordingHttpConnection( self.__openFile("w"), *args, **kwds), lambda ignored, *args, **kwds: RecordingHttpsConnection( self.__openFile("w"), *args, **kwds), ) import GithubCredentials # type: ignore self.login = GithubCredentials.login self.password = GithubCredentials.password self.oauth_token = GithubCredentials.oauth_token self.jwt = GithubCredentials.jwt # @todo Remove client_id and client_secret from ReplayData (as we already remove login, password and oauth_token) # self.client_id = GithubCredentials.client_id # self.client_secret = GithubCredentials.client_secret else: github.Requester.Requester.injectConnectionClasses( lambda ignored, *args, **kwds: ReplayingHttpConnection( self.__openFile("r"), *args, **kwds), lambda ignored, *args, **kwds: ReplayingHttpsConnection( self.__openFile("r"), *args, **kwds), ) self.login = "******" self.password = "******" self.oauth_token = "oauth_token" self.client_id = "client_id" self.client_secret = "client_secret" self.jwt = "jwt" httpretty.enable(allow_net_connect=False)
def test_task_with_ignore_option_followed_by_error(): """Test spintest with ignore option.""" httpretty.enable() httpretty.register_uri(httpretty.GET, "http://test.com/test", status=500) result = spintest( ["http://test.com"], [ { "method": "GET", "route": "/test", "ignore": True }, { "method": "GET", "route": "/test" }, ], ) assert False is result httpretty.disable() httpretty.reset()
def setUp(self): self.kb.cleanup() self.w3afcore = w3afCore() self.request_callback_call_count = 0 self.request_callback_match = 0 if self.MOCK_RESPONSES: httpretty.reset() httpretty.enable() try: url = URL(self.target_url) except ValueError, ve: msg = ('When using MOCK_RESPONSES you need to set the' ' target_url attribute to a valid URL, exception was:' ' "%s".') raise Exception(msg % ve) domain = url.get_domain() proto = url.get_protocol() port = url.get_port() self._register_httpretty_uri(proto, domain, port)
def test_two_tokens_are_generated_with_one_task_with_two_retry(): httpretty.enable() httpretty.register_uri( httpretty.GET, "http://test.com/test", status=200, body=json.dumps({"status": "CREATED"}), ) httpretty.register_uri( httpretty.GET, "http://test.com/test", status=200, body=json.dumps({"status": "CREATING"}), ) loop = asyncio.new_event_loop() token_func = FakeCreatedToken() manager = TaskManager( ["http://test.com"], [{ "method": "GET", "route": "/test", "expected": { "body": { "status": "CREATED" } }, "retry": 1, }], token=token_func, ) result = loop.run_until_complete(manager.next()) assert "SUCCESS" == result["status"] assert token_func.call_count == 2 httpretty.disable() httpretty.reset()
def test_metric_v2_version_string(self, baseapi): metrics_body = { 'request': { 'mbean': 'test:name=Num', 'type': 'read' }, 'value': { 'Value': 0 }, 'timestamp': 0, 'status': 200 } httpretty.enable() httpretty.register_uri( httpretty.GET, 'http://localhost:8080/metrics/v2/read/test:name=Num', body=json.dumps(metrics_body)) metric = baseapi.metric('test:name=Num', version='v2') assert httpretty.last_request( ).path == '/metrics/v2/read/test%3Aname%3DNum' assert metric['Value'] == 0 httpretty.disable() httpretty.reset()
def setUp(self): self.flask_app_obj = app self.app = self.flask_app_obj.test_client() httpretty.enable() self.response_count = 0 self.error_count = 0 def callback(request, uri, headers): self.assertEqual(request.body.decode('utf8'), test_file) for expected_header, value in expected_forwarding_headers.items(): self.assertIn(expected_header, request.headers) self.assertEqual(request.headers[expected_header], value) self.response_count += 1 return (202, headers, "") def err_callback(request, uri, headers): self.error_count += 1 return (200, headers, "") httpretty.register_uri(httpretty.POST, re.compile("example.com/(.*)$"), body=callback) httpretty.register_uri(httpretty.POST, re.compile("errors.com/(.*)$"), body=callback)
def setup(self): httpretty.enable() self.key = RSAKey(kid='testkey').load(os.path.join(FIXTURE_ROOT, 'testkey.pem')) def jwks(_request, _uri, headers): # noqa: E306 ks = KEYS() ks.add(self.key.serialize()) return 200, headers, ks.dump_jwks() httpretty.register_uri( httpretty.GET, oidc_rp_settings.PROVIDER_JWKS_ENDPOINT, status=200, body=jwks) httpretty.register_uri( httpretty.POST, oidc_rp_settings.PROVIDER_TOKEN_ENDPOINT, body=json.dumps({ 'id_token': self.generate_jws(), 'access_token': 'accesstoken', 'refresh_token': 'refreshtoken', }), content_type='text/json') httpretty.register_uri( httpretty.GET, oidc_rp_settings.PROVIDER_USERINFO_ENDPOINT, body=json.dumps({'sub': '1234', 'email': '*****@*****.**', }), content_type='text/json') yield httpretty.disable()
def test_invalid_response(version): httpretty.reset() httpretty.enable() uri = get_fix(version).DISCOVERY_URI_HTTP # FIXME: httpretty returns body as byte string (utf-8 encoded) # and when libtaxii tries to join headers (unicode) with the body (binary) # error happens. Line in Libtaxii codebase # https://github.com/EclecticIQ/libtaxii/blob/master/libtaxii/__init__.py#L126 return httpretty.register_uri(httpretty.POST, uri, body='INVALID-BODY', content_type='text/html') client = make_client(version) with pytest.raises(exc.InvalidResponseError): client.discover_services(uri=uri) httpretty.disable() httpretty.reset()
def setUp(self): super(TestHelper, self).setUp() self.group_id = "7d16eb9a779611e5a957ecf4bb625d2e" self.principle = "*****@*****.**" self.password = "******" self.alert_config_id = "53888cefe4b0d94f32b74eed" self.url_base = "https://cloud.mongodb.com/api/public/v1.0/groups/{group_id}".format( group_id=self.group_id) api = cm_api.Api(self.group_id, self.principle, self.password) self.api = api with open(JSON_DATA, 'r') as data: self.api_data = json.load(data) httpretty.enable() for k, v in self.api_data.iteritems(): httpretty.register_uri(httpretty.GET, self.url_base + v['href'], body=json.dumps(v['response']), content_type="application/json")
def setup_google_recaptcha_response(self): """Set up a mock google recaptcha api""" # httpretty socket blocks if enabled before calling self.get_csrf() ! httpretty.enable() url = current_app.config['GOOGLE_RECAPTCHA_ENDPOINT'] def callback(request, uri, headers): 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(httpretty.POST, url, body=callback, content_type='application/json')
def setUp(self): super(CommentViewSetPartialUpdateTest, self).setUp() httpretty.reset() httpretty.enable() self.addCleanup(httpretty.disable) self.register_get_user_response(self.user) self.url = reverse("comment-detail", kwargs={"comment_id": "test_comment"}) cs_thread = make_minimal_cs_thread({ "id": "test_thread", "course_id": unicode(self.course.id), }) self.register_get_thread_response(cs_thread) cs_comment = make_minimal_cs_comment({ "id": "test_comment", "course_id": cs_thread["course_id"], "thread_id": cs_thread["id"], "username": self.user.username, "user_id": str(self.user.id), "created_at": "2015-06-03T00:00:00Z", "updated_at": "2015-06-03T00:00:00Z", "body": "Original body", }) self.register_get_comment_response(cs_comment) self.register_put_comment_response(cs_comment)
def setUp(self) -> None: # https://github.com/gabrielfalcao/HTTPretty/issues/368 import warnings warnings.filterwarnings("ignore", category=ResourceWarning, message="unclosed.*") warnings.filterwarnings("ignore", category=PendingDeprecationWarning, message="isAlive*") httpretty.enable() httpretty.reset() conf = influxdb_client.configuration.Configuration() conf.host = "http://localhost" conf.debug = False self.influxdb_client = InfluxDBClient(url=conf.host, token="my-token") self.write_options = WriteOptions(batch_size=2, flush_interval=5_000, retry_interval=3_000) self._write_client = WriteApi(influxdb_client=self.influxdb_client, write_options=self.write_options)
def test_metric_v2_list(self, baseapi): # test metric() (no arguments) metrics_body = { 'request': { 'type': 'list' }, 'value': { 'java.util.logging': { 'type=Logging': {} }, }, 'timestamp': 0, 'status': 200 } httpretty.enable() httpretty.register_uri(httpretty.GET, 'http://localhost:8080/metrics/v2/list', body=json.dumps(metrics_body)) metric = baseapi.metric() assert httpretty.last_request().path == '/metrics/v2/list' assert metric == {'java.util.logging': {'type=Logging': {}}} httpretty.disable() httpretty.reset()
def setUp(self): if environ.get('CLIMATA_DIRECT', None): return httpretty.enable() for row in load_file(join('tests', 'file_list.csv')): if row.module != self.module: continue f = open( join('tests', 'files', row.module + '_' + row.filename), 'rb' ) data = f.read() f.close() method = getattr(httpretty, row.method.upper()) url = row.url for char in '.?+': url = url.replace(char, '\\' + char) httpretty.register_uri( method, re.compile(url), body=data, match_querystring=True, )
def setUp(self): httpretty.enable()
def test_create_plp(self, client): httpretty.enable() data = """ <x:Envelope xmlns:x="http://schemas.xmlsoap.org/soap/envelope/" xmlns:cli="http://cliente.bean.master.sigep.bsb.correios.com.br/"> <x:Header/> <x:Body> <cli:fechaPlpVariosServicos> <xml>?</xml> <idPlpCliente>{plp_id}</idPlpCliente> <cartaoPostagem>{post_card}</cartaoPostagem> <listaEtiquetas>{label_list}</listaEtiquetas> <usuario>{user}</usuario> <senha>{password}</senha> </cli:fechaPlpVariosServicos> </x:Body> </x:Envelope> """.format(user=client.user, password=client.password, plp_id='003', post_card='ABC123', label_list=['PC000001HK', 'PC000002HK']) body = fake_body(10) httpretty.register_uri(httpretty.POST, SOAP_URL, data=data, body=body) obj_list = [{ 'tracking_code': 'PC000001HK', 'service_code': '1', 'weight': '1', 'receiver_name': 'Joao Daher', 'receiver_home_phone': '1122223333', 'receiver_mobile_phone': '', 'receiver_email': '*****@*****.**', 'receiver_address': 'Rua Galileu Galilei', 'receiver_complement': '', 'receiver_number': '1067', 'receiver_neighborhood': 'Jardim Iraja', 'receiver_city': 'Passos', 'receiver_state': 'MG', 'receiver_zip_code': '37902000', 'nfe_number': '332323', 'is_insurance': True, 'total': '300', 'dimension_height': '15', 'dimension_width': '15', 'dimension_length': '20', 'dimension_diameter': '5', }, { 'tracking_code': 'PC000002HK', 'service_code': '1', 'weight': '1', 'receiver_name': 'Joao Daher', 'receiver_home_phone': '1122223333', 'receiver_mobile_phone': '', 'receiver_email': '*****@*****.**', 'receiver_address': 'Rua Galileu Galilei', 'receiver_complement': '', 'receiver_number': '1067', 'receiver_neighborhood': 'Jardim Iraja', 'receiver_city': 'Passos', 'receiver_state': 'MG', 'receiver_zip_code': '37902000', 'nfe_number': '3323323', 'is_insurance': True, 'total': '300', 'dimension_height': '15', 'dimension_width': '15', 'dimension_length': '20', 'dimension_diameter': '5', }] data = client.create_plp(intern_plp_number='003', object_list=obj_list) assert data == { 'plp_id': 10, 'tracking_code_list': [ client._remove_dv_tracking_code(code) for code in ['PC000001HK', 'PC000002HK'] ], }
def setUp(self): super().setUp() RequestsInstrumentor().instrument() httpretty.enable() httpretty.register_uri(httpretty.GET, self.URL, body="Hello!")
assert api.stuff.config.cache_lifetime == 8 assert not api.stuff.config.silent api.stuff('more', 'stuff', debug=True) assert api.stuff.config.debug def test_wrap_chain(self): assert api.chained.wrap.stuff is api('chained').wrap('stuff') assert api.more.chaining.stuff is api.more('chaining')('stuff') assert api('expert/chaining/stuff') is not api.expert.chaining.stuff assert api('hello', 'world') is api.hello.world assert api('products', 123) is api.products(123) def test_debugging(self): api.user.get('имя', debug=True) def test_response_exceptions(self): self.assertRaises(HTTPError, api.status_404.get) self.assertRaises(HTTPError, api.status_500.get) try: api.status_404.get(silent=True) api.status_500.get(silent=True) except HTTPError: self.fail("Wrap.get() raised an unexpected HTTPError while being " "told to be silent!") if __name__ == '__main__': httpretty.enable() unittest.main() httpretty.disable()
def setUp(self): personal_access_token = PersonalAccessToken('ACCOUNT_NUMBER', 'PERSONAL_ACCESS_TOKEN') self.harvest = harvest.Harvest('https://api.harvestapp.com/api/v2', personal_access_token) warnings.filterwarnings("ignore", category=ResourceWarning, message="unclosed.*") # There's a bug in httpretty ATM. httpretty.enable()