Example #1
0
    def _fake_popen(self, stdout, stderr, sleeptime):
        def wait_stdout(self):
            import time

            for line in stdout.splitlines():
                time.sleep(sleeptime)
                yield line

        def wait_stderr(self):
            import time

            for line in stderr.splitlines():
                time.sleep(sleeptime)
                yield line

        m = Mock(spec=subprocess.Popen)
        sout = Mock()
        sout.read = stdout
        sout.__iter__ = wait_stdout

        serr = Mock()
        serr.read = stderr
        serr.__iter__ = wait_stderr

        m.return_value.stdout = sout
        m.return_value.stderr = serr
        return m
Example #2
0
 def sideEffect(filePath, _mode):
     mockFile = Mock()
     if filePath == masterChangeSetFilePath:
         mockFile.read = Mock(return_value=mockMasterYaml)
     else:
         self.assertEqual("migrations/include1.yml", filePath)
         mockFile.read = Mock(return_value=mockIncludedYaml)
     return mockFile
Example #3
0
    def test_run(self, mock_execute):
        # Ensure execute returns a sensible result
        result = Mock()
        result.read = Mock(return_value=json.dumps({"result": "ok"}))
        mock_execute.return_value = result

        # Invoke run
        self.session.run("foo/bar")
        self.assertTrue(mock_execute.called)

        # Sanity check
        self.assertTrue(self.session.access_token is not None)

        # Verify call args
        args = mock_execute.call_args[0]
        self.assertEqual(args[0], "foo/bar")
        self.assertEqual(args[1], None)
        self.assertTrue(args[2].has_key("User-Agent"))
        self.assertTrue(args[2].has_key("Authorization"))

        # Invoke run
        data = {"one": 1}
        headers = {"two": 2}
        self.session.run("foo/bar", data, headers)
        self.assertTrue(mock_execute.called)

        args = mock_execute.call_args[0]
        self.assertEqual(args[0], "foo/bar")
        self.assertEqual(args[1], data)
        self.assertTrue(args[2].has_key("two"))

        # Unset asset_token and verify that the 'Authorization'
        # header is not added to the request.
        self.session.access_token = None
        self.session.auth = None

        self.session.run("foo/bar")
        self.assertTrue(mock_execute.called)

        args = mock_execute.call_args[0]
        self.assertFalse(args[2].has_key("Authorization"))

        # Verify that the run method will retry if execute returns
        # an expired_token response.
        result.read = Mock(return_value=json.dumps({"error": "expired_token"}))
        mock_execute.return_value = result

        with patch.object(Session, "renew_access_token") as mock_renew_access_token:
            self.session.run("foo/bar")
            self.assertTrue(mock_renew_access_token.called)
    def test_should_update_state_if_available(self):
        # Set
        app = NewrelicApp("1111", "777")
        headers = {"X-Api-Key": "1111"}
        url = "/v2/applications/777.json"

        # Mocks
        connection_obj = Mock()
        response_obj = Mock()
        httplib.HTTPConnection = Mock(return_value=connection_obj)

        response_obj.status = 200
        response_obj.read = Mock(return_value='{"some":"json"}')
        connection_obj.connect = Mock()
        connection_obj.request = Mock()
        connection_obj.getresponse = Mock(return_value=response_obj)

        # Assertion
        app.update_state()

        connection_obj.connect.assert_called_once()
        connection_obj.request.assert_called_once_with("GET", url, "", headers)
        connection_obj.getresponse.assert_called_once()

        self.assertEquals(app.raw_app, {"some": "json"})
        self.assertTrue(app.reachable)
    def test_should_not_update_state_if_unaavailable(self):
        # Set
        app = NewrelicApp("1111", "777")
        headers = {"X-Api-Key": "1111"}
        url = "/v2/applications/777.json"

        # Mocks
        connection_obj = Mock()
        response_obj = Mock()
        httplib.HTTPConnection = Mock(return_value=connection_obj)

        response_obj.status = 500  # Error
        response_obj.read = Mock(return_value="")
        connection_obj.connect = Mock()
        connection_obj.request = Mock()
        connection_obj.getresponse = Mock(return_value=response_obj)

        # Assertion
        app.update_state()

        connection_obj.connect.assert_called_once()
        connection_obj.request.assert_called_once_with("GET", url, "", headers)
        connection_obj.getresponse.assert_called_once()

        self.assertFalse(app.reachable)
Example #6
0
    def __init__(self, url=None, status_code=None, reason=None, headers=None, body=None):
        super(RequestsResponseMock, self).__init__()

        # hasattr call is protection against upstream changes in requests
        if hasattr(self, "url"):
            self.url = url
        else:
            raise AttributeError()

        if hasattr(self, "status_code"):
            self.status_code = status_code
        else:
            raise AttributeError()

        if hasattr(self, "reason"):
            self.reason = reason
        else:
            raise AttributeError()

        if hasattr(self, "headers"):
            self.headers = headers
        else:
            raise AttributeError()

        if hasattr(self, "raw"):
            stream = Mock()
            stream.read = Mock(side_effect=[body, None])
            stream.stream = Mock(side_effect=AttributeError())
            self.raw = stream
        else:
            raise AttributeError()
    def test_load_data(self):
        cached = {"products": {"prod1": "Product 1", "prod2": "Product 2"}, "tags": ["p1", "p2"]}
        mock_file = Mock()
        mock_file.read = Mock(return_value=json.dumps(cached))

        data = self.mgr._load_data(mock_file)
        self.assertEquals(data, cached)
Example #8
0
def test_crawl():
    html = """<html>
        <head>
            <title>Python is fun!</title>
        </head>
        <body>
            <div>Python is similar to Ruby, but different.</div>
        </body>
    </html>"""

    response_mock = Mock(url="http://expanded_url.com")
    response_mock.read = Mock(return_value=html)
    urllib2.urlopen = Mock(return_value=response_mock)
    url = "http://a.com"

    input_queue = Mock()
    input_queue.get = Mock(return_value=url)
    output_queue = Queue()

    crawler = Crawler()

    crawler.crawl(input_queue, output_queue)

    expected_result = {
        "CONTENT": html,
        "EXPANDED_URL": "http://expanded_url.com",
        "STATUS": "OK",
        "URL": "http://a.com",
    }

    eq_(expected_result, output_queue.get())
Example #9
0
    def test_not_validated_returned(self, mock_open):
        document = {}
        message = "hello"
        key_path = "/etc/pki/pulp/consumer/server/rsa_pub.pem"
        key = RSA.load_key_bio(BIO.MemoryBuffer(RSA_KEY))

        test_conf = {"server": {"rsa_pub": key_path}}
        self.plugin.pulp_conf.update(test_conf)

        mock_fp = Mock()
        mock_fp.read = Mock(return_value=RSA_PUB)
        mock_open.return_value = mock_fp

        # test
        try:
            patcher = patch("pulp.agent.gofer.pulpplugin.RSA")
            rsa = patcher.start()
            rsa.load_pub_key_bio.return_value.verify.return_value = False
            authenticator = self.plugin.Authenticator()
            self.assertRaises(ValidationFailed, authenticator.validate, document, message, key.sign(message))
        finally:
            if patcher:
                patcher.stop()

        # validation
        mock_open.assert_called_with(key_path)
        mock_fp.close.assert_called_with()
    def test_retrieve_of_json_data_from_api(self):
        json_response = json.dumps({"steps": ["step 1", "step 2"]})
        response_mock = Mock()
        response_mock.read = Mock(return_value=json_response)
        self.cache.get_authorized_response = Mock(return_value=response_mock)

        self.assertListEqual(self.cache.get_steps_information(), ["step 1", "step 2"])
Example #11
0
 def create_file_context_manager(*args, **kwargs):
     path = args[0]
     file_mock = Mock()
     file_mock.read = Mock(return_value=file_map[path])
     cm = Mock()
     cm.__enter__ = Mock(return_value=file_mock)
     cm.__exit__ = Mock()
     return cm
Example #12
0
 def test_receive_state(self):
     mi = Mock()
     mi.read = self.response
     interface = StateInterface(mi)
     device = InterfaceDevice(address=None, devices=interface, initial_state=State.UNKNOWN)
     self.assertEqual(device.state, State.UNKNOWN)
     self._response = State.ON
     time.sleep(2)
     self.assertEqual(device.state, State.ON)
Example #13
0
 def test_call_helper(self, transport):
     getresponse_mock = Mock()
     transport.return_value = getresponse_mock
     read_mock = Mock()
     read_mock.read = Mock(return_value="data!")
     getresponse_mock.getresponse = Mock(return_value=read_mock)
     s = HttpLibHttpService("host", 42, "path")
     r = s._call("body", {})
     self.assertIsInstance(r, tuple)
     self.assertEqual(len(r), 3)
    def test_load_s3_schema(self):
        mocked_json = '{"survey": "some_survey"}'
        mocked_connection = Mock()
        with patch("boto3.resource", Mock(return_value=mocked_connection)):
            mocked_file = Mock()
            mocked_file.read = Mock(return_value=mocked_json.encode())
            mocked_object = Mock()
            mocked_connection.Object = Mock(return_value=mocked_object)
            mocked_object.get.return_value = {"Body": mocked_file}

            self.assertEqual(json.loads(mocked_json), load_s3_schema_file("ignored_filename.json"))
Example #15
0
    def test_getNode(self):
        """

        @return:
        """
        uri = "vos://foo.com!vospace/bar"

        nodes = """
            <vos:nodes>
                <vos:node uri="vos://cadc.nrc.ca!vospace/mydir/file123" xs:type="vos:DataNode">
                    <vos:properties>
                        <vos:property uri='ivo://ivoa.net/vospace/core#date'>2016-05-10T09:52:13</vos:property>
                    </vos:properties>
                </vos:node>
                <vos:node uri="vos://cadc.nrc.ca!vospace/mydir/file456" xs:type="vos:DataNode">
                    <vos:properties>
                        <vos:property uri='ivo://ivoa.net/vospace/core#date'>2016-05-19T09:52:14</vos:property>
                    </vos:properties>
                </vos:node>
            </vos:nodes>
        """

        mock_vofile = Mock()
        client = Client()
        client.open = Mock(return_value=mock_vofile)

        mock_vofile.read = Mock(return_value=NODE_XML.format(uri, ""))
        my_node = client.get_node(uri, limit=0, force=False)
        self.assertEqual(uri, my_node.uri)
        self.assertEqual(len(my_node.node_list), 0)

        mock_vofile.read = Mock(return_value=NODE_XML.format(uri, nodes))

        my_node = client.get_node(uri, limit=2, force=True)
        self.assertEqual(uri, my_node.uri)
        self.assertEqual(len(my_node.node_list), 2)

        my_node = client.get_node(uri, limit=2, force=False)
        self.assertEqual(uri, my_node.uri)
        self.assertEqual(len(my_node.node_list), 2)
    def _set_up_mock_httplib(self, desired_response):
        mock_file = Mock()
        mock_file.read = Mock(return_value=desired_response)

        mock_r = Mock()

        mock_getresponse = Mock(return_value=mock_file)
        mock_r.getresponse = mock_getresponse

        mock_httplib = Mock(spec=httplib)
        mock_httplib.HTTPSConnection = Mock(return_value=mock_r)

        return mock_httplib
Example #17
0
class TestAPI(unittest.TestCase):
    def setUp(self):
        mapper = Mock()
        self.db = Mock()
        self.input = Mock()
        self.input.read.return_value = b'{"name":"test","period":1800}'
        self.req = {
            "CONTENT_TYPE": "application/json",
            "CONTENT_LENGTH": len(self.input.read()),
            "wsgi.input": self.input,
        }
        self.res = Mock()
        fuse.api.log = Mock()
        self.api = fuse.api.APIWrapper(config, self.db, mapper)
    def _mock_pkg_profile(packages):
        """
        Turn a list of package objects into an RPMProfile object.
        """

        dict_list = []
        for pkg in packages:
            dict_list.append(pkg.to_dict())

        mock_file = Mock()
        mock_file.read = Mock(return_value=json.dumps(dict_list))

        mock_profile = RPMProfile(from_file=mock_file)
        return mock_profile
    def test_call_paypal(self, urllib2_mock):
        mixin = PayPalFormMixin()

        response_mock = Mock()
        response_mock.read = Mock(return_value=self.paypal_response)
        urllib2_mock.urlopen.return_value = response_mock
        response = mixin.call_paypal(API_URL, {})
        self.assertEqual(
            response["ACK"], ["Success"], msg=("Should parse the response from paypal and return it as a dict")
        )

        with patch.object(mixin, "log_error") as log_error_mock:
            urllib2_mock.urlopen = PropertyMock(side_effect=HTTPException)
            mixin.call_paypal(API_URL, {})
            self.assertEqual(log_error_mock.call_count, 1, msg=("Should log an error if calling the PayPal API fails."))
Example #20
0
    def test_gifsicle_empty_result(self, mock_popen):
        """Test a call to gifsicle that has an empty result"""
        mock_image = Mock()
        mock_process = Mock()
        mock_process.communicate.return_value = ("", False)
        mock_popen.return_value = mock_process
        result, error = utils.resize_gif(mock_image, (300, 300))
        mock_popen.assert_called_once_with(
            ["gifsicle", "--resize-fit", "300x300"], stdin=self.mock_pipe, stdout=self.mock_pipe
        )
        self.assertEqual(mock_image.seek.call_count, 3)
        mock_process.communicate.assert_called_once_with(mock_image.read())

        self.assertEqual(result, "")
        self.assertEqual(error, True)
Example #21
0
    def _irregular_reader(self, items):
        def item_read(read_length):
            try:
                item = items.pop(0)
            except IndexError:
                # If no more items, the buffer is empty and would return empty string
                return ""

            return item.read(read_length)

        mock_fh = Mock()
        mock_fh.read = Mock()
        mock_fh.read.side_effect = item_read

        return mock_fh
    def setUpResponse(self, headers, body, status_code=200):
        if not headers:
            headers = {"Content-Type": "application/json"}

        def decode_content():
            pass

        response = Response()
        response.status_code = status_code
        response.headers = headers
        stream = Mock()
        stream.read = Mock()
        stream.read.side_effect = [body, None]
        response.raw = stream

        return response
Example #23
0
    def test_load(self, mock_open):
        mock_fp = Mock()
        mock_fp.read = Mock(return_value=RSA_KEY)
        mock_fp.__enter__ = Mock(return_value=mock_fp)
        mock_fp.__exit__ = Mock()
        mock_open.return_value = mock_fp

        # test

        authenticator = Authenticator()
        authenticator.load()

        # validation

        self.assertTrue(mock_fp.__exit__.called)
        self.assertTrue(isinstance(authenticator.rsa_key, RSA.RSA))
Example #24
0
    def test_attach_image_fp(self, mock_MIMEImage):
        mock_image_msg = Mock()
        mock_MIMEImage.return_value = mock_image_msg
        mock_message = Mock()
        self.email.msg_related = mock_message
        mock_fp = Mock()
        mock_data = mock_fp.read()
        self.email.attach_img(mock_fp, "test_img")

        assert_equal(1, mock_MIMEImage.call_count)

        mock_MIMEImage.assert_called_once_with(mock_data)
        assert_equal(2, mock_image_msg.add_header.call_count)
        mock_image_msg.add_header.assert_any_calls("Content-ID", "<test_img>")
        mock_image_msg.add_header.assert_any_calls("Content-Disposition", "inline")

        mock_message.attach.assert_called_once_with(mock_image_msg)
Example #25
0
    def open_mocker(self, filename):
        contents = {
            "/sys/bus/usb/devices/1-5/idVendor": "8086",
            "/sys/bus/usb/devices/1-1/idVendor": "12d1",
            "/sys/bus/usb/devices/1-8/idVendor": "12d1",
            "/sys/bus/usb/devices/1-1/idProduct": "14dc",
            "/sys/bus/usb/devices/1-8/idProduct": "15dc",
            "/sys/bus/usb/devices/usb1/idVendor": "8086",
            "/sys/bus/usb/devices/usb2/idVendor": "8086",
        }
        if filename not in contents:
            raise FileNotFoundError(filename)

        mock_file_handle = Mock()
        mock_file_handle.read = Mock(return_value=contents[filename])

        mock_object = Mock()
        mock_object.__enter__ = Mock(return_value=mock_file_handle)
        mock_object.__exit__ = Mock(return_value=False)
        return mock_object
    def test_build_digest(self, mock_open):
        data = "puppet-module"
        mock_fp = Mock()
        mock_fp.read = Mock(return_value=data)
        mock_fp.__enter__ = Mock(return_value=mock_fp)
        mock_fp.__exit__ = Mock()
        mock_open.return_value = mock_fp

        # test

        path = "/tmp/abc"
        digest = builder.digest(path)

        # validation

        h = sha256()
        h.update(data)

        mock_open.assert_called_with(path)
        self.assertEqual(digest, h.hexdigest())
Example #27
0
    def test_decrypt_file_should_handle_encrypted_file_where_line_break_is_in_initialization_vector(self):
        # setup

        # Inject an artifical iv with linebreaks in it
        iv_with_line_break = "123\n1234\n2341234\nt3jgeggggg\ng43g33g3g3af1"[: self.cryptor.block_size]

        random_generator = Mock()
        random_generator.read = Mock()
        random_generator.read.return_value = iv_with_line_break

        try:
            original_random_generator = self.cryptor.random_generator
            self.cryptor.random_generator = random_generator

            # test
            self.cryptor.encrypt_file(TEST_KEY, self.filepath["unencrypted"], self.filepath["test"])

            # Ensure ValueError is not raised
            self.cryptor.decrypt_file(TEST_KEY, self.filepath["test"], self.filepath["decryption-test-result"])
        finally:
            self.cryptor.random_generator = original_random_generator
Example #28
0
    def test_not_validated(self, mock_open):
        document = {}
        message = "hello"
        key_path = "/etc/pki/pulp/consumer/server/rsa_pub.pem"
        key = RSA.load_key_bio(BIO.MemoryBuffer(OTHER_KEY))

        test_conf = {"server": {"rsa_pub": key_path}}
        self.plugin.pulp_conf.update(test_conf)

        mock_fp = Mock()
        mock_fp.read = Mock(return_value=RSA_PUB)
        mock_open.return_value = mock_fp

        # test

        authenticator = self.plugin.Authenticator()
        self.assertRaises(ValidationFailed, authenticator.validate, document, message, key.sign(message))

        # validation
        mock_open.assert_called_with(key_path)
        mock_fp.close.assert_called_with()
Example #29
0
    def test_signing(self, mock_open):
        message = "hello"
        key_path = "/etc/pki/pulp/rsa.pem"
        key = RSA.load_key_bio(BIO.MemoryBuffer(RSA_KEY))

        test_conf = {"authentication": {"rsa_key": key_path}}
        self.plugin.pulp_conf.update(test_conf)

        mock_fp = Mock()
        mock_fp.read = Mock(return_value=RSA_KEY)
        mock_open.return_value = mock_fp

        # test

        authenticator = self.plugin.Authenticator()
        signature = authenticator.sign(message)

        # validation
        mock_open.assert_called_with(key_path)
        self.assertEqual(signature, key.sign(message))
        mock_fp.close.assert_called_with()
Example #30
0
    def test_mock(self):
        html = """
        <html>
            <head>
                <title>Python is fun!</title>
            </head>
            <body>
                <div><Python is similar to Ruby, but different./div>
            </body>
        </html>
        """

        url = "http://a.com"
        response_mock = Mock(url=url)
        response_mock.read = Mock(return_value=html)

        urllib2.urlopen = Mock(return_value=response_mock)

        resp = urllib2.urlopen("http://a.com")

        self.assertEqual(html, resp.read())
        self.assertEqual(url, resp.url)