Example #1
0
    def test_nodetype(self):
        mock_node = MagicMock(id=333)
        mock_node.type = "vos:ContainerNode"
        client = Client()
        client.get_node = Mock(return_value=mock_node)
        self.assertEquals("vos:ContainerNode", client._node_type("vos:/somenode"))
        self.assertTrue(client.isdir("vos:/somenode"))

        mock_node.type = "vos:DataNode"
        self.assertEquals("vos:DataNode", client._node_type("vos:/somenode"))
        self.assertTrue(client.isfile("vos:/somenode"))

        # through a link
        mock_node.type = "vos:ContainerNode"
        mock_link_node = Mock(type="vos:LinkNode")
        mock_link_node.target = "vos:/somefile"
        client.get_node = Mock(side_effect=[mock_link_node, mock_node, mock_link_node, mock_node])
        self.assertEquals("vos:ContainerNode", client._node_type("vos:/somenode"))
        self.assertTrue(client.isdir("vos:/somenode"))

        # through an external link - not sure why the type is DataNode in this case???
        mock_link_node.target = "/somefile"
        client.get_node = Mock(side_effect=[mock_link_node, mock_link_node])
        self.assertEquals("vos:DataNode", client._node_type("vos:/somenode"))
        self.assertTrue(client.isfile("vos:/somenode"))
 def __loaded_slidelayout(self, prs_slidemaster=None):
     """
     Return _SlideLayout instance loaded using mocks. *prs_slidemaster* is
     an already-loaded model-side _SlideMaster instance (or mock, as
     appropriate to calling test).
     """
     # partname for related slideMaster
     sldmaster_partname = "/ppt/slideMasters/slideMaster1.xml"
     # path to test slideLayout XML
     slidelayout_path = absjoin(test_file_dir, "slideLayout1.xml")
     # model-side slideMaster part
     if prs_slidemaster is None:
         prs_slidemaster = Mock(spec=_SlideMaster)
     # a part dict containing the already-loaded model-side slideMaster
     loaded_part_dict = {sldmaster_partname: prs_slidemaster}
     # a slideMaster package part for rel target
     pkg_slidemaster_part = Mock(spec=pptx.packaging.Part)
     pkg_slidemaster_part.partname = sldmaster_partname
     # a package-side relationship from slideLayout to its slideMaster
     rel = Mock(name="pptx.packaging._Relationship")
     rel.rId = "rId1"
     rel.reltype = RT_SLIDE_MASTER
     rel.target = pkg_slidemaster_part
     # the slideLayout package part to send to _load()
     pkg_slidelayout_part = Mock(spec=pptx.packaging.Part)
     pkg_slidelayout_part.relationships = [rel]
     with open(slidelayout_path, "rb") as f:
         pkg_slidelayout_part.blob = f.read()
     # _load and return
     slidelayout = _SlideLayout()
     return slidelayout._load(pkg_slidelayout_part, loaded_part_dict)
    def test_sendEvent_should_use_kwargs_as_event_items(self):
        mock_broadcaster = Mock(WampBroadcaster)
        mock_broadcaster.target = "broadcaster-target"
        mock_broadcaster.logger = Mock()
        mock_broadcaster.client = Mock()

        WampBroadcaster._sendEvent(
            mock_broadcaster,
            "event-id",
            "event-data",
            tracking_id="tracking-id",
            target="target",
            state="foobar",
            bar="baz",
        )

        actual_call = mock_broadcaster.client.publish.call_args
        self.assertEqual(
            call(
                "target",
                {
                    "payload": "event-data",
                    "type": "event",
                    "id": "event-id",
                    "tracking_id": "tracking-id",
                    "target": "target",
                    "state": "foobar",
                    "bar": "baz",
                },
            ),
            actual_call,
        )
Example #4
0
 def test_remove_effect(self):
     effect = Mock()
     effect.target = self.unit
     self.unit.effects.append(effect)
     self.unit.remove_effect(effect)
     self.assertEquals(len(self.unit.effects), 0)
     self.assertTrue(effect.target is None)
Example #5
0
    def test_should_create_process_protocol_with_no_tracking_id_if_not_given(self, mock_protocol, mock_reactor):
        mock_protocol.return_value = "mock-protocol"
        mock_receiver = Mock(Receiver)
        mock_receiver.states = {None: Mock()}
        mock_broadcaster = Mock()
        mock_receiver.broadcaster = mock_broadcaster
        mock_receiver.get_target_directory.return_value = "/etc/yadtshell/targets/devabc123"

        mock_receiver.configuration = {
            "hostname": "hostname",
            "python_command": "/usr/bin/python",
            "script_to_execute": "/usr/bin/yadtshell",
        }

        mock_event = Mock(Event)
        mock_event.target = "devabc123"
        mock_event.command = "yadtshell"
        mock_event.arguments = ["update"]

        Receiver.perform_request(mock_receiver, mock_event, Mock())

        expected_command_with_arguments = "/usr/bin/python /usr/bin/yadtshell update"

        self.assertEqual(
            call("hostname", mock_broadcaster, "devabc123", expected_command_with_arguments, tracking_id=None),
            mock_protocol.call_args,
        )
Example #6
0
def default_args():
    args = Mock()
    args.conf_file = ".lamvery.yml"
    args.dry_run = True
    args.publish = True
    args.alias = None
    args.version = None
    args.target = None
    return args
 def test_by_address_with_srv(self):
     with patch("dns.resolver.query") as query:
         answer = Mock()
         answer.target = "different.example.org."
         answer.port = 12345
         query.return_value = [answer]
         self.server = MinecraftServer.lookup("example.org")
         query.assert_called_once_with("_minecraft._tcp.example.org", "SRV")
     self.assertEqual(self.server.host, "different.example.org")
     self.assertEqual(self.server.port, 12345)
Example #8
0
def _learning_curve(learning_curve):
    X = np.array([[0, 1], [1, 0], [1, 1]] * 100, dtype=float)
    X[:, 1] += np.random.random((300)) - 0.5
    y = np.array([0, 0, 1] * 100)

    dataset = Mock()
    dataset.train_test_split.return_value = train_test_split(X, y)
    dataset.data = X
    dataset.target = y

    return learning_curve(dataset, LogisticRegression(), steps=5, verbose=1)
Example #9
0
 def test_get_info_list(self):
     # list tuples of a LinkNode
     mock_node = MagicMock(type="vos:DataNode")
     mock_node.return_value = mock_node
     mock_node.name = "testnode"
     mock_node.get_info.return_value = {"name": "aa"}
     mock_link_node = Mock(type="vos:LinkNode")
     mock_link_node.target = "vos:/somefile"
     client = Client()
     client.get_node = MagicMock(side_effect=[mock_link_node, mock_node])
     self.assertEquals({"testnode": mock_node.get_info.return_value}.items(), client.get_info_list("vos:/somenode"))
    def test_should_vote_when_handling_request(self, uuid_fun):
        uuid_fun.return_value = "1234-5678"
        receiver = Mock(Receiver)
        receiver.broadcaster = Mock()
        receiver.states = {'foo': None}
        event = Mock()
        event.arguments = ['--tracking-id=foo']
        event.target = 'target'
        Receiver.handle_request(receiver, event)

        receiver.broadcaster._sendEvent.assert_called_with(
            'vote', data='1234-5678', tracking_id='foo', target='target')
Example #11
0
def mock_context():
    @contextlib.contextmanager
    def target(*args):
        ctx.push(*args)
        yield
        ctx.pop()

    ctx = Mock(name="context", spec=["push", "pop", "peek"])
    ctx.formatter = JSONFormatter()
    ctx.build_resource_uri = lambda resource: "uri://" + resource.resource_path
    ctx.target = target
    return ctx
Example #12
0
def test_search(grid_search, Dataset, main):
    from ..learn import search

    dataset = Mock()
    dataset.data = np.array([[1], [2]])
    dataset.target = np.array([1, 2])
    Dataset.return_value = dataset
    main.arguments = {"<model_name>": "lr"}
    result = search()
    assert result is grid_search.return_value
    assert grid_search.call_args[0][0] is dataset
    assert isinstance(grid_search.call_args[0][1], Pipeline)
    assert isinstance(grid_search.call_args[0][2], dict)
Example #13
0
def test_grid_search():
    from ..grid_search import grid_search

    dataset = Mock()
    dataset.data = np.array([[1, 2, 3], [3, 3, 3]] * 20)
    dataset.target = np.array([0, 1] * 20)
    pipeline = LogisticRegression()
    parameters = dict(C=[1.0, 3.0])

    result = grid_search(dataset, pipeline, parameters)
    assert isinstance(result, GridSearchCV)
    assert hasattr(result, "best_estimator_")
    assert hasattr(result, "best_score_")
Example #14
0
def create_mock_formulabase():
    """ Generate a formulabase object that does nothing, and returns no errors """
    mock_formulabase = Mock(spec=FormulaBase)
    mock_formulabase.side_effect = lambda *args, **kw: mock_formulabase
    mock_formulabase.should_run.return_value = True
    mock_formulabase.resolve.return_value = None
    mock_formulabase.prompt.return_value = None
    mock_formulabase.sync.return_value = None
    mock_formulabase.target = True
    for phase in PHASE.values:
        setattr(mock_formulabase, phase.name, Mock(return_value=None))

    return mock_formulabase
Example #15
0
    def test_should_publish_event_about_failed_command_on_target(self, mock_log):
        mock_receiver = Mock(Receiver)
        mock_broadcaster = Mock()
        mock_receiver.broadcaster = mock_broadcaster

        mock_event = Mock(Event)
        mock_event.target = "devabc123"
        mock_event.tracking_id = "any-tracking-id"
        mock_event.command = "yadtshell"
        mock_event.arguments = ["update"]

        Receiver.publish_failed(mock_receiver, mock_event, "It failed!")

        mock_broadcaster.publish_cmd_for_target.assert_called_with(
            "devabc123", "yadtshell", "failed", "It failed!", tracking_id="any-tracking-id"
        )
        self.assertEqual(yadtreceiver.METRICS["commands_failed.devabc123"], 1)
    def test_sendEvent_should_publish_expected_event_on_default_target(self):
        mock_broadcaster = Mock(WampBroadcaster)
        mock_broadcaster.target = "broadcaster-target"
        mock_broadcaster.logger = Mock()
        mock_broadcaster.client = Mock()

        WampBroadcaster._sendEvent(mock_broadcaster, "event-id", "event-data", tracking_id="tracking-id")

        actual_call = mock_broadcaster.client.publish.call_args
        self.assertEqual(
            call(
                "broadcaster-target",
                {
                    "payload": "event-data",
                    "type": "event",
                    "id": "event-id",
                    "tracking_id": "tracking-id",
                    "target": "broadcaster-target",
                },
            ),
            actual_call,
        )
Example #17
0
    def test_should_publish_event_about_started_command_on_target(self, mock_log):
        mock_receiver = Mock(Receiver)
        mock_receiver.configuration = {"hostname": "hostname"}
        mock_broadcaster = Mock()
        mock_receiver.broadcaster = mock_broadcaster

        mock_event = Mock(Event)
        mock_event.tracking_id = "any-tracking-id"
        mock_event.target = "devabc123"
        mock_event.command = "yadtshell"
        mock_event.arguments = ["update"]

        Receiver.publish_start(mock_receiver, mock_event)

        mock_broadcaster.publish_cmd_for_target.assert_called_with(
            "devabc123",
            "yadtshell",
            "started",
            "(hostname) target[devabc123] request: command=\"yadtshell\", arguments=['update']",
            tracking_id="any-tracking-id",
        )
        self.assertEqual(yadtreceiver.METRICS["commands_started.devabc123"], 1)
Example #18
0
    def test_should_broadcast_error_when_spawning_fails(self, mock_protocol, mock_reactor):
        mock_protocol.side_effect = RuntimeError("Booom!")
        mock_receiver = Mock(Receiver)
        mock_broadcaster = Mock()
        mock_receiver.broadcaster = mock_broadcaster
        mock_receiver.get_target_directory.return_value = "/etc/yadtshell/targets/devabc123"
        mock_receiver.states = {None: Mock()}

        mock_receiver.configuration = {
            "hostname": "hostname",
            "python_command": "/usr/bin/python",
            "script_to_execute": "/usr/bin/yadtshell",
        }

        mock_event = Mock(Event)
        mock_event.target = "devabc123"
        mock_event.command = "yadtshell"
        mock_event.arguments = ["update"]

        Receiver.perform_request(mock_receiver, mock_event, Mock())

        mock_receiver.publish_failed.assert_called_with(mock_event, "<type 'exceptions.RuntimeError'> : Booom!")
Example #19
0
    def test_should_publish_failed_event_with_stderr_from_process(self, mock_log):
        mock_protocol = Mock(ProcessProtocol)
        mock_broadcaster = Mock()
        mock_protocol.broadcaster = mock_broadcaster
        mock_protocol.hostname = "hostname"
        mock_protocol.target = "dev123"
        mock_protocol.readable_command = "/usr/bin/python abc"
        mock_protocol.tracking_id = "tracking_id"
        mock_protocol.error_buffer = StringIO("Someone has shut down the internet.")

        ProcessProtocol.publish_failed(mock_protocol, 123)

        self.assertEquals(
            call(
                "dev123",
                "/usr/bin/python abc",
                "failed",
                message="Someone has shut down the internet.",
                tracking_id="tracking_id",
            ),
            mock_broadcaster.publish_cmd_for_target.call_args,
        )
        self.assertEqual(METRICS["commands_failed.dev123"], 1)
Example #20
0
    def test_should_publish_finished_event(self):
        mock_protocol = Mock(ProcessProtocol)
        mock_broadcaster = Mock()
        mock_protocol.broadcaster = mock_broadcaster
        mock_protocol.hostname = "hostname"
        mock_protocol.target = "dev123"
        mock_protocol.readable_command = "/usr/bin/python abc"
        mock_protocol.tracking_id = "tracking-id"
        mock_protocol.error_buffer = Mock()

        ProcessProtocol.publish_finished(mock_protocol)

        self.assertEquals(
            call(
                "dev123",
                "/usr/bin/python abc",
                "finished",
                '(hostname) target[dev123] request finished: "/usr/bin/python abc" succeeded.',
                tracking_id="tracking-id",
            ),
            mock_broadcaster.publish_cmd_for_target.call_args,
        )
        self.assertEqual(METRICS["commands_succeeded.dev123"], 1)
 def test__load_sets_slidelayout(self):
     """_Slide._load() sets slidelayout"""
     # setup ------------------------
     path = os.path.join(thisdir, "test_files/slide1.xml")
     slidelayout = Mock(name="slideLayout")
     slidelayout.partname = "/ppt/slideLayouts/slideLayout1.xml"
     rel = Mock(name="pptx.packaging._Relationship")
     rel.rId = "rId1"
     rel.reltype = RT_SLIDE_LAYOUT
     rel.target = slidelayout
     pkgpart = Mock(name="pptx.packaging.Part")
     with open(path, "rb") as f:
         pkgpart.blob = f.read()
     pkgpart.relationships = [rel]
     part_dict = {slidelayout.partname: slidelayout}
     slide = self.sld._load(pkgpart, part_dict)
     # exercise ---------------------
     retval = slide.slidelayout
     # verify -----------------------
     expected = slidelayout
     actual = retval
     msg = "expected: %s, got %s" % (expected, actual)
     self.assertEqual(expected, actual, msg)
Example #22
0
    def test_should_spawn_new_process_on_reactor_even_when_not_registered(self, _, mock_protocol, mock_reactor):
        mock_protocol.return_value = "mock-protocol"
        mock_receiver = Mock(Receiver)
        mock_broadcaster = Mock()
        mock_receiver.broadcaster = mock_broadcaster
        mock_receiver.get_target_directory.return_value = "/etc/yadtshell/targets/devabc123"
        mock_receiver.states = {}

        mock_receiver.configuration = {
            "hostname": "hostname",
            "python_command": "/usr/bin/python",
            "script_to_execute": "/usr/bin/yadtshell",
        }

        mock_event = Mock(Event)
        mock_event.target = "devabc123"
        mock_event.command = "yadtshell"
        mock_event.arguments = ["update"]

        Receiver.perform_request(mock_receiver, mock_event, Mock())

        self.assertEquals(
            call(
                "hostname", mock_broadcaster, "devabc123", "/usr/bin/python /usr/bin/yadtshell update", tracking_id=None
            ),
            mock_protocol.call_args,
        )
        self.assertEquals(
            call(
                "mock-protocol",
                "/usr/bin/python",
                ["/usr/bin/python", "/usr/bin/yadtshell", "update"],
                path="/etc/yadtshell/targets/devabc123",
                env={},
            ),
            mock_reactor.spawnProcess.call_args,
        )