def tearDown(self): self.strategy = None User.reset_cache() TestUserSocialAuth.reset_cache() TestNonce.reset_cache() TestAssociation.reset_cache() HTTPretty.disable()
def test_global_boolean_enabled(): HTTPretty.disable() expect(HTTPretty.is_enabled()).to.be.falsy HTTPretty.enable() expect(HTTPretty.is_enabled()).to.be.truthy HTTPretty.disable() expect(HTTPretty.is_enabled()).to.be.falsy
def tearDown(self): HTTPretty.disable() HTTPretty.reset() self.backend = None self.strategy = None self.name = None self.complete_url = None
def mocked_urls(url_files, methods=None): """mocks the underlying python sockets library to return a given file's content """ # if environment variable is set, then don't mock the tests just grab files # over the network. Example: # env ULMO_DONT_MOCK_TESTS=1 py.test if os.environ.get('ULMO_DONT_MOCK_TESTS', False): yield else: if isinstance(url_files, basestring): url_files = {'.*': url_files} HTTPretty.enable() for url_match, url_file in url_files.iteritems(): if not isinstance(url_match, basestring) and len(url_match) == 2: url_match, methods = url_match if not os.path.isabs(url_file): url_file = get_test_file_path(url_file) callback = _build_request_callback(url_file) url_re = re.compile(url_match) if methods is None: methods = ['GET', 'POST', 'HEAD'] for method in methods: request_class = getattr(HTTPretty, method) HTTPretty.register_uri(request_class, url_re, body=callback) yield HTTPretty.disable() HTTPretty.reset()
def start(self): HTTPretty.disable() args = [self.port] self.process = Process(target=subprocess_server_tcp, args=args) self.process.start() time.sleep(1)
def stop(self): """Stops the mocked context, restoring the routes back to what they were """ if not self.started: raise RuntimeError('Called stop() before start()') HTTPretty.disable()
def test_httpretty_bypasses_when_disabled(context): u"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( '. 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('<- HELLO WORLD ->') HTTPretty.enable() fd = urllib2.urlopen('http://localhost:9999/go-for-bubbles/') got3 = fd.read() fd.close() expect(got3).to.equal('glub glub')
def test_httpretty_bypasses_when_disabled(): u"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() assert that(got1).equals( '. 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() assert that(got2).equals('<- HELLO WORLD ->') HTTPretty.enable() fd = urllib2.urlopen('http://localhost:9999/go-for-bubbles/') got3 = fd.read() fd.close() assert that(got3).equals('glub glub')
def test_socktype_good_python_version(): import socket with patch("socket.SocketType", socket.socket): HTTPretty.enable() expect(socket.SocketType).to.equal(socket.socket) HTTPretty.disable()
def stop_mocking(self): self.__class__._count -= 1 if self.__class__._count < 0: raise RuntimeError('can\'t stop() before start().') if self.__class__._count == 0: HTTPretty.disable()
def __exit__(self, etype, value, traceback): """ :param etype: exit type :param value: exit value :param traceback: the traceback for the exit """ HTTPretty.reset() HTTPretty.disable()
def stop(self): self.__class__.nested_count -= 1 if self.__class__.nested_count < 0: raise RuntimeError('Called stop() before start().') if self.__class__.nested_count == 0: HTTPretty.disable()
def go(app, port, data={}): from httpretty import HTTPretty HTTPretty.disable() http = HTTPServer(app) HTTPretty.disable() http.listen(int(port)) IOLoop.instance().start()
def __exit__(self, etype, value, traceback): """ Defines the behaviour for __exit__ :param etype: exit type :param value: exit value :param traceback: the traceback for the exit """ HTTPretty.reset() HTTPretty.disable()
def tearDown(self): self.backend = None self.strategy = None self.user = None User.reset_cache() User.set_active(True) TestUserSocialAuth.reset_cache() TestNonce.reset_cache() TestAssociation.reset_cache() HTTPretty.disable()
def start(self): app = self.get_handlers() data = {} args = (app, self.port, data) HTTPretty.disable() self.process = Process(target=subprocess_server_tornado, args=args) self.process.start() time.sleep(1)
def tearDown(self): self.backend = None self.strategy = None self.user = None User.reset_cache() User.set_active(True) TestUserPixelpinAuth.reset_cache() TestNonce.reset_cache() TestAssociation.reset_cache() HTTPretty.disable()
def wrapper(*args, **kwargs): HTTPretty.reset() HTTPretty.enable() _do_httpretty_registration(path) try: return func(*args, **kwargs) finally: HTTPretty.disable()
def tearDown(self): HTTPretty.disable() self.backend = None self.strategy = None self.name = None self.complete_url = None User.reset_cache() TestUserSocialAuth.reset_cache() TestNonce.reset_cache() TestAssociation.reset_cache() TestCode.reset_cache()
def test_latest_subject_positions(self): message = self._skeleton_message() RoomPosition().process_message(message) path = 'latest_subject_positions/%s' % message['sensor_id'] full_path = "http://127.0.0.1:8000/%s" % path HTTPretty.enable() HTTPretty.register_uri(HTTPretty.GET, full_path) response = requests.get(full_path) HTTPretty.disable() eq_(response.status_code, STATUS_OK, 'Response has status_code: %s' % response.status_code)
def test_socktype_bad_python_version_regression(): """ Some versions of python accidentally internally shadowed the SockType variable, so it was no longer the socket object but and int Enum representing the socket type e.g. AF_INET. Make sure we don't patch SockType in these cases https://bugs.python.org/issue20386 """ import socket someObject = object() with patch('socket.SocketType', someObject): HTTPretty.enable() expect(socket.SocketType).to.equal(someObject) HTTPretty.disable()
def mocked_urls(url_files, methods=None, force=False): """mocks the underlying python sockets library to return a given file's content. Note: that this function checks for an environment variable named ULMO_DONT_MOCK_TESTS; if that environment variable is set then urls will not be mocked and the HTTP requests will go over the network. For example, this could be used to to run the whole test suite without mocking files: # env ULMO_DONT_MOCK_TESTS=1 py.test Parameters ---------- url_files : str or dict Files to be mocked. It can either be a string representation of a filepath to a file whose contents will be used as a response to all HTTP requests. Or it can be a dict where the keys are regular expression strings and the values are filepaths - the regex keys will be used to match urls if they match, the file path will be used. methods : iterable of str or None HTTP methods that will be mocked. If set to None (default) then the default methods are GET, POST and HEAD. """ # if environment variable is set, then mock the tests otherwise just grab files # over the network. Example: # env ULMO_MOCK_TESTS=1 py.test if not os.environ.get('ULMO_MOCK_TESTS', False) and not force: yield else: if isinstance(url_files, basestring): url_files = {'.*': url_files} HTTPretty.enable() for url_match, url_file in url_files.items(): if not isinstance(url_match, basestring) and len(url_match) == 2: url_match, methods = url_match if not os.path.isabs(url_file): url_file = get_test_file_path(url_file) callback = _build_request_callback(url_file) url_re = re.compile(url_match) if methods is None: methods = ['GET', 'POST', 'HEAD'] for method in methods: request_class = getattr(HTTPretty, method) HTTPretty.register_uri(request_class, url_re, match_querystring=True, body=callback) yield HTTPretty.disable() HTTPretty.reset()
def mocked_urls(url_files, methods=None): """mocks the underlying python sockets library to return a given file's content. Note: that this function checks for an environment variable named ULMO_DONT_MOCK_TESTS; if that environment variable is set then urls will not be mocked and the HTTP requests will go over the network. For example, this could be used to to run the whole test suite without mocking files: # env ULMO_DONT_MOCK_TESTS=1 py.test Parameters ---------- url_files : str or dict Files to be mocked. It can either be a string representation of a filepath to a file whose contents will be used as a response to all HTTP requests. Or it can be a dict where the keys are regular expression strings and the values are filepaths - the regex keys will be used to match urls if they match, the file path will be used. methods : iterable of str or None HTTP methods that will be mocked. If set to None (default) then the default methods are GET, POST and HEAD. """ if os.environ.get('ULMO_DONT_MOCK_TESTS', False): yield else: if isinstance(url_files, basestring): url_files = {'.*': url_files} HTTPretty.enable() for url_match, url_file in url_files.iteritems(): if not isinstance(url_match, basestring) and len(url_match) == 2: url_match, methods = url_match if not os.path.isabs(url_file): url_file = get_test_file_path(url_file) callback = _build_request_callback(url_file) url_re = re.compile(url_match) if methods is None: methods = ['GET', 'POST', 'HEAD'] for method in methods: request_class = getattr(HTTPretty, method) HTTPretty.register_uri(request_class, url_re, match_querystring=True, body=callback) yield HTTPretty.disable() HTTPretty.reset()
def test_latest_subject_positions(self): # Keep this import here in order to avoid OpenCV imports from pipeline.room_position import RoomPosition message = self._skeleton_message() RoomPosition().process_message(message) path = 'latest_subject_positions/%s' % message['sensor_id'] full_path = "http://127.0.0.1:8000/%s" % path HTTPretty.enable() HTTPretty.register_uri(HTTPretty.GET, full_path) response = requests.get(full_path) HTTPretty.disable() eq_(response.status_code, STATUS_OK, 'Response has status_code: %s' % response.status_code)
def stop(cls): """Stop running this class' fixtures""" # Decrease our counter FixtureManager.nested_count -= 1 # If we have stopped running too many times, complain and leave if FixtureManager.nested_count < 0: raise RuntimeError('When running `httpretty-fixtures`, `stop()`' 'was run more times than (or before) `start()`') # If we have gotten out of nesting, then stop HTTPretty and # DEV: Only disable HTTPretty if it was started outside of FixtureManager if FixtureManager.nested_count == 0 and not FixtureManager.httpretty_enabled_at_start: HTTPretty.disable()
def go(port): from httpretty import HTTPretty HTTPretty.disable() import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('localhost', port)) s.listen(True) conn, addr = s.accept() while True: data = conn.recv(1024) conn.send(b"RECEIVED: " + bytes(data)) conn.close()
def test_httpretty_should_not_raise_on_socket_send_when_uri_not_registered(): ("HTTPretty should not raise a RuntimeError when the fakesocket " "is used in an invalid usage.") import socket HTTPretty.enable() sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0) sock.setblocking(0) expect(sock.sendto).when.called_with( b'whatever', ('127.0.0.1', 53)).should_not.throw(RuntimeError) sock.close() HTTPretty.reset() HTTPretty.disable()
def test_httpretty_should_not_raise_on_socket_send_when_uri_not_registered(): """HTTPretty should not raise a RuntimeError when the fakesocket is used in an invalid usage. """ import socket HTTPretty.enable() sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0) sock.setblocking(0) expect(sock.sendto).when.called_with(b"whatever", ("127.0.0.1", 53)).should_not.throw(RuntimeError) sock.close() HTTPretty.reset() HTTPretty.disable()
def test_https_passthrough(): url = 'https://raw.githubusercontent.com/gabrielfalcao/HTTPretty/master/COPYING' response1 = requests.get(url, stream=True) HTTPretty.enable() HTTPretty.register_uri(HTTPretty.GET, 'https://google.com/', body="Not Google") response2 = requests.get('https://google.com/') expect(response2.content).to.equal(b'Not Google') response3 = requests.get(url, stream=True) (response3.content).should.equal(response1.content) HTTPretty.disable() response4 = requests.get(url, stream=True) (response4.content).should.equal(response1.content)
def test_http_passthrough(): url = 'http://httpbin.org/status/200' response1 = requests.get(url) response1 = requests.get(url, stream=True) HTTPretty.enable() HTTPretty.register_uri(HTTPretty.GET, 'http://google.com/', body="Not Google") response2 = requests.get('http://google.com/') expect(response2.content).to.equal(b'Not Google') response3 = requests.get(url, stream=True) (response3.content).should.equal(response1.content) HTTPretty.disable() response4 = requests.get(url, stream=True) (response4.content).should.equal(response1.content)
def start(self): def go(app, port, data={}): from httpretty import HTTPretty HTTPretty.disable() http = HTTPServer(app) HTTPretty.disable() http.listen(int(port)) IOLoop.instance().start() app = self.get_handlers() data = {} args = (app, self.port, data) HTTPretty.disable() self.process = Process(target=go, args=args) self.process.start() time.sleep(1)
def test_httpretty_should_raise_on_socket_send_when_uri_registered(): """HTTPretty should raise a RuntimeError when the fakesocket is used in an invalid usage. """ import socket HTTPretty.enable() HTTPretty.register_uri(HTTPretty.GET, 'http://127.0.0.1:5000') expect(core.POTENTIAL_HTTP_PORTS).to.be.equal(set([80, 443, 5000])) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(('127.0.0.1', 5000)) expect(sock.send).when.called_with(b'whatever').to.throw(RuntimeError) sock.close() # restore the previous value core.POTENTIAL_HTTP_PORTS.remove(5000) HTTPretty.reset() HTTPretty.disable()
def test_http_passthrough(): url = 'http://ip4.me/' response1 = requests.get(url) HTTPretty.enable() HTTPretty.register_uri(HTTPretty.GET, 'http://google.com/', body="Not Google") response2 = requests.get('http://google.com/') expect(response2.content).to.equal(b'Not Google') response3 = requests.get(url) expect(response3.content).to.equal(response1.content) HTTPretty.disable() response4 = requests.get(url) expect(response4.content).to.equal(response1.content)
def start(self): HTTPretty.disable() def go(port): from httpretty import HTTPretty HTTPretty.disable() import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('localhost', port)) s.listen(True) conn, addr = s.accept() while True: data = conn.recv(1024) conn.send(b"RECEIVED: " + bytes(data)) conn.close() args = [self.port] self.process = Process(target=go, args=args) self.process.start() time.sleep(1)
def test_https_passthrough(): from sure import expect from httpretty import HTTPretty import requests url = "https://www.cloudflare.com/ips-v4" response1 = requests.get(url) HTTPretty.enable() HTTPretty.register_uri(HTTPretty.GET, "http://google.com/", body="Not Google") response2 = requests.get("http://google.com/") expect(response2.content).to.equal("Not Google") response3 = requests.get(url) expect(response3.content).to.equal(response1.content) HTTPretty.disable() response4 = requests.get(url) expect(response4.content).to.equal(response1.content)
def test_https_passthrough(): from sure import expect from httpretty import HTTPretty import requests url = 'https://www.cloudflare.com/ips-v4' response1 = requests.get(url) HTTPretty.enable() HTTPretty.register_uri(HTTPretty.GET, 'http://google.com/', body="Not Google") response2 = requests.get('http://google.com/') expect(response2.content).to.equal('Not Google') response3 = requests.get(url) expect(response3.content).to.equal(response1.content) HTTPretty.disable() response4 = requests.get(url) expect(response4.content).to.equal(response1.content)
def teardown_class(cls): HTTPretty.disable()
def tearDown(self): HTTPretty.disable()
def tearDown(self): """ Tear stuff down """ HTTPretty.disable()
def test_socktype_good_python_version(): import socket with patch('socket.SocketType', socket.socket): HTTPretty.enable() expect(socket.SocketType).to.equal(socket.socket) HTTPretty.disable()
def stop(self): HTTPretty.disable()
# # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import os from httpretty import version, HTTPretty from setuptools import setup HTTPretty.disable() def get_packages(): # setuptools can't do the job :( packages = [] for root, dirnames, filenames in os.walk('httpretty'): if '__init__.py' in filenames: packages.append(".".join(os.path.split(root)).strip(".")) return packages setup(name='httpretty', version=version, description='HTTP client mock for Python', author=u'Gabriel Falcao',