Here are the examples of the python api requests_mock.Mocker taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
189 Examples
3
Example 1
Project: home-assistant Source File: test_rest.py
@requests_mock.Mocker()
def test_turn_on_status_not_ok(self, mock_req):
"""Test turn_on when error status returned."""
mock_req.post(self.resource, status_code=500)
self.switch.turn_on()
self.assertEqual(self.body_on, mock_req.last_request.text)
self.assertEqual(None, self.switch.is_on)
3
Example 2
Project: home-assistant Source File: test_updater.py
@requests_mock.Mocker()
def test_reporting_false_works(self, m):
"""Test we do not send any data."""
m.post(updater.UPDATER_URL,
json={'version': '0.15',
'release-notes': 'https://home-assistant.io'})
response = updater.get_newest_version(None)
assert response == ('0.15', 'https://home-assistant.io')
history = m.request_history
assert len(history) == 1
assert history[0].json() == {}
3
Example 3
Project: django-bulbs Source File: test_models.py
@vcr.use_cassette()
@mock_vault(SECRETS)
def test_handles_sodahead_answer_creation_errors(self):
sodahead_endpoint = re.compile('https://onion.sodahead.com/api/polls/[\d]+/')
poll = Poll.objects.create(question_text='listening to your heart', title=random_title())
with requests_mock.Mocker() as mocker:
mocker.post(sodahead_endpoint, status_code=500, json={})
with self.assertRaises(SodaheadResponseError):
Answer.objects.create(poll=poll, answer_text='something')
3
Example 4
@requests_mock.Mocker()
@patch('forecastio.api.get_forecast', wraps=forecastio.api.get_forecast)
def test_setup(self, mock_req, mock_get_forecast):
"""Test for successfully setting up the forecast.io platform."""
uri = (r'https://api.(darksky.net|forecast.io)\/forecast\/(\w+)\/'
r'(-?\d+\.?\d*),(-?\d+\.?\d*)')
mock_req.get(re.compile(uri),
text=load_fixture('darksky.json'))
darksky.setup_platform(self.hass, self.config, MagicMock())
self.assertTrue(mock_get_forecast.called)
self.assertEqual(mock_get_forecast.call_count, 1)
3
Example 5
Project: pyoanda Source File: test_transaction.py
@requests_mock.Mocker()
def test_get_transaction_history(self, m):
# Mock zip file content
content = BytesIO()
with ZipFile(content, 'w') as zip:
zip.writestr('transactions.json', json.dumps({'ok': True}))
content.seek(0)
# Mock requests, one HEAD to check if it's there, one GET once it is
location = 'http://example.com/transactions.json.gz'
m.head(location, status_code=200)
m.get(location, body=content, status_code=200)
method = 'request_transaction_history'
with mock.patch.object(Client, method, return_value=location):
transactions = self.client.get_transaction_history()
assert transactions['ok']
assert m.call_count == 2
3
Example 6
Project: amy Source File: test_commands.py
@requests_mock.Mocker()
def test_getting_event_metadata(self, mock):
"""Ensure metadata are fetched and normalized by `get_event_metadata`."""
# underlying `fetch_event_metadata` and `parse_metadata_from_event_website`
# are tested in great detail in `test_util.py`, so here's just a short
# test
website_url = 'https://github.com/swcarpentry/workshop-template'
mock_text = self.mocked_event_page
mock.get(website_url, text=mock_text, status_code=200)
# mock placed, let's test `get_event_metadata`
metadata = self.cmd.get_event_metadata(website_url)
self.assertEqual(metadata, self.expected_metadata_parsed)
3
Example 7
Project: home-assistant Source File: test_rest.py
@requests_mock.Mocker()
def test_update_when_off(self, mock_req):
"""Test update when switch is off."""
mock_req.get(self.resource, text=self.body_off)
self.switch.update()
self.assertEqual(False, self.switch.is_on)
3
Example 8
Project: planet-client-python Source File: test_mosaics.py
def test_get_mosaic_quads():
mosaic_name = 'color_balance_mosaic'
with Mocker() as m:
text = read_fixture('get-mosaic-quads.json')
uri = os.path.join(client.base_url,
'mosaics/%s/quads/?count=50' % mosaic_name)
m.get(uri, text=text, status_code=200)
r = client.get_mosaic_quads(mosaic_name, count=50)
assert r.response.status_code == 200
assert r.get() == json.loads(text)
3
Example 9
def test_drop_database(self):
with requests_mock.Mocker() as m:
m.register_uri(
requests_mock.GET,
"http://localhost:8086/query",
text='{"results":[{}]}'
)
self.cli.drop_database('new_db')
self.assertEqual(
m.last_request.qs['q'][0],
'drop database "new_db"'
)
3
Example 10
def setUp(self):
mocker = requests_mock.Mocker()
mocker.post(
"https://graph.facebook.com/oauth/access_token",
text="access_token=urlencoded",
headers={"Content-Type": "text/plain"},
)
mocker.start()
self.addCleanup(mocker.stop)
facebook = OAuth2Session('foo', redirect_uri='https://i.b')
self.session = facebook_compliance_fix(facebook)
3
Example 11
Project: home-assistant Source File: test_ddwrt.py
@mock.patch('homeassistant.components.device_tracker.ddwrt._LOGGER.error')
def test_invalid_response(self, mock_error):
"""Test error handling when response has an error status."""
with requests_mock.Mocker() as mock_request:
mock_request.register_uri(
'GET', r'http://%s/Status_Wireless.live.asp' % TEST_HOST,
status_code=444)
with assert_setup_component(1):
assert setup_component(
self.hass, DOMAIN, {DOMAIN: {
CONF_PLATFORM: 'ddwrt',
CONF_HOST: TEST_HOST,
CONF_USERNAME: 'fake_user',
CONF_PASSWORD: '0'
}})
self.assertTrue(
'Invalid response from ddwrt' in
str(mock_error.call_args_list[-1]))
3
Example 12
Project: pyoanda Source File: test_transaction.py
@requests_mock.Mocker()
def test_get_transaction_history_gives_up(self, m):
"""Ensures that get_transaction_history eventually gives up."""
# Mock requests, one HEAD to check if it's there, one GET once it is
location = 'http://example.com/transactions.json.gz'
m.head(location, [{'status_code': 404}, {'status_code': 404}])
method = 'request_transaction_history'
with mock.patch.object(Client, method, return_value=location):
transactions = self.client.get_transaction_history(.3)
assert not transactions
# Possible timing issue, may be one or the other
assert m.call_count == 2 or m.call_count == 3
3
Example 13
def runTest(self):
"""
We are mocking the request so every second call is rate limited.
"""
with requests_mock.Mocker() as m:
m.register_uri('GET', 'https://api.hipchat.com/v2/user/@john', status_code=200, json=self.hipchat_callback)
for i in xrange(3):
self.hipchat.get_user('@john')
3
Example 14
@requests_mock.Mocker()
def test_setup(self, mock_req):
"""Test setup with valid configuration."""
mock_req.get('localhost', status_code=200)
self.assertTrue(setup_component(self.hass, 'switch', {
'switch': {
'platform': 'rest',
'name': 'foo',
'resource': 'http://localhost',
'body_on': 'custom on text',
'body_off': 'custom off text',
}
}))
self.assertEqual(1, mock_req.call_count)
assert_setup_component(1, 'switch')
3
Example 15
Project: planet-client-python Source File: test_mosaics.py
def test_list_mosaics():
with Mocker() as m:
text = read_fixture('list-mosaics.json')
uri = os.path.join(client.base_url, 'mosaics/')
m.get(uri, text=text, status_code=200)
r = client.list_mosaics()
assert r.response.status_code == 200
assert r.get() == json.loads(text)
3
Example 16
Project: home-assistant Source File: test_rest.py
@requests_mock.Mocker()
def test_turn_off_status_not_ok(self, mock_req):
"""Test turn_off when error status returned."""
mock_req.post(self.resource, status_code=500)
self.switch.turn_off()
self.assertEqual(self.body_off, mock_req.last_request.text)
self.assertEqual(None, self.switch.is_on)
3
Example 17
Project: amy Source File: test_util.py
@requests_mock.Mocker()
def test_fetching_event_metadata_yaml(self, mock):
"Ensure 'fetch_event_metadata' works correctly with YAML metadata provided."
website_url = 'https://pbanaszkiewicz.github.io/workshop'
repo_url = ('https://raw.githubusercontent.com/pbanaszkiewicz/'
'workshop/gh-pages/index.html')
mock.get(website_url, text='', status_code=200)
mock.get(repo_url, text=self.yaml_content, status_code=200)
metadata = fetch_event_metadata(website_url)
self.assertEqual(metadata['slug'], 'workshop')
3
Example 18
@requests_mock.Mocker()
def test_setup(self, mock):
"""Test the setup."""
mock_responses(mock)
response = sleepiq.setup(self.hass, self.config)
self.assertTrue(response)
3
Example 19
def test_login(client):
'''Verify login functionality'''
with requests_mock.Mocker() as m:
uri = os.path.join(client.base_url, 'auth/login')
response = json.dumps({'api_key': 'foobar'}).encode('utf-8')
b64 = base64.urlsafe_b64encode(response)
response = 'whatever.%s.whatever' % b64.decode('utf-8')
m.post(uri, text=response, status_code=200)
resp = client.login('jimmy', 'crackcorn')
assert resp['api_key'] == 'foobar'
3
Example 20
Project: influxdb-python Source File: client_test.py
def test_create_numeric_named_database(self):
with requests_mock.Mocker() as m:
m.register_uri(
requests_mock.GET,
"http://localhost:8086/query",
text='{"results":[{}]}'
)
self.cli.create_database('123')
self.assertEqual(
m.last_request.qs['q'][0],
'create database "123"'
)
3
Example 21
Project: pyoanda Source File: test_fundation.py
@requests_mock.Mocker()
def test_custom_json_options(self, m):
with mock.patch.object(Client, 'get_credentials', return_value=True):
c = Client(
("http://mydomain.com", "http://mystreamingdomain.com"),
"my_account",
"my_token"
)
c.json_options['parse_float'] = Decimal
m.get(requests_mock.ANY, text=json.dumps({'float': 1.01}))
r = c._Client__call('http://www.example.com/')
assert isinstance(r['float'], Decimal)
3
Example 22
Project: pyoanda Source File: test_transaction.py
@requests_mock.Mocker()
def test_request_transaction_history(self, m):
location = 'http://example.com/transactions.json.gz'
m.get(
requests_mock.ANY,
headers={'Location': location}, status_code=202
)
self.assertEqual(location, self.client.request_transaction_history())
3
Example 23
def test_login_failure(client):
'''Verify login functionality'''
with requests_mock.Mocker() as m:
uri = os.path.join(client.base_url, 'auth/login')
response = json.dumps({'message': 'invalid'})
m.post(uri, text=response, status_code=401)
try:
client.login('jimmy', 'crackcorn')
except api.exceptions.InvalidIdentity as ex:
assert str(ex) == 'invalid'
else:
assert False
3
Example 24
Project: pyoanda Source File: test_transaction.py
@requests_mock.Mocker()
def test_get_transaction_history_slow(self, m):
"""Ensures that get_transaction_history retries requests."""
# Mock zip file content
content = BytesIO()
with ZipFile(content, 'w') as zip:
zip.writestr('transactions.json', json.dumps({'ok': True}))
content.seek(0)
# Mock requests, one HEAD to check if it's there, one GET once it is
location = 'http://example.com/transactions.json.gz'
m.head(location, [{'status_code': 404}, {'status_code': 200}])
m.get(location, body=content, status_code=200)
method = 'request_transaction_history'
with mock.patch.object(Client, method, return_value=location):
transactions = self.client.get_transaction_history()
assert transactions['ok']
assert m.call_count == 3
3
Example 25
def setUp(self):
mocker = requests_mock.Mocker()
mocker.post(
"https://www.linkedin.com/uas/oauth2/accessToken",
json={"access_token": "linkedin"},
)
mocker.post(
"https://api.linkedin.com/v1/people/~/shares",
status_code=201,
json={
"updateKey": "UPDATE-3346389-595113200",
"updateUrl": "https://www.linkedin.com/updates?discuss=abc&scope=xyz"
}
)
mocker.start()
self.addCleanup(mocker.stop)
linkedin = OAuth2Session('foo', redirect_uri='https://i.b')
self.session = linkedin_compliance_fix(linkedin)
3
Example 26
Project: home-assistant Source File: test_ddwrt.py
@mock.patch('homeassistant.components.device_tracker.ddwrt._LOGGER.error')
def test_login_failed(self, mock_error):
"""Create a Ddwrt scanner with wrong credentials."""
with requests_mock.Mocker() as mock_request:
mock_request.register_uri(
'GET', r'http://%s/Status_Wireless.live.asp' % TEST_HOST,
status_code=401)
with assert_setup_component(1):
assert setup_component(
self.hass, DOMAIN, {DOMAIN: {
CONF_PLATFORM: 'ddwrt',
CONF_HOST: TEST_HOST,
CONF_USERNAME: 'fake_user',
CONF_PASSWORD: '0'
}})
self.assertTrue(
'Failed to authenticate' in
str(mock_error.call_args_list[-1]))
3
Example 27
Project: pyoanda Source File: test_transaction.py
@requests_mock.Mocker()
def test_get_transaction_history_handles_bad_files(self, m):
"""Ensures that get_transaction_history gracefully handles bad files.
"""
# Mock requests, one HEAD to check if it's there, one GET once it is
location = 'http://example.com/transactions.json.gz'
m.head(location, status_code=200)
m.get(location, text='invalid', status_code=200)
method = 'request_transaction_history'
with mock.patch.object(Client, method, return_value=location):
transactions = self.client.get_transaction_history()
assert not transactions
3
Example 28
def setUp(self):
mocker = requests_mock.Mocker()
mocker.post(
"https://api.weibo.com/oauth2/access_token",
json={"access_token": "weibo"},
)
mocker.start()
self.addCleanup(mocker.stop)
weibo = OAuth2Session('foo', redirect_uri='https://i.b')
self.session = weibo_compliance_fix(weibo)
3
Example 29
Project: home-assistant Source File: test_ddwrt.py
def test_update_wrong_data(self):
"""Test error handling of bad response when active devices checked."""
with requests_mock.Mocker() as mock_request:
mock_request.register_uri(
'GET', r'http://%s/Status_Wireless.live.asp' % TEST_HOST,
text=load_fixture('Ddwrt_Status_Wireless.txt').
replace('active_wireless', 'missing'))
mock_request.register_uri(
'GET', r'http://%s/Status_Lan.live.asp' % TEST_HOST,
text=load_fixture('Ddwrt_Status_Lan.txt'))
with assert_setup_component(1):
assert setup_component(
self.hass, DOMAIN, {DOMAIN: {
CONF_PLATFORM: 'ddwrt',
CONF_HOST: TEST_HOST,
CONF_USERNAME: 'fake_user',
CONF_PASSWORD: '0'
}})
3
Example 30
Project: planet-client-python Source File: test_mod.py
def test_workspace_set_create(client):
with requests_mock.Mocker() as m:
uri = os.path.join(client.base_url, 'workspaces/')
workspace = json.loads(read_fixture('workspace.json'))
request = clone(workspace)
request.pop('id')
m.post(uri, text=json.dumps(workspace), status_code=200)
assert client.set_workspace(request).get_raw() == json.dumps(workspace)
3
Example 31
@requests_mock.Mocker()
def test_setup_minimum(self, mock_req):
"""Test setup with minimum configuration."""
mock_req.get('http://localhost', status_code=200)
self.assertTrue(setup_component(self.hass, 'switch', {
'switch': {
'platform': 'rest',
'resource': 'http://localhost'
}
}))
self.assertEqual(1, mock_req.call_count)
assert_setup_component(1, 'switch')
3
Example 32
Project: sevenbridges-python Source File: conftest.py
@pytest.fixture
def request_mocker(request):
"""
:param request: pytest request object for cleaning up.
:return: Returns instance of requests mocker used to mock HTTP calls.
"""
m = requests_mock.Mocker()
m.start()
request.addfinalizer(m.stop)
return m
3
Example 33
Project: home-assistant Source File: test_rest.py
@requests_mock.Mocker()
def test_turn_on_success(self, mock_req):
"""Test turn_on."""
mock_req.post(self.resource, status_code=200)
self.switch.turn_on()
self.assertEqual(self.body_on, mock_req.last_request.text)
self.assertEqual(True, self.switch.is_on)
3
Example 34
Project: planet-client-python Source File: test_mod.py
def test_fetch_scene_info_scene_id(client):
'''Verify get_scene_metadata path handling'''
with requests_mock.Mocker() as m:
uri = os.path.join(client.base_url, 'scenes/ortho/x22')
m.get(uri, text='bananas', status_code=200)
assert client.get_scene_metadata('x22').get_raw() == 'bananas'
3
Example 35
Project: home-assistant Source File: test_rest.py
@requests_mock.Mocker()
def test_turn_off_success(self, mock_req):
"""Test turn_off."""
mock_req.post(self.resource, status_code=200)
self.switch.turn_off()
self.assertEqual(self.body_off, mock_req.last_request.text)
self.assertEqual(False, self.switch.is_on)
3
Example 36
Project: amy Source File: test_util.py
@requests_mock.Mocker()
def test_fetching_event_metadata_html(self, mock):
"Ensure 'fetch_event_metadata' works correctly with HTML metadata provided."
website_url = 'https://pbanaszkiewicz.github.io/workshop'
repo_url = ('https://raw.githubusercontent.com/pbanaszkiewicz/'
'workshop/gh-pages/index.html')
mock.get(website_url, text=self.html_content, status_code=200)
mock.get(repo_url, text='', status_code=200)
metadata = fetch_event_metadata(website_url)
self.assertEqual(metadata['slug'], '2015-07-13-test')
3
Example 37
Project: home-assistant Source File: test_rest.py
@requests_mock.Mocker()
def test_update_when_on(self, mock_req):
"""Test update when switch is on."""
mock_req.get(self.resource, text=self.body_on)
self.switch.update()
self.assertEqual(True, self.switch.is_on)
3
Example 38
Project: planet-client-python Source File: test_mosaics.py
def test_get_mosaic():
mosaic_name = 'color_balance_mosaic'
with Mocker() as m:
text = read_fixture('get-mosaic.json')
uri = os.path.join(client.base_url,
'mosaics/%s' % mosaic_name)
m.get(uri, text=text, status_code=200)
r = client.get_mosaic(mosaic_name)
assert r.response.status_code == 200
assert r.get() == json.loads(text)
3
Example 39
Project: home-assistant Source File: test_rest.py
@requests_mock.Mocker()
def test_update_when_unknown(self, mock_req):
"""Test update when unknown status returned."""
mock_req.get(self.resource, text='unknown status')
self.switch.update()
self.assertEqual(None, self.switch.is_on)
3
Example 40
Project: django-bulbs Source File: test_models.py
@vcr.use_cassette()
@mock_vault(SECRETS)
def test_poll_creation_fails_when_sodahead_request_fails(self):
with requests_mock.Mocker() as mocker:
mocker.post('https://onion.sodahead.com/api/polls/', status_code=500)
with self.assertRaises(SodaheadResponseError):
Poll.objects.create(question_text='other text', title=random_title())
3
Example 41
Project: home-assistant Source File: test_sleepiq.py
@requests_mock.Mocker()
def test_setup_login_failed(self, mock):
"""Test the setup if a bad username or password is given."""
mock.put('https://api.sleepiq.sleepnumber.com/rest/login',
status_code=401,
json=load_fixture('sleepiq-login-failed.json'))
response = sleepiq.setup(self.hass, self.config)
self.assertFalse(response)
3
Example 42
Project: planet-client-python Source File: test_mod.py
def test_status_code_404(client):
'''Verify 404 handling'''
with requests_mock.Mocker() as m:
uri = os.path.join(client.base_url, 'whatevs')
m.get(uri, text='test', status_code=404)
try:
client._get('whatevs').get_body()
except api.exceptions.MissingResource as ex:
assert str(ex) == 'test'
else:
assert False
3
Example 43
def test_create_database(self):
with requests_mock.Mocker() as m:
m.register_uri(
requests_mock.GET,
"http://localhost:8086/query",
text='{"results":[{}]}'
)
self.cli.create_database('new_db')
self.assertEqual(
m.last_request.qs['q'][0],
'create database "new_db"'
)
3
Example 44
Project: django-bulbs Source File: test_views.py
@vcr.use_cassette()
@mock_vault(SECRETS)
def test_sodahead_service_failure(self):
with requests_mock.Mocker() as mocker:
sodahead_endpoint = re.compile('https://onion.sodahead.com/api/polls/')
mocker.post(sodahead_endpoint, status_code=500)
list_url = reverse('poll-list')
data = {
'questions_text': 'go underneath the bridge!',
'title': random_title()
}
self.give_permissions()
response = self.api_client.post(
list_url,
json.dumps(data),
content_type='application/json'
)
self.assertEqual(response.status_code, 503)
3
Example 45
def setUp(self):
directions_path = os.path.join(os.path.dirname(__file__), 'resources', ex_resp_directions)
with open(directions_path, 'rb') as directions:
ex_directions = pickle.load(directions)
elevations_path = os.path.join(os.path.dirname(__file__), 'resources', ex_resp_elevations)
with open(elevations_path, 'rb') as elevations:
ex_elevations = pickle.load(elevations)
with requests_mock.Mocker() as m:
m.get('https://maps.googleapis.com/maps/api/directions/json?mode=walking&origin={},{}&destination={},{}'.format(
ex_orig[0], ex_orig[1], ex_dest[0], ex_dest[1]
), json=ex_directions, status_code=200)
m.get('https://maps.googleapis.com/maps/api/elevation/json?path=enc:{}&samples={}'.format(
ex_enc_polyline, ex_nr_samples
), json=ex_elevations, status_code=200)
self.polyline = Polyline(ex_orig, ex_dest, ex_speed)
3
Example 46
Project: planet-client-python Source File: test_mod.py
def test_assert_client_execution_success(client):
'''verify simple mock success response'''
with requests_mock.Mocker() as m:
uri = os.path.join(client.base_url, 'whatevs')
m.get(uri, text='test', status_code=200)
assert 'test' == client._get('whatevs').get_body().get_raw()
3
Example 47
Project: planet-client-python Source File: test_mod.py
def test_status_code_other(client):
'''Verify other unexpected HTTP status codes'''
with requests_mock.Mocker() as m:
uri = os.path.join(client.base_url, 'whatevs')
# yep, this is totally made up
m.get(uri, text='emergency', status_code=911)
try:
client._get('whatevs').get_body()
except api.exceptions.APIException as ex:
assert str(ex) == '911: emergency'
else:
assert False
3
Example 48
Project: planet-client-python Source File: test_mod.py
def test_login_errors(client):
'''Verify login functionality'''
with requests_mock.Mocker() as m:
uri = os.path.join(client.base_url, 'auth/login')
response = 'An error occurred'
m.post(uri, text=response, status_code=500)
try:
client.login('jimmy', 'crackcorn')
except api.exceptions.APIException as ex:
assert str(ex) == '500: %s' % response
else:
assert False
3
Example 49
def setUp(self):
mocker = requests_mock.Mocker()
mocker.post(
"https://login.mailchimp.com/oauth2/token",
json={"access_token": "mailchimp", "expires_in": 0, "scope": None},
)
mocker.start()
self.addCleanup(mocker.stop)
mailchimp = OAuth2Session('foo', redirect_uri='https://i.b')
self.session = mailchimp_compliance_fix(mailchimp)
3
Example 50
def assertResult(self, valid_file=None, invalid_file=None, settings={}):
with requests_mock.Mocker() as m:
InvalidLinkBear.check_prerequisites = lambda *args: True
uut = InvalidLinkBear(self.section, Queue())
for name, value in settings.items():
self.section.append(Setting(name, value))
m.add_matcher(custom_matcher)
if valid_file:
out = uut.execute("valid", valid_file)
self.assertEqual(out, [])
if invalid_file:
out = uut.execute("invalid", invalid_file)
self.assertNotEqual(out, [])
self.assertNotEqual(out, None)