Python httpretty.reset() Examples

The following are 30 code examples of httpretty.reset(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module httpretty , or try the search function .
Example #1
Source File: test_learners.py    From edx-analytics-dashboard with GNU Affero General Public License v3.0 6 votes vote down vote up
def _register_uris(self, learners_status, learners_payload, course_metadata_status, course_metadata_payload):
        httpretty.register_uri(
            httpretty.GET,
            '{data_api_url}/learners/'.format(data_api_url=settings.DATA_API_URL),
            body=json.dumps(learners_payload),
            status=learners_status
        )
        httpretty.register_uri(
            httpretty.GET,
            '{data_api_url}/course_learner_metadata/{course_id}/'.format(
                data_api_url=settings.DATA_API_URL,
                course_id=CourseSamples.DEMO_COURSE_ID,
            ),
            body=json.dumps(course_metadata_payload),
            status=course_metadata_status
        )
        self.addCleanup(httpretty.reset) 
Example #2
Source File: test_course.py    From edx-analytics-data-api-client with Apache License 2.0 6 votes vote down vote up
def assertCorrectEnrollmentUrl(self, course, demographic=None):
        """ Verifies that the enrollment URL is correct. """

        uri = self.get_api_url('courses/{0}/enrollment/'.format(course.course_id))
        if demographic:
            uri += '%s/' % demographic

        httpretty.register_uri(httpretty.GET, uri, body='{}')
        course.enrollment(demographic)

        date = '2014-01-01'
        httpretty.reset()
        httpretty.register_uri(httpretty.GET, '{0}?start_date={1}'.format(uri, date), body='{}')
        course.enrollment(demographic, start_date=date)

        httpretty.reset()
        httpretty.register_uri(httpretty.GET, '{0}?end_date={1}'.format(uri, date), body='{}')
        course.enrollment(demographic, end_date=date)

        httpretty.reset()
        httpretty.register_uri(httpretty.GET, '{0}?start_date={1}&end_date={1}'.format(uri, date), body='{}')
        course.enrollment(demographic, start_date=date, end_date=date) 
Example #3
Source File: test_course.py    From edx-analytics-data-api-client with Apache License 2.0 6 votes vote down vote up
def assertCorrectActivityUrl(self, course, activity_type=None):
        """ Verifies that the activity URL is correct. """

        uri = self.get_api_url('courses/{0}/activity/'.format(course.course_id))
        if activity_type:
            uri += '?activity_type=%s' % activity_type

        httpretty.register_uri(httpretty.GET, uri, body='{}')
        course.activity(activity_type)

        date = '2014-01-01'
        httpretty.reset()
        httpretty.register_uri(httpretty.GET, '{0}&start_date={1}'.format(uri, date), body='{}')
        course.activity(activity_type, start_date=date)

        httpretty.reset()
        httpretty.register_uri(httpretty.GET, '{0}&end_date={1}'.format(uri, date), body='{}')
        course.activity(activity_type, end_date=date)

        httpretty.reset()
        httpretty.register_uri(httpretty.GET, '{0}&start_date={1}&end_date={1}'.format(uri, date), body='{}')
        course.activity(activity_type, start_date=date, end_date=date) 
Example #4
Source File: helpers.py    From coinbase-python with Apache License 2.0 6 votes vote down vote up
def mock_response(method, uri, data, errors=None, warnings=None, pagination=None):
    def wrapper(fn):
        @six.wraps(fn)
        @hp.activate
        def inner(*args, **kwargs):
            body = {'data': data}
            if errors is not None:
                body['errors'] = errors
            if warnings is not None:
                body['warnings'] = warnings
            if pagination is not None:
                body['pagination'] = pagination
            hp.reset()
            hp.register_uri(method, re.compile('.*' + uri + '$'), json.dumps(body))
            return fn(*args, **kwargs)
        return inner
    return wrapper 
Example #5
Source File: maintenance_tests.py    From openSUSE-release-tools with GNU General Public License v2.0 6 votes vote down vote up
def setUp(self):
        """
        Initialize the configuration
        """

        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 = MaintenanceChecker(apiurl = APIURL,
                user = 'maintbot',
                logger = self.logger)
        self.checker.override_allow = False # Test setup cannot handle. 
Example #6
Source File: factory_source_tests.py    From openSUSE-release-tools with GNU General Public License v2.0 6 votes vote down vote up
def setUp(self):
        """
        Initialize the configuration
        """

        Cache.last_updated[APIURL] = {'__oldest': '2016-12-18T11:49:37Z'}
        httpretty.reset()
        httpretty.enable(allow_net_connect=False)

        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
        #osc.conf.config['http_debug'] = 1

        logging.basicConfig()
        self.logger = logging.getLogger(__file__)
        self.logger.setLevel(logging.DEBUG)

        self.checker = FactorySourceChecker(apiurl = APIURL,
                user = 'factory-source',
                logger = self.logger)
        self.checker.override_allow = False # Test setup cannot handle. 
Example #7
Source File: test_couch.py    From openag_python with GNU General Public License v3.0 6 votes vote down vote up
def test_get_or_create_db():
    server = Server("http://test.test:5984")
    httpretty.register_uri(
        httpretty.HEAD, "http://test.test:5984/test", status=404, body=""
    )
    def create_test_db(request, uri, headers):
        httpretty.reset()
        httpretty.register_uri(
            httpretty.HEAD, "http://test.test:5984/test", status=200
        )
        httpretty.register_uri(
            httpretty.PUT, "http://test.test:5984/test", status=500
        )
        return 201, headers, ""
    httpretty.register_uri(
        httpretty.PUT, "http://test.test:5984/test", body=create_test_db
    )
    assert "test" not in server
    test_db = server.get_or_create("test")
    assert "test" in server 
Example #8
Source File: tests.py    From python-opencage-geocoder with MIT License 6 votes vote down vote up
def testRateLimitExceeded(self):
        httpretty.register_uri(
            httpretty.GET,
            self.geocoder.url,
            body='{"status":{"code":402,"message":"OK"},"thanks":"For using an OpenCage Data API","total_results":0,"licenses":[{"url":"http://creativecommons.org/licenses/by-sa/3.0/","name":"CC-BY-SA"},{"url":"http://opendatacommons.org/licenses/odbl/summary/","name":"ODbL"}],"rate":{"reset":1402185600,"limit":"2500","remaining":0},"results":[],"timestamp":{"created_http":"Sat, 07 Jun 2014 10:38:45 GMT","created_unix":1402137525}}',
            status=402,
            adding_headers={'X-RateLimit-Limit': '2500', 'X-RateLimit-Remaining': '0', 'X-RateLimit-Reset': '1402185600'},
        )

        self.assertRaises(RateLimitExceededError, self.geocoder.geocode, "whatever")

        # check the exception
        try:
            self.geocoder.geocode("whatever")
        except RateLimitExceededError as ex:
            self.assertEqual(str(ex), 'Your rate limit has expired. It will reset to 2500 on 2014-06-08T00:00:00')
            self.assertEqual(ex.reset_to, 2500) 
Example #9
Source File: tests.py    From python-opencage-geocoder with MIT License 6 votes vote down vote up
def testDonostia(self):
        httpretty.register_uri(
            httpretty.GET,
            self.geocoder.url,
            body='{"thanks":"For using an OpenCage Data API","status":{"message":"OK","code":200},"rate":{"remaining":2482,"limit":"2500","reset":1402185600},"total_results":7,"results":[{"geometry":{"lat":"43.3213324","lng":"-1.9856227"},"annotations":{},"components":{"postcode":"20001;20002;20003;20004;20005;20006;20007;20008;20009;20010;20011;20012;20013;20014;20015;20016;20017;20018","county":"Donostialdea/Donostia-San Sebasti\u00e1n","state":"Basque Country","country":"Spain","city":"San Sebasti\u00e1n","country_code":"es"},"formatted":"San Sebasti\u00e1n, Donostialdea/Donostia-San Sebasti\u00e1n, 20001;20002;20003;20004;20005;20006;20007;20008;20009;20010;20011;20012;20013;20014;20015;20016;20017;20018, Basque Country, Spain, es","bounds":{"southwest":{"lat":"43.2178373","lng":"-2.086808"},"northeast":{"lng":"-1.8878838","lat":"43.3381344"}}},{"formatted":"Donostia, Irun, Bidasoa Beherea / Bajo Bidasoa, Basque Country, Spain, es","components":{"county":"Bidasoa Beherea / Bajo Bidasoa","state":"Basque Country","country":"Spain","city":"Irun","country_code":"es","road":"Donostia"},"bounds":{"southwest":{"lat":"43.3422299","lng":"-1.8022744"},"northeast":{"lng":"-1.8013452","lat":"43.3449598"}},"geometry":{"lng":"-1.8019153","lat":"43.3432784"},"annotations":{}},{"annotations":{},"geometry":{"lng":"-1.8022744","lat":"43.3422299"},"formatted":"Donostia, Anaka, Irun, Bidasoa Beherea / Bajo Bidasoa, Basque Country, Spain, es","components":{"county":"Bidasoa Beherea / Bajo Bidasoa","state":"Basque Country","country":"Spain","city":"Irun","suburb":"Anaka","country_code":"es","road":"Donostia"},"bounds":{"southwest":{"lng":"-1.8022971","lat":"43.3421635"},"northeast":{"lng":"-1.8022744","lat":"43.3422299"}}},{"geometry":{"lng":"-2.69312049872164","lat":"42.868297"},"annotations":{},"bounds":{"southwest":{"lng":"-2.6933154","lat":"42.8681484"},"northeast":{"lat":"42.8684357","lng":"-2.6929252"}},"formatted":"Donostia kalea, Ibaiondo, Vitoria-Gasteiz, Vitoria-Gasteizko Eskualdea / Cuadrilla de Vitoria, Basque Country, Spain, es","components":{"county":"Vitoria-Gasteizko Eskualdea / Cuadrilla de Vitoria","state":"Basque Country","country":"Spain","city":"Vitoria-Gasteiz","suburb":"Ibaiondo","country_code":"es","road":"Donostia kalea"}},{"bounds":{"southwest":{"lng":"-2.6889534","lat":"42.8620967"},"northeast":{"lat":"42.8623764","lng":"-2.6885774"}},"formatted":"Donostia kalea, Lakua, Vitoria-Gasteiz, Vitoria-Gasteizko Eskualdea / Cuadrilla de Vitoria, Basque Country, Spain, es","components":{"county":"Vitoria-Gasteizko Eskualdea / Cuadrilla de Vitoria","state":"Basque Country","country":"Spain","city":"Vitoria-Gasteiz","suburb":"Lakua","country_code":"es","road":"Donostia kalea"},"geometry":{"lat":"42.8622515","lng":"-2.68876582144679"},"annotations":{}},{"annotations":{},"geometry":{"lat":"51.5146888","lng":"-0.1609307"},"components":{"restaurant":"Donostia","country":"United Kingdom","state_district":"Greater London","country_code":"gb","county":"London","state":"England","suburb":"Marylebone","city":"City of Westminster","road":"Great Cumberland Mews"},"formatted":"Donostia, Great Cumberland Mews, Marylebone, City of Westminster, London, Greater London, England, United Kingdom, gb","bounds":{"northeast":{"lng":"-0.1608807","lat":"51.5147388"},"southwest":{"lat":"51.5146388","lng":"-0.1609807"}}},{"geometry":{"lat":43.31283,"lng":-1.97499},"annotations":{},"bounds":{"northeast":{"lng":"-1.92020404339","lat":"43.3401603699"},"southwest":{"lat":"43.2644081116","lng":"-2.04920697212"}},"formatted":"San Sebastian, Gipuzkoa, Basque Country, Spain, Donostia / San Sebasti\u00e1n","components":{"county":"Gipuzkoa","state":"Basque Country","country":"Spain","town":"San Sebastian","local administrative area":"Donostia / San Sebasti\u00e1n"}}],"timestamp":{"created_unix":1402136556,"created_http":"Sat, 07 Jun 2014 10:22:36 GMT"},"licenses":[{"name":"CC-BY-SA","url":"http://creativecommons.org/licenses/by-sa/3.0/"},{"name":"ODbL","url":"http://opendatacommons.org/licenses/odbl/summary/"}]}',

        )

        results = self.geocoder.geocode("Donostia")
        self.assertTrue(
            any((abs(result['geometry']['lat'] - 43.300836) < 0.05 and abs(result['geometry']['lng'] - -1.9809529) < 0.05) for result in results),
            msg="Bad result"
        )

        # test that the results are in unicode
        self.assertEqual(results[0]['formatted'], six.u('San Sebasti\xe1n, Donostialdea/Donostia-San Sebasti\xe1n, 20001;20002;20003;20004;20005;20006;20007;20008;20009;20010;20011;20012;20013;20014;20015;20016;20017;20018, Basque Country, Spain, es')) 
Example #10
Source File: test_WriteApiBatching.py    From influxdb-client-python with MIT License 6 votes vote down vote up
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) 
Example #11
Source File: test_client.py    From presto-python-client with Apache License 2.0 5 votes vote down vote up
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() 
Example #12
Source File: test_views.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        super(ProgramOfferUpdateViewTests, self).tearDown()
        httpretty.disable()
        httpretty.reset() 
Example #13
Source File: test_course_blocks.py    From edx-analytics-pipeline with GNU Affero General Public License v3.0 5 votes vote down vote up
def setUp(self):
        super(PullCourseBlocksApiDataTest, self).setUp()
        httpretty.reset() 
Example #14
Source File: test_course_list.py    From edx-analytics-pipeline with GNU Affero General Public License v3.0 5 votes vote down vote up
def setUp(self):
        super(PullCourseListApiDataTest, self).setUp()
        self.setup_dirs()
        self.create_task()
        httpretty.reset() 
Example #15
Source File: test_runtime.py    From msrest-for-python with MIT License 5 votes vote down vote up
def test_request_redirect_delete(self):

        url = self.client.format_url("/get_endpoint")
        request = self.client.delete(url, {'check':True})

        httpretty.register_uri(httpretty.DELETE, 'https://my_service.com/http/success/200', status=200)
        httpretty.register_uri(httpretty.DELETE, "https://my_service.com/get_endpoint",
                                responses=[
                                httpretty.Response(body="", status=307, method='DELETE', location='/http/success/200'),
                                ])


        response = self.client.send(request)
        assert response.status_code == 200, "Should redirect on 307 with location header"
        assert response.request.method == 'DELETE'

        assert response.history[0].status_code == 307
        assert response.history[0].is_redirect

        httpretty.reset()
        httpretty.register_uri(httpretty.DELETE, "https://my_service.com/get_endpoint",
                                responses=[
                                httpretty.Response(body="", status=307, method='DELETE'),
                                ])

        response = self.client.send(request)
        assert response.status_code == 307, "Should not redirect on 307 without location header"
        assert response.history == []
        assert not response.is_redirect 
Example #16
Source File: test_publishers.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        super(LMSPublisherTests, self).tearDown()
        httpretty.disable()
        httpretty.reset() 
Example #17
Source File: test_utils.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        # Reset HTTPretty state (clean up registered urls and request history)
        httpretty.reset() 
Example #18
Source File: test_runtime.py    From msrest-for-python with MIT License 5 votes vote down vote up
def test_request_redirect_head(self):

        url = self.client.format_url("/get_endpoint")
        request = self.client.head(url, {'check':True})

        httpretty.register_uri(httpretty.HEAD, 'https://my_service.com/http/success/200', status=200)
        httpretty.register_uri(httpretty.HEAD, "https://my_service.com/get_endpoint",
                                responses=[
                                httpretty.Response(body="", status=307, method='HEAD', location='/http/success/200'),
                                ])


        response = self.client.send(request)
        assert response.status_code == 200, "Should redirect on 307 with location header"
        assert response.request.method == 'HEAD'

        assert response.history[0].status_code == 307
        assert response.history[0].is_redirect

        httpretty.reset()
        httpretty.register_uri(httpretty.HEAD, "https://my_service.com/get_endpoint",
                                responses=[
                                httpretty.Response(body="", status=307, method='HEAD'),
                                ])

        response = self.client.send(request)
        assert response.status_code == 307, "Should not redirect on 307 without location header"
        assert response.history == []
        assert not response.is_redirect 
Example #19
Source File: test_runtime.py    From msrest-for-python with MIT License 5 votes vote down vote up
def test_request_redirect_post(self):

        url = self.client.format_url("/get_endpoint")
        request = self.client.post(url, {'check':True})

        httpretty.register_uri(httpretty.GET, 'https://my_service.com/http/success/get/200', status=200)
        httpretty.register_uri(httpretty.POST, "https://my_service.com/get_endpoint",
                                responses=[
                                httpretty.Response(body="", status=303, method='POST', location='/http/success/get/200'),
                                ])


        response = self.client.send(request)
        assert response.status_code == 200, "Should redirect with GET on 303 with location header"
        assert response.request.method == 'GET'

        assert response.history[0].status_code == 303
        assert response.history[0].is_redirect

        httpretty.reset()
        httpretty.register_uri(httpretty.POST, "https://my_service.com/get_endpoint",
                                responses=[
                                httpretty.Response(body="", status=303, method='POST'),
                                ])

        response = self.client.send(request)
        assert response.status_code == 303, "Should not redirect on 303 without location header"
        assert response.history == []
        assert not response.is_redirect 
Example #20
Source File: test_api.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        super(ProgramsApiClientTests, self).tearDown()
        httpretty.disable()
        httpretty.reset() 
Example #21
Source File: test_views.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        super(ProgramOfferListViewTests, self).tearDown()
        httpretty.disable()
        httpretty.reset() 
Example #22
Source File: json.py    From girlfriend with MIT License 5 votes vote down vote up
def tearDown(self):
        os.remove("line_file.json")
        os.remove("array_file.json")
        os.remove("object_file.json")
        os.remove("block_file.json")
        httpretty.disable()
        httpretty.reset() 
Example #23
Source File: test_models.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        # Reset HTTPretty state (clean up registered urls and request history)
        httpretty.reset() 
Example #24
Source File: test_api.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        # Reset HTTPretty state (clean up registered urls and request history)
        httpretty.reset() 
Example #25
Source File: test_views.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        super(EnterpriseOfferListViewTests, self).tearDown()
        httpretty.disable()
        httpretty.reset() 
Example #26
Source File: test_views.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        super(EnterpriseOfferUpdateViewTests, self).tearDown()
        httpretty.disable()
        httpretty.reset() 
Example #27
Source File: test_models.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        super(UserTests, self).tearDown()
        httpretty.disable()
        httpretty.reset() 
Example #28
Source File: test_gzip.py    From influxdb-client-python with MIT License 5 votes vote down vote up
def setUp(self) -> None:
        super(GzipSupportTest, self).setUp()
        # 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() 
Example #29
Source File: test_QueryApiDataFrame.py    From influxdb-client-python with MIT License 5 votes vote down vote up
def setUp(self) -> None:
        super(QueryDataFrameApi, self).setUp()
        # 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() 
Example #30
Source File: test_WriteApiBatching.py    From influxdb-client-python with MIT License 5 votes vote down vote up
def test_to_low_flush_interval(self):

        self._write_client.__del__()
        self._write_client = WriteApi(influxdb_client=self.influxdb_client,
                                      write_options=WriteOptions(batch_size=8,
                                                                 flush_interval=1,
                                                                 jitter_interval=1000))

        httpretty.register_uri(httpretty.POST, uri="http://localhost/api/v2/write", status=204)

        for i in range(50):
            val_one = float(i)
            val_two = float(i) + 0.5
            point_one = Point("OneMillis").tag("sensor", "sensor1").field("PSI", val_one).time(time=i)
            point_two = Point("OneMillis").tag("sensor", "sensor2").field("PSI", val_two).time(time=i)

            self._write_client.write("my-bucket", "my-org", [point_one, point_two])
            time.sleep(0.1)

        self._write_client.__del__()

        _requests = httpretty.httpretty.latest_requests

        for _request in _requests:
            body = _request.parsed_body
            self.assertTrue(body, msg="Parsed body should be not empty " + str(_request))

        httpretty.reset()