Example #1
0
def get_mock():
    ysc = youtube_status_code
    yu = youtube_url
    yc = youtube_cookies
    yt = youtube_text
    yh = youtube_headers
    yosc = youtube_oembed_status_code
    you = youtube_oembed_url
    yoh = youtube_oembed_headers
    yot = youtube_oembed_text

    mock_obj_1 = Mock()
    mock_obj_1.status_code = ysc
    mock_obj_1.url = yu
    mock_obj_1.headers = yh
    mock_obj_1.cookies = yc
    mock_obj_1.text = yt
    mock_obj_1.json = lambda: json.loads(mock_obj_1.text)

    mock_obj_2 = Mock()
    mock_obj_2.status_code = 200
    mock_obj_2.url = you
    mock_obj_2.headers = yoh
    mock_obj_2.text = yot
    mock_obj_2.json = lambda: json.loads(mock_obj_2.text)

    return [mock_obj_1, mock_obj_1, mock_obj_2]
Example #2
0
def mock_response(fixture=None, status=200):
    response = Mock()
    if fixture is None:
        response.text = ""
    elif isinstance(fixture, dict):
        response.text = str(fixture)
    else:
        response.text = load_fixture(fixture)
    response.status_code = status
    return response
Example #3
0
    def mock_response(self, status_code, headers, data):
        mock_response = Mock()
        mock_response.status_code = status_code
        mock_response.headers = headers
        mock_response.text = json.dumps(data)

        self.request_mock.return_value = mock_response
Example #4
0
    def _verify(self, requests, response_text="", assertion=EXPIRED_ASSERTION, status_code=200):
        response = Mock()
        response.text = response_text
        response.status_code = status_code
        requests.request.return_value = response

        return self.verifier.verify(assertion)
Example #5
0
 def post(url, data, verify=True):
     response = Mock()
     if not post.called:
         response.status_code = 404
         post.called = True
     response.text = "I AINT NO JSON, FOOL!"
     return 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_wrong_id(self):
     """ Raise due to wrong ID """
     resp = Mock(name="Mock Response")
     resp.text = '{"id":"FOO", "result":"pong", "error":null}'
     resp.status_code = 200
     with self.assertRaises(exceptions.IdError):
         self.c._parse_resp("FOO2", resp)
Example #8
0
def default_args():
    args = Mock()
    args.conf_file = ".lamvery.yml"
    args.text = "foo"
    args.secret_name = "bar"
    args.store = False
    return args
Example #9
0
    def test_get_api_pod_parse_error(self, m_json_load, m_session):
        # Set up driver.
        self.driver.pod_name = "pod-1"
        self.driver.namespace = "a"
        pod1 = '{"metadata": {"namespace": "a", "name": "pod-1"}}'

        api_root = "http://kubernetesapi:8080/api/v1/"
        self.driver.api_root = api_root

        # Set up mock objects
        self.driver.auth_token = "TOKEN"

        m_json_load.side_effect = TypeError

        get_obj = Mock()
        get_obj.status_code = 200
        get_obj.text = pod1

        m_session_obj = Mock()
        m_session_obj.headers = Mock()
        m_session_obj.get.return_value = get_obj

        m_session.return_value = m_session_obj
        m_session_obj.__enter__ = Mock(return_value=m_session_obj)
        m_session_obj.__exit__ = Mock(return_value=False)

        # Call method under test
        assert_raises(ApplyProfileError, self.driver._get_api_pod)
    def test_registration(self):
        """
        Test handle registration and subsequent checks.
        """
        client = self.portal.handle_client

        response = Mock()
        response.status_code = 201
        response.headers = {"location": self.handle_url}
        client.session.post = Mock(return_value=response)

        view = self.portal.page.restrictedTraverse("hasHandle")

        self.assertEqual(view.create(), self.handle_url)
        self.assertTrue(view.hasHandle())
        self.assertEqual(view.handle(), self.handle)

        response.status_code = 204
        response.text = ""
        client.session.get = Mock(return_value=response)
        client.session.put = Mock(return_value=response)
        client.session.delete = Mock(return_value=response)

        self.assertEqual(view.read(), self.handle_url)
        self.assertEqual(view.update(), self.handle_url)

        self.assertTrue(view.hasDeletePermission())
        self.assertEqual(view.delete(), None)
Example #11
0
    def test_get_api_pod_with_client_certs(self, m_json_load, m_session):
        # Set up driver.
        self.driver.pod_name = "pod-1"
        self.driver.namespace = "a"
        pod1 = '{"metadata": {"namespace": "a", "name": "pod-1"}}'

        api_root = "http://kubernetesapi:8080/api/v1/"
        self.driver.api_root = api_root
        self.driver.client_certificate = "cert.pem"
        self.driver.client_key = "key.pem"
        self.driver.certificate_authority = "ca.pem"

        get_obj = Mock()
        get_obj.status_code = 200
        get_obj.text = pod1

        m_session_obj = Mock()
        m_session_obj.headers = Mock()
        m_session_obj.get.return_value = get_obj

        m_session.return_value = m_session_obj
        m_session_obj.__enter__ = Mock(return_value=m_session_obj)
        m_session_obj.__exit__ = Mock(return_value=False)

        # Call method under test
        self.driver._get_api_pod()

        # Assert correct data in calls.
        m_session_obj.get.assert_called_once_with(
            api_root + "namespaces/a/pods/pod-1", verify="ca.pem", cert=("cert.pem", "key.pem")
        )
        m_json_load.assert_called_once_with(pod1)
Example #12
0
    def test_get_api_pod(self, m_json_load, m_session):
        # Set up driver.
        self.driver.pod_name = "pod-1"
        self.driver.namespace = "a"
        pod1 = '{"metadata": {"namespace": "a", "name": "pod-1"}}'

        api_root = "http://kubernetesapi:8080/api/v1/"
        self.driver.api_root = api_root

        # Set up mock objects
        self.driver.auth_token = "TOKEN"

        get_obj = Mock()
        get_obj.status_code = 200
        get_obj.text = pod1

        m_session_obj = Mock()
        m_session_obj.headers = Mock()
        m_session_obj.get.return_value = get_obj

        m_session.return_value = m_session_obj
        m_session_obj.__enter__ = Mock(return_value=m_session_obj)
        m_session_obj.__exit__ = Mock(return_value=False)

        # Call method under test
        self.driver._get_api_pod()

        # Assert correct data in calls.
        m_session_obj.headers.update.assert_called_once_with({"Authorization": "Bearer " + "TOKEN"})
        m_session_obj.get.assert_called_once_with(api_root + "namespaces/a/pods/pod-1", verify=False)
        m_json_load.assert_called_once_with(pod1)
    def test_get_api_path(self, m_json_load, m_session):
        """Test _get_api_path

        Test for correct calls in _get_api_path.
        """
        # Set up mock objects
        self.plugin.auth_token = "TOKEN"
        m_session_return = Mock()
        m_session_return.headers = Mock()
        m_get_return = Mock()
        m_get_return.text = "response_body"
        m_session_return.get.return_value = m_get_return
        m_session.return_value = m_session_return

        # Initialize args
        path = "path/to/api/object"

        # Call method under test
        self.plugin._get_api_path(path)

        # Assert correct data in calls.
        m_session_return.headers.update.assert_called_once_with({"Authorization": "Bearer " + "TOKEN"})
        m_session_return.get.assert_called_once_with(
            calico_kubernetes.KUBE_API_ROOT + "path/to/api/object", verify=False
        )
        m_json_load.assert_called_once_with("response_body")
    def test_get_pod_config(self, m_json_load, m_secure, m_session):
        """Test _get_pod_config Success

        Test for correct calls in _get_api_path.
        """
        # Set up class member
        self.plugin.pod_name = "pod-1"
        self.plugin.namespace = "a"
        pod1 = '{"metadata": {"namespace": "a", "name": "pod-1"}}'

        # Set up mock objects
        m_secure.return_value = True
        self.plugin.auth_token = "TOKEN"

        get_obj = Mock()
        get_obj.status_code = 200
        get_obj.text = pod1

        m_session_obj = Mock()
        m_session_obj.headers = Mock()
        m_session_obj.get.return_value = get_obj

        m_session.return_value = m_session_obj
        m_session_obj.__enter__ = Mock(return_value=m_session_obj)
        m_session_obj.__exit__ = Mock(return_value=False)

        # Call method under test
        api_root = "http://kubernetesapi:8080/api/v1/"
        self.plugin.api_root = api_root
        self.plugin._get_pod_config()

        # Assert correct data in calls.
        m_session_obj.headers.update.assert_called_once_with({"Authorization": "Bearer " + "TOKEN"})
        m_session_obj.get.assert_called_once_with(api_root + "namespaces/a/pods/pod-1", verify=False)
        m_json_load.assert_called_once_with(pod1)
Example #15
0
 def test_parse_response(self):
     """ Valid apicall """
     resp = Mock(name="Mock Response")
     resp.text = '{"id":"FOO", "result":"pong", "error":null}'
     resp.status_code = 200
     result = self.c._parse_resp("FOO", resp)
     self.assertEqual(dict(result="pong", error=None), result)
Example #16
0
    def _stubbed_get(self, url, params=None, auth=None):
        response = Mock()
        response.status_code = 200
        response.text = "\n".join(json.dumps(m) for m in self.messages)
        response.iter_lines.return_value = (json.dumps(m) for m in self.messages)

        return response
Example #17
0
 def test_parse_response_500(self):
     """ Deal gracefully with 500 errors """
     resp = Mock(name="Mock Response")
     resp.text = "A Server error occurred. Please contact the administrator."
     resp.status_code = 500
     with self.assertRaises(exceptions.RemoteError):
         self.c._parse_resp("FOO", resp)
    def test_submit_job(self, mock_g, mock_n, mock_k, mock_session_post):

        # Mock OpenStack clients and response to POST
        mock_image = {"name": test_image_name, "id": test_image_id}
        mock_gclient = Mock()
        mock_gclient.images = Mock()
        mock_gclient.images.list = Mock(return_value=[mock_image])
        mock_g.return_value = mock_gclient

        mock_flavor = Mock()
        mock_flavor.name = test_flavor_name
        mock_flavor.id = test_flavor_id
        mock_nclient = Mock()
        mock_nclient.flavors = Mock()
        mock_nclient.flavors.list = Mock(return_value=[mock_flavor])
        mock_n.return_value = mock_nclient

        mock_response = Mock()
        mock_response.text = test_job_id
        mock_response.status_code = 200
        mock_session_post.return_value = mock_response

        c = ProcClient(test_auth, host=test_host)

        # good submission using image and flavor names
        c.submit_job(test_job_works, test_image_name, test_flavor_name)
        mock_session_post.assert_called_once_with(test_job_url, params=test_params_works, files=test_files_works)

        mock_session_post.reset_mock()

        # good submission using image and flavor UUIDs
        c.submit_job(test_job_works, test_image_id, test_flavor_id)
        mock_session_post.assert_called_once_with(test_job_url, params=test_params_works, files=test_files_works)

        mock_session_post.reset_mock()

        # With nopost we should not do a POST
        c.submit_job(test_job_works, test_image_name, test_flavor_name, nopost=True)
        self.assertEqual(mock_session_post.call_count, 0)

        # failed submission due to bad image name
        with self.assertRaises(ValueError):
            c.submit_job(test_job_works, "bad_image", test_flavor_name)
        self.assertEqual(mock_session_post.call_count, 0)

        # failed submission due to bad flavor name
        with self.assertRaises(ValueError):
            c.submit_job(test_job_works, test_image_name, "yucky")
        self.assertEqual(mock_session_post.call_count, 0)

        # failed submission because no Executable line in job file
        with self.assertRaises(ValueError):
            c.submit_job(test_job_fails, test_image_name, test_flavor_name)
        self.assertEqual(mock_session_post.call_count, 0)

        # works without Executable by specifying jobscriptonvm
        c.submit_job(test_job_fails, test_image_name, test_flavor_name, jobscriptonvm=test_script_on_vm)
        mock_session_post.assert_called_once_with(test_job_url, params=test_params_on_vm, files=test_files_on_vm)

        mock_session_post.reset_mock()
Example #19
0
 def test_parse_response_invalid_json(self):
     """ Deal gracefully with an invaldi JSON response """
     resp = Mock(name="Mock Response")
     resp.text = "A Server error occurred. Please contact the administrator."
     resp.status_code = 200
     with self.assertRaises(exceptions.IndecipherableResponseError):
         self.c._parse_resp("FOO", resp)
Example #20
0
 def test_get_current_balance(self, mock_request):
     mock_response = Mock()
     mock_response.status_code = 200
     mock_response.text = "Some text data"
     mock_request.get.return_value = mock_response
     account = Account(Mock())
     self.assertEqual({"status": 200, "data": "Some text data"}, account.get_current_balance(1))
    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")
 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"
Example #23
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
Example #24
0
    def test_get_api_path(self):
        with patch.object(self.plugin, "_get_api_token", autospec=True) as m_api_token, patch(
            "integrations.kubernetes.calico_kubernetes.requests.Session", autospec=True
        ) as m_session, patch.object(json, "loads", autospec=True) as m_json_load:
            # Set up mock objects
            m_api_token.return_value = "Token"
            m_session_return = Mock()
            m_session_return.headers = Mock()
            m_get_return = Mock()
            m_get_return.text = "response_body"
            m_session_return.get.return_value = m_get_return
            m_session.return_value = m_session_return

            # Initialize args
            path = "path/to/api/object"

            # Call method under test
            self.plugin._get_api_path(path)

            # Assert
            m_api_token.assert_called_once_with()
            m_session.assert_called_once_with()
            m_session_return.headers.update.assert_called_once_with({"Authorization": "Bearer " + "Token"})
            m_session_return.get.assert_called_once_with(
                calico_kubernetes.KUBE_API_ROOT + "path/to/api/object", verify=False
            )
            m_json_load.assert_called_once_with("response_body")
Example #25
0
def get_mock_session(page_text):
    page_obj = Mock()
    page_obj.text = page_text
    page_obj.raise_for_status = Mock()
    session = requests.Session()
    session.get = Mock(return_value=page_obj)
    return page_obj, session
Example #26
0
 def test_get_with_fields_arguments(self, request):
     mock_response = Mock()
     mock_response.text = '{"talking_about_count": 309, "likes": 6201, "id": "138467959508514"}'
     mock_response.status_code = 200
     request.return_value = mock_response
     f = FBGraph()
     result = f.get("sproutsocialinc", {"fields": "likes,talking_about_count"})
     self.assertDictEqual(result, {"id": "138467959508514", "likes": 6201, "talking_about_count": 309})
Example #27
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"])
Example #28
0
def get_mock_no_oembed():
    mock = Mock()
    mock.status_code = youtube_status_code
    mock.url = youtube_url
    mock.cookies = youtube_cookies
    mock.text = "youtube_text"
    mock.json = lambda: json.loads(mock.text)
    return [mock]
 def test_request_token_response(self, requests, auth):
     "Return full response text without parsing key/secret."
     response = Mock()
     response.text = "oauth_token=token&oauth_token_secret=secret"
     requests.return_value = response
     request = self.factory.get("/login/")
     token = self.oauth.get_request_token(request, callback="/callback/")
     self.assertEqual(token, "oauth_token=token&oauth_token_secret=secret")
 def response(self):
     response = Mock()
     response.headers = {"status": "200", "content-type": "application/json"}
     resp_json = {"status": True, "error_code": None, "error_message": "", "data": self.test_data}
     response.json.return_value = resp_json
     response.content = json.dumps(resp_json)
     response.text = text_type(response.content)
     return response