def test_save_payment_arcs_command_mocked(self):
        command_with_item_forms = Mock()
        items = [
            PagSegItem(description="Python Birds", price=Decimal("18.99"), quantity=3),
            PagSegItem(
                description="Objetos Pythônicos", price=Decimal("24.99"), quantity=2, reference=ndb.Key(PagSegItem, 10)
            ),
        ]
        command_with_item_forms.items = items

        ndb.put_multi(items)
        payment = mommy.save_one(PagSegPayment)
        command_with_item_forms.result = payment

        payment_owner = mommy.save_one(Node)
        save_payment_arcs_cmd = SavePaymentArcsCmd(payment_owner)
        CommandSequential(command_with_item_forms, save_payment_arcs_cmd).execute()

        self.assertEqual(payment, pagseguro_facade.search_payments(payment_owner)()[0])

        logs = SearchLogs(payment)()
        self.assertEqual(1, len(logs))
        self.assertEqual(STATUS_CREATED, logs[0].status)

        self.assertListEqual(items, SearchItems(payment)())
Example #2
0
def test_run_interactive(capfd):
    """Ensure the calls to run a command on a list of hosts interactively."""

    runner = Bladerunner({"threads": 14})
    fake_result = Mock()
    fake_result.result = Mock(return_value="fake results")

    mock_con = Mock()
    runner.interactive_hosts = {"fake host": mock_con}

    fake_thread = Mock()
    fake_thread.__enter__ = fake_context
    fake_thread.__exit__ = fake_context
    fake_thread.submit = Mock(return_value=fake_result)

    threadpool_mock = patch.object(
        base,
        "ThreadPoolExecutor",
        return_value=fake_thread,
    )

    with patch.object(runner, "setup_interactive") as mock_setup:
        with threadpool_mock as mock_threadpool:
            runner.run_interactive("fake cmd", "fake host")

    mock_setup.assert_called_once_with("fake host")
    mock_threadpool.assert_called_once_with(max_workers=14)

    stdout, stderr = capfd.readouterr()
    assert stdout == "fake host: fake results\n"
    assert stderr == ""
Example #3
0
 def test_no_logged_user(self, cookie_facade):
     cmd_mock = Mock()
     cmd_mock.execute = Mock(return_value=cmd_mock)
     cmd_mock.result = None
     cookie_facade.retrive_cookie_data = Mock(return_value=cmd_mock)
     result = facade.logged_user(None).execute().result
     self.assertIsNone(result)
Example #4
0
    def test_get_user_stack_status_resume_after_suspend(self):
        self.init_block()

        now = int(time.time())
        suspend_timeout = self.block.configuration.get("suspend_timeout")
        suspend_timestamp = now - suspend_timeout
        self.block.stacks = {
            self.block.stack_name: {"suspend_timestamp": suspend_timestamp, "status": {"status": "CREATE_COMPLETE"}}
        }

        mock_result = Mock()
        mock_result.ready.return_value = True
        mock_result.successful.return_value = True
        mock_result.result = {"status": "RESUME_COMPLETE"}
        mock_launch_stack_task = Mock(return_value=mock_result)
        mock_suspend_user_stack = Mock()

        with patch.multiple(
            self.block, launch_stack_task=mock_launch_stack_task, suspend_user_stack=mock_suspend_user_stack
        ):
            data = {"initialize": True, "reset": False}
            result = self.call_handler("get_user_stack_status", data)

        self.assertEqual(result, mock_result.result)
        self.assertTrue(mock_launch_stack_task.called)
        self.assertTrue(mock_suspend_user_stack.called)
Example #5
0
def test_run_interactive_returns():
    """Confirm the dict return when print_results is False."""

    runner = Bladerunner({"threads": 17})
    fake_result = Mock()
    fake_result.result = Mock(return_value="some result")

    mock_con = Mock()
    runner.interactive_hosts = {"host": mock_con}

    fake_thread = Mock()
    fake_thread.__enter__ = fake_context
    fake_thread.__exit__ = fake_context
    fake_thread.submit = Mock(return_value=fake_result)

    threadpool_mock = patch.object(
        base,
        "ThreadPoolExecutor",
        return_value=fake_thread,
    )

    with patch.object(runner, "setup_interactive") as mock_setup:
        with threadpool_mock as mock_threadpool:
            results = runner.run_interactive("ok", "host", print_results=False)

    mock_setup.assert_called_once_with("host")
    mock_threadpool.assert_called_once_with(max_workers=17)

    assert results == {"host": "some result"}
    def test_save_item_arcs_command(self):
        command_with_item_forms = Mock()
        access_data = CreateOrUpdateAccessData("renzo@gmail.com", "abc1234")()

        items = [
            PagSegItem(description="Python Birds", price=Decimal("18.99"), quantity=3),
            PagSegItem(
                description="Objetos Pythônicos", price=Decimal("24.99"), quantity=2, reference=ndb.Key(PagSegItem, 10)
            ),
        ]
        command_with_item_forms.items = items

        address_form_mock = Mock()
        client_form_mock = Mock()

        command_with_item_forms.address_form = address_form_mock
        command_with_item_forms.client_form = client_form_mock
        command_with_item_forms.access_data = access_data

        ndb.put_multi(items)
        payment = mommy.save_one(PagSegPayment)
        command_with_item_forms.result = payment

        save_payment_to_items_arcs_cmd = SavePaymentToItemsArcs()
        CommandSequential(command_with_item_forms, save_payment_to_items_arcs_cmd).execute()

        self.assertListEqual(items, SearchItems(payment)())
        self.assertListEqual(items, save_payment_to_items_arcs_cmd.items)

        # Data used for sequential commands
        self.assertEqual("renzo@gmail.com", save_payment_to_items_arcs_cmd.access_data.email)
        self.assertEqual("abc1234", save_payment_to_items_arcs_cmd.access_data.token)
        self.assertEqual(save_payment_to_items_arcs_cmd.address_form, address_form_mock)
        self.assertEqual(save_payment_to_items_arcs_cmd.client_form, client_form_mock)
Example #7
0
 def test_logged_user(self, cookie_facade):
     user = mommy.save_one(MainUser)
     cmd_mock = Mock()
     cmd_mock.execute = Mock(return_value=cmd_mock)
     cmd_mock.result = {"id": user.key.id()}
     cookie_facade.retrive_cookie_data = Mock(return_value=cmd_mock)
     result = facade.logged_user(None).execute().result
     self.assertEqual(user, result)
Example #8
0
def make_fake_conn(receive_returns=None):
    receive_returns = receive_returns or (["{}"], "", 0)
    conn = Mock()
    conn.return_value = conn
    conn.execute = conn
    conn.receive = Mock(return_value=receive_returns)
    conn.result = Mock(return_value=conn)
    return conn
Example #9
0
def mock_protocol():
    mproto = Mock(RPCProtocol)

    foo = Mock(RPCResponse)
    foo.result = None

    mproto.parse_reply = Mock(return_value=foo)

    return mproto
Example #10
0
 def create_blank_response(cls, code, msg):
     response = Mock(spec=Response)
     response.responseCode = code
     mock_msg = Mock()
     mock_msg.message = msg
     response.details = [mock_msg]
     response.messageDEPRECATED = msg
     response.result = Mock(spec=Result)
     return response
Example #11
0
 def _get_output_for_task_success(self, attempted, succeeded, total, student=None):
     """returns the task_id and the result returned by instructor_task_status()."""
     # view task entry for task in progress
     instructor_task = self._create_progress_entry(student)
     task_id = instructor_task.task_id
     mock_result = Mock()
     mock_result.task_id = task_id
     mock_result.state = SUCCESS
     mock_result.result = {"attempted": attempted, "succeeded": succeeded, "total": total, "action_name": "rescored"}
     output = self._test_get_status_from_result(task_id, mock_result)
     return output
    def test_save_payment_to_log_command(self):
        command_with_item_forms = Mock()
        payment = mommy.save_one(PagSegPayment)
        command_with_item_forms.result = payment

        save_payment_to_log_cmd = SavePaymentToLog()
        CommandSequential(command_with_item_forms, save_payment_to_log_cmd).execute()

        logs = SearchLogs(payment)()
        self.assertEqual(1, len(logs))
        self.assertEqual(STATUS_CREATED, logs[0].status)
    def test_autodetect_import_csv_raises_on_failure_to_detect_encoding(self, mock_UniversalDetector):
        mock_detector = Mock()
        mock_UniversalDetector.return_value = mock_detector
        mock_detector.result = {"encoding": None}

        mock_file = StringIO()
        mock_file.write("\xFF\x00\xFF")
        mock_file.name = "filename"
        mock_file.size = 10

        self.assertRaises(DirigibleImportError, lambda: worksheet_from_csv(Worksheet(), mock_file, 1, 1, False))
    def test_execute(self, timeseries_mock):
        response = Mock()
        response.result = SAMPLE_DRUID_RESPONSE

        self.test_druid_check = DRUID_CHECK.copy()

        timeseries_mock.return_value = response

        with patch("alamo_worker.plugins.druid.DruidPlugin.process") as proc:
            self.druid.execute(self.test_druid_check)
            self.assertTrue(proc.called)
            proc.assert_called_once_with(self.test_druid_check, SAMPLE_DRUID_RESPONSE)
 def create_mock_status_query_result(cls, scheduleStatus):
     mock_query_result = Mock(spec=Response)
     mock_query_result.result = Mock(spec=Result)
     mock_query_result.result.scheduleStatusResult = Mock(spec=ScheduleStatusResult)
     if scheduleStatus == ScheduleStatus.INIT:
         # status query result for before job is launched.
         mock_query_result.result.scheduleStatusResult.tasks = []
     else:
         mock_task_one = cls.create_mock_task("hello", 0, 1000, scheduleStatus)
         mock_task_two = cls.create_mock_task("hello", 1, 1004, scheduleStatus)
         mock_query_result.result.scheduleStatusResult.tasks = [mock_task_one, mock_task_two]
     return mock_query_result
Example #16
0
 def test_update_progress_to_progress(self):
     # view task entry for task in progress
     instructor_task = self._create_progress_entry()
     task_id = instructor_task.task_id
     mock_result = Mock()
     mock_result.task_id = task_id
     mock_result.state = PROGRESS
     mock_result.result = {"attempted": 5, "succeeded": 4, "total": 10, "action_name": "rescored"}
     output = self._test_get_status_from_result(task_id, mock_result)
     self.assertEquals(output["message"], "Progress: rescored 4 of 5 so far (out of 10)")
     self.assertEquals(output["succeeded"], False)
     self.assertEquals(output["task_state"], PROGRESS)
     self.assertTrue(output["in_progress"])
     self.assertEquals(output["task_progress"], mock_result.result)
Example #17
0
 def decorated(self, *args, **kwargs):
     conn = Mock(name="conn")
     tmp = Mock(name="tmp")
     inject = Mock(name="inject")
     if em_side_effect is None:
         return_value = Mock(name="return_value")
         return_value.is_successful = Mock(return_value=em_successful)
         return_value.result = em_result
         e_m = Mock(name="execute_module", return_value=return_value)
     else:
         e_m = Mock(side_effect=em_side_effect)
     runner = Mock()
     runner._execute_module = e_m
     connection = self.connection_class(conn, tmp, inject, runner)
     return method(self, connection, conn, tmp, inject, runner, e_m, *args, **kwargs)
    def test_update_payment_and_save_log_command(self):
        command_with_item_forms = Mock()
        payment = mommy.save_one(PagSegPayment, status=STATUS_CREATED)
        command_with_item_forms.result = payment
        payment.status = STATUS_SENT_TO_PAGSEGURO

        save_payment_to_log_cmd = UpdatePaymentAndSaveLog()
        CommandSequential(command_with_item_forms, save_payment_to_log_cmd).execute()

        search = SearchLogs(payment)
        logs = search()
        self.assertEqual(1, len(logs))
        self.assertEqual(STATUS_SENT_TO_PAGSEGURO, logs[0].status)
        self.assertEqual(STATUS_SENT_TO_PAGSEGURO, payment.key.get().status)
        self.assertEqual(save_payment_to_log_cmd.result, payment)
    def test_buildsetFinished_sends_email(self):
        fakeBuildMessage = Mock()
        mn = MailNotifier("from@example.org", buildSetSummary=True, mode="all", builders=["Builder"])

        mn.buildMessage = fakeBuildMessage

        def fakeGetBuild(number):
            return build

        def fakeGetBuilder(buildername):
            if buildername == builder.name:
                return builder
            return None

        def fakeGetBuildRequests(self, bsid):
            return defer.succeed([{"buildername": "Builder", "brid": 1}])

        builder = Mock()
        builder.getBuild = fakeGetBuild
        builder.name = "Builder"

        build = Mock()
        build.result = FAILURE
        build.finished = True
        build.reason = "testReason"
        build.builder = builder
        build.getBuilder = Mock()
        build.getBuilder.return_value = builder

        self.db = fakedb.FakeDBConnector(self)
        self.db.insertTestData(
            [
                fakedb.Buildset(id=99, sourcestampid=127, results=SUCCESS, reason="testReason"),
                fakedb.BuildRequest(id=11, buildsetid=99, buildername="Builder"),
                fakedb.Build(number=0, brid=11, results=SUCCESS),
            ]
        )
        mn.parent = self

        self.status = Mock()
        mn.master_status = Mock()
        mn.master_status.getBuilder = fakeGetBuilder
        mn.buildMessageDict = Mock()
        mn.buildMessageDict.return_value = {"body": "body", "type": "text", "subject": "subject"}

        mn.buildsetFinished(99, FAILURE)
        fakeBuildMessage.assert_called_with("Buildset Complete: testReason", [build], SUCCESS)
 def create_getjobs_response(cls):
     result = Mock()
     result.responseCode = ResponseCode.OK
     result.result = Mock()
     result.result.getJobsResult = Mock()
     mock_job_one = Mock()
     mock_job_one.key = Mock()
     mock_job_one.key.role = "RoleA"
     mock_job_one.key.environment = "test"
     mock_job_one.key.name = "hithere"
     mock_job_two = Mock()
     mock_job_two.key = Mock()
     mock_job_two.key.role = "bozo"
     mock_job_two.key.environment = "test"
     mock_job_two.key.name = "hello"
     result.result.getJobsResult.configs = [mock_job_one, mock_job_two]
     return result
    def test_render_result(self, mako_template):
        task = tasks.PythonTask()
        task.result_template = "result.mak"
        task.task_dir = Mock(return_value="/tmp/task")
        result = Mock(AsyncResult)
        result.successful.return_value = True
        result.result = {"query": "myquery"}
        from mako.template import Template

        tpl = Mock(Template)
        tpl.render.return_value = "mytemplate"
        mako_template.return_value = tpl
        files = ["result.csv"]

        html = task.render_result(result, files)

        self.assertEquals(html, "mytemplate")
        mako_template.assert_called_with(filename="/tmp/task/result.mak", output_encoding="utf-8")
        tpl.render.assert_called_with(query="myquery", files=files)
Example #22
0
    def test_get_user_stack_status_first_time(self):
        self.init_block()

        mock_result = Mock()
        mock_result.ready.return_value = True
        mock_result.successful.return_value = True
        mock_result.result = {"status": "CREATE_COMPLETE"}
        mock_launch_stack_task = Mock(return_value=mock_result)
        mock_suspend_user_stack = Mock()

        with patch.multiple(
            self.block, launch_stack_task=mock_launch_stack_task, suspend_user_stack=mock_suspend_user_stack
        ):
            data = {"initialize": True, "reset": False}
            result = self.call_handler("get_user_stack_status", data)

        self.assertEqual(result, mock_result.result)
        self.assertTrue(mock_launch_stack_task.called)
        self.assertTrue(mock_suspend_user_stack.called)
Example #23
0
 def test_update_progress_to_failure(self):
     # view task entry for task in progress that later fails
     instructor_task = self._create_progress_entry()
     task_id = instructor_task.task_id
     mock_result = Mock()
     mock_result.task_id = task_id
     mock_result.state = FAILURE
     mock_result.result = NotImplementedError("This task later failed.")
     mock_result.traceback = "random traceback"
     output = self._test_get_status_from_result(task_id, mock_result)
     self.assertEquals(output["message"], "This task later failed.")
     self.assertEquals(output["succeeded"], False)
     self.assertEquals(output["task_state"], FAILURE)
     self.assertFalse(output["in_progress"])
     expected_progress = {
         "exception": "NotImplementedError",
         "message": "This task later failed.",
         "traceback": "random traceback",
     }
     self.assertEquals(output["task_progress"], expected_progress)
Example #24
0
 def create_status_call_result(cls):
     """Set up the mock status call that will be used to get a task list for
 a batched kill command.
 """
     status_response = Mock(spec=Response)
     status_response.responseCode = ResponseCode.OK
     status_response.messageDEPRECATED = "Ok"
     status_response.result = Mock(spec=Result)
     schedule_status = Mock(spec=ScheduleStatusResult)
     status_response.result.scheduleStatusResult = schedule_status
     mock_task_config = Mock()
     # This should be a list of ScheduledTask's.
     schedule_status.tasks = []
     for i in range(20):
         task_status = Mock(spec=ScheduledTask)
         task_status.assignedTask = Mock(spec=AssignedTask)
         task_status.assignedTask.instanceId = i
         task_status.assignedTask.taskId = "Task%s" % i
         task_status.assignedTask.slaveId = "Slave%s" % i
         task_status.slaveHost = "Slave%s" % i
         task_status.assignedTask.task = mock_task_config
         schedule_status.tasks.append(task_status)
     return status_response
Example #25
0
    def test_success(self, UrlFetchClassMock):
        # Mocking pagseguro Fetch
        UrlFetchClassMock.return_value = _build_mock()

        # Mocking previous command
        data_cmd_mock = Mock()
        data_cmd_mock.access_data.email = "foo@bar.com"
        data_cmd_mock.access_data.token = "4567890oiuytfgh"
        reference0 = ItemReferenceMock()
        reference1 = ItemReferenceMock()
        items = [
            PagSegItem(description="Python Course", price=Decimal("120"), quantity=1, reference=reference0.key),
            PagSegItem(description="Another Python Course", price=Decimal("240"), quantity=2, reference=reference1.key),
        ]
        ndb.put_multi(items)
        data_cmd_mock.items = items
        data_cmd_mock.client_form = ValidateClientCmd(email="jhon@bar.com", name="Jhon Doe").form
        data_cmd_mock.address_form = pagseguro_facade.validate_address_cmd(
            "Rua 1", "2", "meu bairro", "12345678", "São Paulo", "SP", "apto 4"
        ).form

        payment = PagSegPayment()
        payment.put()
        data_cmd_mock.result = payment

        contact_pagseguro_cmd = ContactPagseguro("https://store.com/pagseguro")
        CommandSequential(data_cmd_mock, contact_pagseguro_cmd).execute()

        self.assertEqual(payment, contact_pagseguro_cmd.result)
        self.assertEqual(payment.status, STATUS_SENT_TO_PAGSEGURO)
        self.assertEqual(
            contact_pagseguro_cmd.checkout_code,
            _SUCCESS_PAGSEGURO_CODE,
            "Should have the code extracted from xml _PAGSEGURO_DETAIL_XML",
        )
        self.assertIsNone(payment.code)
Example #26
0
    def patch_targeting(
        self, celery_mock, px3_ready=True, px3_successful=True, px4_ready=True, px4_successful=True, px4_filtering=False
    ):
        if px3_ready:
            px3_failed = not px3_successful
        else:
            px3_successful = px3_failed = False

        if px4_ready:
            px4_failed = not px4_successful
        else:
            px4_successful = px4_failed = False

        error = ValueError("Ruh-Roh!")

        px3_result_mock = Mock(id="123", task_id="123")
        px3_result_mock.ready.return_value = px3_ready
        px3_result_mock.successful.return_value = px3_successful
        px3_result_mock.failed.return_value = px3_failed
        if px3_ready:
            px3_result_mock.result = (
                FilteringResult(
                    self.test_edges,
                    models.datastructs.TieredEdges(edges=self.test_edges, campaign_id=1, content_id=1),
                    self.test_filter.filter_id,
                    self.test_filter.url_slug,
                    1,
                    1,
                )
                if px3_successful
                else error
            )
        else:
            px3_result_mock.result = None

        px4_result_mock = Mock(id="1234", task_id="1234")
        px4_result_mock.ready.return_value = px4_ready
        px4_result_mock.successful.return_value = px4_successful
        px4_result_mock.failed.return_value = px4_failed
        if px4_ready:
            if px4_filtering:
                px4_result_mock.result = (
                    FilteringResult(
                        self.test_edges,
                        models.datastructs.TieredEdges(edges=self.test_edges, campaign_id=1, content_id=1),
                        self.test_filter.filter_id,
                        self.test_filter.url_slug,
                        1,
                        1,
                    )
                    if px4_successful
                    else error
                )
            else:
                px4_result_mock.result = (
                    empty_filtering_result._replace(ranked=self.test_edges) if px4_successful else error
                )
        else:
            px4_result_mock.result = None

        async_mock = Mock()
        async_mock.side_effect = [px3_result_mock, px4_result_mock]
        celery_mock.current_app.AsyncResult = async_mock
Example #27
0
 def create_blank_response(cls, code, msg):
     response = Mock(spec=Response)
     response.responseCode = code
     response.message = msg
     response.result = Mock(spec=Result)
     return response
Example #28
0
 def setup_fetch_mock(self):
     fetch_mock = Mock()
     fetch_mock.result = {"id": "123", "email": "foo@gmail.com", "name": "foo"}
     fetch_mock.errors = {}
     return fetch_mock