Example #1
0
def generic_successful_response():
    mock_network_response = Mock(DefaultNetworkResponse)
    mock_network_response.content = b'{"message": "success"}'
    mock_network_response.status_code = 200
    mock_network_response.ok = True
    mock_network_response.raw = Mock()
    return mock_network_response
Example #2
0
def __one_bad_two_ok(*args):
    response = Mock()
    response.ok = args[0] == "http://example.com/oembed2"
    response.text = "hello, world"
    response.headers = {"content-type": "application/json"}

    return response
    def test_delete_passes(self, mock_login, mock_delete, mock_list_tags):
        """
        Test .delete() works
        """
        mock_login.return_value = self.account_id

        mock_response = Mock(spec=requests.Response)
        mock_response.status_code = 200
        mock_response.ok = True

        mock_delete.return_value = mock_response

        mock_list_tags.return_value = [
            {"id": "19dede15-118b-467f-bfe9-e9c771d7cc2c", "scheduled_query_id": "00000000-0000-469c-0000-000000000000"}
        ]

        alert = AnomalyAlert(self.username, self.password)

        alert.delete("19dede15-118b-467f-bfe9-e9c771d7cc2c")
        mock_delete.assert_has_calls(
            [
                call(
                    url="https://logentries.com/rest/{account_id}/api/tags/{tag}".format(
                        account_id=self.account_id, tag="19dede15-118b-467f-bfe9-e9c771d7cc2c"
                    )
                ),
                call(
                    url="https://logentries.com/rest/{account_id}/api/scheduled_queries/{query_id}".format(
                        account_id=self.account_id, query_id="00000000-0000-469c-0000-000000000000"
                    )
                ),
            ]
        )
Example #4
0
def non_json_response():
    mock_network_response = Mock(DefaultNetworkResponse)
    mock_network_response.content = b""
    mock_network_response.ok = True
    mock_network_response.status_code = 200
    mock_network_response.json.side_effect = ValueError("No JSON object could be decoded")
    return mock_network_response
Example #5
0
    def setUp(self):
        WebauthTestCase.setUp(self)

        # mock service for testing
        service = OAuth1Service(
            "example",
            consumer_key="123",
            consumer_secret="456",
            request_token_url="http://example.com/request_token",
            access_token_url="http://example.com/access_token",
            authorize_url="http://example.com/authorize",
        )
        self.service = service

        def raise_for_status(*args, **kwargs):
            raise Exception("Response not OK!")

        self.raise_for_status = raise_for_status

        # mock response for testing
        response = Mock()
        response.content = "oauth_token=123&oauth_token_secret=456"
        response.ok = True
        response.raise_for_status = lambda: None
        self.response = response
 def test_get_hash_success(self, m_get):
     mock_resp = Mock()
     mock_resp.ok = True
     mock_resp.text = "the_hash"
     m_get.return_value = mock_resp
     result = util.get_gitbuilder_hash()
     assert result == "the_hash"
Example #7
0
def test_token_request_allows_missing_refresh_token(mock_network_layer):
    mock_network_response = Mock()
    mock_network_response.ok = True
    mock_network_response.json.return_value = {"access_token": "fake_token"}
    mock_network_layer.request.return_value = mock_network_response
    oauth = OAuth2(client_id="", client_secret="", access_token="fake_access_token", network_layer=mock_network_layer)
    oauth.send_token_request({}, access_token=None, expect_refresh_token=False)
Example #8
0
 def test_arbitrary_member(self, mock_request):
     mock_response = Mock()
     mock_response.ok = True
     mock_response.content = json.dumps({"short_codes": []})
     mock_request.return_value = mock_response
     self.assertEqual([], self.client.sms.short_codes.list())
     mock_request.assert_called_once_with("GET", ANY, params=ANY, auth=AUTH, timeout=sentinel.timeout)
Example #9
0
 def test_get_hash_fail(self, m_get, m_get_gitbuilder_url):
     m_get_gitbuilder_url.return_value = "http://baseurl.com"
     mock_resp = Mock()
     mock_resp.ok = False
     m_get.return_value = mock_resp
     result = suite.get_hash()
     assert result is None
 def test_package_version_for_hash(self, m_get):
     mock_resp = Mock()
     mock_resp.ok = True
     mock_resp.text = "the_version"
     m_get.return_value = mock_resp
     result = util.package_version_for_hash("hash")
     assert result == "the_version"
    def test_load_post(self, RequestsGetMock):

        # set up a mock response with stubbed json to simulate the API
        def read_post_json():
            with open(os.path.join(os.path.dirname(__file__), "data", "post.json")) as post_json_file:
                return json.load(post_json_file)

        mock_response = Mock(Response)
        mock_response.ok = True
        mock_response.text = "some text"
        mock_response.json = read_post_json

        RequestsGetMock.return_value = mock_response

        # call we're testing
        post = self.loader.load_post(1)

        # some validations
        self.assertIsInstance(post, Post)
        self.assertEqual(post.wp_id, 1)
        self.assertEqual(post.title, "This is a Test Post")
        self.assertEqual(post.author.name, "testauthor")
        self.assertEqual(post.categories.first().name, "News")
        self.assertEqual(post.tags.first().name, "Testing")
        self.assertEqual(post.attachments.first().url, "https://test.local/testpost.jpg")
Example #12
0
File: base.py Project: jinnko/rauth
 def setUp(self):
     response = Mock()
     response.content = json.dumps({"status": "ok"})
     response.headers = {"Content-Type": "application/json"}
     response.ok = True
     response.status_code = requests.codes.ok
     self.response = response
Example #13
0
    def setUp(self):
        # mock request object
        request = Request()
        request.method = "GET"
        request.url = "http://example.com/"
        request.params = {}
        request.data = {}
        request.params_and_data = {}
        self.request = request

        # mock response object
        response = Mock()
        response.content = "access_token=321"
        response.headers = {"content-type": "text/html; charset=UTF-8"}
        response.ok = True
        response.status_code = 200
        self.response = response

        # mock raise_for_status with an error
        def raise_for_status():
            raise Exception("Response not OK!")

        self.raise_for_status = raise_for_status

        # mock hook object
        hook = Mock()
        hook.consumer_key = "123"
        hook.consumer_secret = "456"
        hook.access_token = "321"
        hook.access_token_secret = "654"
        self.hook = hook
    def test_create_scheduled_query_pass(self, mock_login, mock_post):
        """
        Test ._create_scheduled_query() passes
        """
        # simulate login
        mock_login.return_value = self.account_id

        # Create the response
        mock_response = Mock(spec=requests.Response)
        mock_response.status_code = 201
        mock_response.json.return_value = {"scheduled_query": {"id": "00000000-0000-03a2-0000-000000000000"}}
        mock_response.ok = True

        mock_post.return_value = mock_response

        session = requests.session()

        alert = AnomalyAlert(self.username, self.password, session)

        query = "where(status=404) calculate(COUNT)"
        scope_count = 1
        scope_unit = "day"
        change = "+15"

        # Call .create
        response = alert._create_scheduled_query(
            query=query, change=change, scope_count=scope_count, scope_unit=scope_unit
        )

        self.assertDictEqual(response, {"scheduled_query": {"id": "00000000-0000-03a2-0000-000000000000"}})
Example #15
0
    def setUp(self):
        WebauthTestCase.setUp(self)

        # mock service for testing
        service = OAuth2Service(
            "example",
            consumer_key="123",
            consumer_secret="456",
            access_token_url="http://example.com/access_token",
            authorize_url="http://example.com/authorize",
        )
        self.service = service

        def raise_for_status():
            raise Exception("Response not OK!")

        self.raise_for_status = raise_for_status

        # mock response for testing
        response = Mock()
        response.content = "access_token=321"
        response.ok = True
        response.status_code = 200
        response.raise_for_status = lambda: None
        self.response = response
Example #16
0
def test_should_raise_error_on_all_request_errors():
    with patch("requests.get") as mock_get, pytest.raises(consumer.PyEmbedConsumerError):
        response = Mock()
        response.ok = False
        response.text = "hello, world"
        mock_get.return_value = response

        consumer.get_first_oembed_response(["http://example.com/oembed1", "http://example.com/oembed2"])
def test_make_twilio_request_bad_data(mock):
    resp = Mock()
    resp.ok = False
    mock.return_value = resp

    url = "http://random/url"
    make_twilio_request("POST", url)
    mock.assert_called_with("POST", "http://random/url.json", headers=post_headers)
Example #18
0
def network_response_with_missing_tokens(request):
    mock_network_response = Mock(DefaultNetworkResponse)
    mock_network_response.ok = True
    json_dict = {}
    for key in request.param:
        json_dict[key] = "fake_token"
    mock_network_response.json.return_value = json_dict
    return mock_network_response
 def test_get_branch_info(self, m_get):
     mock_resp = Mock()
     mock_resp.ok = True
     mock_resp.json.return_value = "some json"
     m_get.return_value = mock_resp
     result = util.get_branch_info("teuthology", "master")
     m_get.assert_called_with("https://api.github.com/repos/ceph/teuthology/git/refs/heads/master")
     assert result == "some json"
Example #20
0
def generic_successful_response():
    mock_network_response = Mock(Response)
    content = '{"message": "success"}'
    mock_network_response.content = content.encode("utf-8")
    mock_network_response.status_code = 200
    mock_network_response.ok = True
    mock_network_response.raw = Mock()
    mock_network_response.json.return_value = json.loads(content)
    return mock_network_response
Example #21
0
 def test_package_version_for_hash(self, m_get, m_get_gitbuilder_url):
     m_get_gitbuilder_url.return_value = "http://baseurl.com"
     mock_resp = Mock()
     mock_resp.ok = True
     mock_resp.text = "the_version"
     m_get.return_value = mock_resp
     result = suite.package_version_for_hash("hash")
     m_get.assert_called_with("http://baseurl.com/sha1/hash/version")
     assert result == "the_version"
Example #22
0
 def test_get_hash_success(self, m_get, m_get_gitbuilder_url):
     m_get_gitbuilder_url.return_value = "http://baseurl.com"
     mock_resp = Mock()
     mock_resp.ok = True
     mock_resp.text = "the_hash"
     m_get.return_value = mock_resp
     result = suite.get_hash()
     m_get.assert_called_with("http://baseurl.com/ref/master/sha1")
     assert result == "the_hash"
Example #23
0
 def test_get_package_version_not_found(self, m_get_response):
     rem = self._get_remote()
     ctx = dict(foo="bar")
     resp = Mock()
     resp.ok = False
     m_get_response.return_value = resp
     gp = self.klass("ceph", {}, ctx=ctx, remote=rem)
     with pytest.raises(VersionNotFoundError):
         gp.version
    def testPassThrough(self, mock_request):
        mock_response = Mock()
        mock_response.ok = (True,)
        mock_response.content = json.dumps({"key": "value"})
        mock_request.return_value = mock_response

        assert_equal(self.r.timeout, sentinel.timeout)
        assert_equal((mock_response, {"key": "value"}), self.r.request("GET", base_uri))

        mock_request.assert_called_once_with("GET", base_uri + ".json", headers=ANY, timeout=sentinel.timeout, auth=ANY)
Example #25
0
def empty_events_response(final_stream_position):
    # pylint:disable=redefined-outer-name
    mock_box_response = Mock(BoxResponse)
    mock_network_response = Mock(DefaultNetworkResponse)
    mock_box_response.network_response = mock_network_response
    mock_box_response.json.return_value = mock_json = {"next_stream_position": final_stream_position, "entries": []}
    mock_box_response.content = json.dumps(mock_json).encode()
    mock_box_response.status_code = 200
    mock_box_response.ok = True
    return mock_box_response
Example #26
0
 def get_response(limit, offset):
     items_json, items = mock_items
     mock_box_response = Mock(BoxResponse)
     mock_network_response = Mock(DefaultNetworkResponse)
     mock_box_response.network_response = mock_network_response
     mock_box_response.json.return_value = mock_json = {"entries": items_json[offset : limit + offset]}
     mock_box_response.content = json.dumps(mock_json).encode()
     mock_box_response.status_code = 200
     mock_box_response.ok = True
     return mock_box_response, items[offset : limit + offset]
Example #27
0
def test_should_raise_if_error_reading_url():
    response = Mock()
    response.ok = False
    response.status_code = 404

    with patch("requests.get") as mock_get, pytest.raises(discovery.PyEmbedDiscoveryError):
        mock_get.return_value = response

        discoverer = discovery.UrlDiscoverer("http://example.com/providers.json")
        discoverer.get_oembed_urls("http://example.com/simple/123")
Example #28
0
def get_oembed_urls(fixture="valid_oembed.html", oembed_format=None, ok=True):
    with patch("requests.get") as mock_get:
        response = Mock()
        response.ok = ok
        response.text = open("pyembed/core/test/fixtures/auto_discovery/" + fixture).read()
        mock_get.return_value = response

        result = list(discovery.AutoDiscoverer().get_oembed_urls("http://example.com", oembed_format))

        mock_get.assert_called_with("http://example.com")
        return result
Example #29
0
def __set_up_mocks(mock_get, mock_parse, content_type="application/json"):
    response = Mock()
    response.ok = True
    response.text = "hello, world"
    response.headers = {"content-type": content_type}

    mock_get.return_value = response

    parsed = Mock()
    mock_parse.return_value = parsed
    return parsed
Example #30
0
 def test_get_package_sha1_fetched_not_found(self, m_get, m_get_config_value, m_config):
     m_config.baseurl_template = "http://{host}/{proj}-{pkg_type}-{dist}-{arch}-{flavor}/{uri}"
     m_config.gitbuilder_host = "gitbuilder.ceph.com"
     m_get_config_value.return_value = None
     resp = Mock()
     resp.ok = False
     m_get.return_value = resp
     rem = self._get_remote()
     ctx = dict(foo="bar")
     gp = packaging.GitbuilderProject("ceph", {}, ctx=ctx, remote=rem)
     assert not gp.sha1