Example #1
0
 def test_poll_requeues_loops(self):
     loop = MagicMock()
     loop.function = MagicMock()
     loop.requeue = True
     self.engine._callbacks.append(loop)
     self.engine.poll(0.02)
     self.assertTrue(loop in self.engine._callbacks)
Example #2
0
    def test_import(self, server_proxy, requests):
        """
        Test import operation
        """
        proxy = MagicMock()
        proxy.ImportInfrastructure.return_value = (True, "newinfid")
        server_proxy.return_value = proxy
        options = MagicMock()
        options.auth_file = get_abs_path("../../auth.dat")
        options.restapi = None
        parser = MagicMock()

        out = StringIO()
        oldstdout = sys.stdout
        sys.stdout = out
        res = main("import", options, [get_abs_path("../files/test.radl")], parser)
        self.assertEquals(res, True)
        output = out.getvalue().strip()
        self.assertIn("New Inf: newinfid", output)

        out = StringIO()
        sys.stdout = out
        options.xmlrpc = None
        options.restapi = "https://localhost:8800"
        requests.side_effect = self.get_response
        res = main("import", options, [get_abs_path("../files/test.radl")], parser)
        self.assertEquals(res, True)
        output = out.getvalue().strip()
        self.assertIn("New Inf: newinfid", output)
        sys.stdout = oldstdout
Example #3
0
    def test_save_grade_success(self):
        data = {
            'rubric_scores[]': [0, 0],
            'location': self.location,
            'submission_id': 1,
            'submission_key': 'fake key',
            'score': 2,
            'feedback': 'feedback',
            'submission_flagged': 'false',
            'answer_unknown': 'false',
            'rubric_scores_complete' : 'true'
        }

        qdict = MagicMock()

        def fake_get_item(key):
            return data[key]

        qdict.__getitem__.side_effect = fake_get_item
        qdict.getlist = fake_get_item
        qdict.keys = data.keys

        response = self.peer_module.save_grade(qdict)

        self.assertTrue(response['success'])
Example #4
0
    def test_getstate(self, server_proxy, requests):
        """
        Test getstate operation
        """
        proxy = MagicMock()
        proxy.GetInfrastructureState.return_value = (True, {"state": "running", "vm_states": {"vm1": "running"}})
        server_proxy.return_value = proxy
        options = MagicMock()
        options.auth_file = get_abs_path("../../auth.dat")
        options.restapi = None
        parser = MagicMock()

        out = StringIO()
        oldstdout = sys.stdout
        sys.stdout = out
        res = main("getstate", options, ["infid"], parser)
        self.assertEquals(res, True)
        output = out.getvalue().strip()
        self.assertIn("The infrastructure is in state: running\nVM ID: vm1 is in state: running.", output)

        out = StringIO()
        sys.stdout = out
        options.xmlrpc = None
        options.restapi = "https://localhost:8800"
        requests.side_effect = self.get_response
        res = main("getstate", options, ["infid"], parser)
        self.assertEquals(res, True)
        output = out.getvalue().strip()
        self.assertIn("The infrastructure is in state: running\nVM ID: vm1 is in state: running.", output)
        sys.stdout = oldstdout
Example #5
0
    def test_rebootvm(self, server_proxy, requests):
        """
        Test rebootvm operation
        """
        proxy = MagicMock()
        proxy.RebootVM.return_value = (True, "")
        server_proxy.return_value = proxy
        options = MagicMock()
        options.auth_file = get_abs_path("../../auth.dat")
        options.restapi = None
        parser = MagicMock()

        out = StringIO()
        oldstdout = sys.stdout
        sys.stdout = out
        res = main("rebootvm", options, ["infid", "vmid"], parser)
        self.assertEquals(res, True)
        output = out.getvalue().strip()
        self.assertIn("VM successfully rebooted", output)

        out = StringIO()
        sys.stdout = out
        options.xmlrpc = None
        options.restapi = "https://localhost:8800"
        requests.side_effect = self.get_response
        res = main("rebootvm", options, ["infid", "vmid"], parser)
        self.assertEquals(res, True)
        output = out.getvalue().strip()
        self.assertIn("VM successfully rebooted", output)
        sys.stdout = oldstdout
Example #6
0
    def test_comit_no_parents(self):
        mocked_repo = MagicMock()
        mocked_parent = MagicMock()

        mocked_parent.id = 1

        mocked_repo.status.return_value = True
        mocked_repo.index.write_tree.return_value = "tree"
        mocked_repo.revparse_single.return_value = mocked_parent
        mocked_repo.create_commit.return_value = "commit"

        author = ("author_1", "author_2")
        commiter = ("commiter_1", "commiter_2")

        with patch('gitfs.repository.Signature') as mocked_signature:
            mocked_signature.return_value = "signature"

            repo = Repository(mocked_repo)
            commit = repo.commit("message", author, commiter)

            assert commit == "commit"
            assert mocked_repo.status.call_count == 1
            assert mocked_repo.index.write_tree.call_count == 1
            assert mocked_repo.index.write.call_count == 1

            mocked_signature.has_calls([call(*author), call(*commiter)])
            mocked_repo.revparse_single.assert_called_once_with("HEAD")
            mocked_repo.create_commit.assert_called_once_with("HEAD",
                                                              "signature",
                                                              "signature",
                                                              "message",
                                                              "tree", [1])
Example #7
0
    def test_addresource(self, server_proxy, requests):
        """
        Test addresource operation
        """
        proxy = MagicMock()
        proxy.AddResource.return_value = (True, ["1"])
        server_proxy.return_value = proxy
        options = MagicMock()
        options.auth_file = get_abs_path("../../auth.dat")
        options.restapi = None
        parser = MagicMock()

        out = StringIO()
        oldstdout = sys.stdout
        sys.stdout = out
        res = main("addresource", options, ["infid", get_abs_path("../files/test.radl")], parser)
        self.assertEquals(res, True)
        output = out.getvalue().strip()
        self.assertIn("Resources with IDs: 1 successfully added.", output)

        out = StringIO()
        sys.stdout = out
        options.xmlrpc = None
        options.restapi = "https://localhost:8800"
        requests.side_effect = self.get_response
        res = main("addresource", options, ["infid", get_abs_path("../files/test.radl")], parser)
        self.assertEquals(res, True)
        output = out.getvalue().strip()
        self.assertIn("Resources with IDs: 1 successfully added.", output)
        sys.stdout = oldstdout
Example #8
0
def test_valid_enable_ipmi(login_mock, query_dn_mock, set_mo_mock):
    # Patch ImcHandle.login to create a Faux ImcHandle object w/o real CIMC
    # Patch ImcHandle.set_mo to simulate CIMC interaction w/o real CIMC
    login_mock.return_value = True
    set_mo_mock.return_value = True
    ipmi_enabled_mock = MagicMock()
    ipmi_enabled_mock.admin_state = "enabled"
    test_cimc = ImcHandle(ip='169.254.1.1',
                          username='admin',
                          password='right')

    test_cimc._set_platform(platform=IMC_PLATFORM.TYPE_CLASSIC)
    query_dn_mock.return_value = ipmi_enabled_mock

    # Scenario: Enable IPMI default values
    assert ipmi_enable(test_cimc) is ipmi_enabled_mock
    # Assert values of the object passed to add_mo()
    test_ipmi_mo = set_mo_mock.call_args[0][0]
    assert test_ipmi_mo.admin_state == "enabled"
    assert test_ipmi_mo.priv == CommIpmiLanConsts.PRIV_ADMIN
    assert test_ipmi_mo.key == '0'*40

    # Scenario: Enable IPMI custom priv and key
    assert ipmi_enable(test_cimc, priv="user", key='1'*40) is ipmi_enabled_mock
    test_ipmi_mo = set_mo_mock.call_args[0][0]
    assert test_ipmi_mo.admin_state == "enabled"
    assert test_ipmi_mo.priv == "user"
    assert test_ipmi_mo.key == '1'*40
 def test_create_aggregate_projections(self):
     connection = MagicMock()
     self.create_task(cls=CopyToVerticaDummyTableWithProjections).create_aggregate_projections(connection)
     self.assertEquals([
         call('CREATE PROJECTION IF NOT EXISTS foobar.dummy_table_projection_2 DEFINITION_2 on foobar.dummy_table;'),
         call('SELECT start_refresh();'),
     ], connection.cursor().execute.mock_calls)
Example #10
0
def test_search_q():
    user = MagicMock(spec=auth_models.User)
    user.is_staff = True
    queryset = MagicMock(spec=QuerySet)

    expected_result = MagicMock(spec=QuerySet)
    (queryset
        .select_related.return_value
        .prefetch_related.return_value
        .filter.return_value) = expected_result

    params = {'q': ['meow']}
    result = models.place.objects.get_search_queryset(user, queryset, params)

    q = (
        MyQ(title__icontains='meow')
        | MyQ(address__icontains='meow')
        | MyQ(address2__icontains='meow')
        | MyQ(city__icontains='meow')
        | MyQ(state__icontains='meow')
        | MyQ(country__icontains='meow')
    )
    chained = (
       call
       .select_related('cover_photo')
       .prefetch_related('cover_photo__photo_file_set')
       .filter(q)
    )
    assert queryset.mock_calls == chained.call_list()
    assert result is expected_result
Example #11
0
 def test_notification_rate_limit2(self, mock_retry, mock_summ, mock_delay,
                                   verify_signature_mock, debug_mock):
     """ Test that the notification task rate limit errors ok """
     # Check that we fail gracefully when we hit the rate limit
     mock_delay.side_effect = lambda arg: process_notification(arg)
     resp = MagicMock()
     resp.headers = {'x-ratelimit-reset': 1404298869}
     exc = misfit_exceptions.MisfitRateLimitError(429, '', resp)
     mock_summ.side_effect = exc
     mock_retry.side_effect = Exception
     with HTTMock(JsonMock().goal_http,
                  JsonMock().profile_http,
                  JsonMock('summary_detail').summary_http):
         try:
             content = json.dumps(self.notification_content).encode('utf8')
             self.client.post(reverse('misfit-notification'), data=content,
                              content_type='application/json')
             assert False, 'We should have raised an exception'
         except Exception:
             assert True
     mock_delay.assert_called_once_with(content)
     mock_summ.assert_called_once_with(
         detail=True,
         end_date=datetime.date(2014, 10, 8),
         start_date=datetime.date(2014, 10, 5))
     mock_retry.assert_called_once_with(countdown=549)
     eq_(Goal.objects.filter(user=self.user).count(), 2)
     eq_(Profile.objects.filter(user=self.user).count(), 1)
     eq_(Summary.objects.filter(user=self.user).count(), 0)
Example #12
0
 def test_poll_processes_events(self):
     channel = MagicMock()
     channel._handle_events = MagicMock()
     self.engine._channels = {1: channel}
     self.engine._poller.poll = MagicMock(return_value={1:Engine.ALL_EVENTS})
     self.engine.poll(0.02)
     channel._handle_events.assert_called_once_with(Engine.ALL_EVENTS)
Example #13
0
 def test_systemexit_during_deferred_processing_is_raised(self):
     defer = MagicMock()
     defer.function = MagicMock(side_effect=SystemExit)
     defer.requeue = False
     defer.end = self.engine.latest_poll_time - 1
     self.engine._deferreds.append(defer)
     self.assertRaises(SystemExit, self.engine.poll, 0.02)
Example #14
0
 def test_keyboardinterrupt_during_deferred_processing_is_raised(self):
     defer = MagicMock()
     defer.function = MagicMock(side_effect=KeyboardInterrupt)
     defer.requeue = False
     defer.end = self.engine.latest_poll_time - 1
     self.engine._deferreds.append(defer)
     self.assertRaises(KeyboardInterrupt, self.engine.poll, 0.02)
Example #15
0
    def test_getattr_with_correct_path(self):
        mocked_repo = MagicMock()
        mocked_first = MagicMock()
        mocked_last = MagicMock()

        mocked_first.return_value = "tomorrow"
        mocked_last.return_value = "tomorrow"
        mocked_repo.get_commit_dates.return_value = ['/']
        with patch('gitfs.views.history.lru_cache') as mocked_cache:
            mocked_cache.__call__ = lambda f: f

            history = HistoryView(repo=mocked_repo, uid=1, gid=1,
                                  mount_time="now")
            history._get_first_commit_time = mocked_first
            history._get_last_commit_time = mocked_last

            result = history.getattr("/", 1)
            asserted_result = {
                'st_uid': 1,
                'st_gid': 1,
                'st_ctime': "tomorrow",
                'st_mtime': "tomorrow",
                'st_nlink': 2,
                'st_mode': S_IFDIR | 0o555,
            }
            assert asserted_result == result
Example #16
0
    def test_rename(self):
        mocked_re = MagicMock()
        mocked_index = MagicMock()
        mocked_os = MagicMock()
        mocked_result = MagicMock()

        mocked_result.rename.return_value = True
        mocked_re.sub.return_value = "new"
        mocked_os.path.split.return_value = [1, 1]

        with patch.multiple('gitfs.views.current', re=mocked_re,
                            os=mocked_os):
            from gitfs.views import current as current_view
            old_rename = current_view.PassthroughView.rename
            current_view.PassthroughView.rename = lambda self, old, new: True

            current = CurrentView(regex="regex", repo="repo",
                                  repo_path="repo_path",
                                  ignore=CachedIgnore())
            current._stage = mocked_index

            result = current.rename("old", "new")
            assert result is True
            mocked_index.assert_called_once_with(**{
                'remove': 1,
                'add': "new",
                "message": "Rename old to new"
            })
            mocked_os.path.split.assert_called_once_with("old")
            current_view.PassthroughView.rename = old_rename
 def get_group_with_posting_members(members):
     'A helper function to generate groups to test'
     retval = MagicMock()
     # --=mpj17=-- I am not proud of this next line
     gp = retval.site_root().ListManager.get_list().getProperty
     gp.return_value = members
     return retval
    def test_reap_tmp_images(self, _os_datastore_path, _uuid):
        """ Test that stray images are found and deleted by the reaper """

        def _fake_ds_folder(datastore, folder):
            return "%s__%s" % (datastore, folder)

        ds = MagicMock()
        ds.id = "dsid"
        ds.type = DatastoreType.EXT3

        # In a random transient directory, set up a directory to act as the
        # tmp images folder and to contain a stray image folder with a file.
        tmpdir = file_util.mkdtemp(delete=True)
        tmp_images_folder = _fake_ds_folder(ds.id, TMP_IMAGE_FOLDER_NAME)
        tmp_images_dir = os.path.join(tmpdir, tmp_images_folder)
        tmp_image_dir = os.path.join(tmp_images_dir, "stray_image")
        os.mkdir(tmp_images_dir)
        os.mkdir(tmp_image_dir)
        (fd, path) = tempfile.mkstemp(prefix='strayimage_', dir=tmp_image_dir)

        self.assertTrue(os.path.exists(path))

        def _fake_os_datastore_path(datastore, folder):
            return os.path.join(tmpdir, _fake_ds_folder(datastore, folder))

        _os_datastore_path.side_effect = _fake_os_datastore_path

        ds_manager = MagicMock()
        ds_manager.get_datastores.return_value = [ds]
        image_manager = EsxImageManager(self.vim_client, ds_manager)
        image_manager.reap_tmp_images()

        # verify stray image is deleted
        self.assertFalse(os.path.exists(path))
Example #19
0
    def test_create(self, server_proxy, requests):
        """
        Test create operation
        """
        proxy = MagicMock()
        proxy.CreateInfrastructure.return_value = (True, "inf1")
        server_proxy.return_value = proxy
        options = MagicMock()
        options.auth_file = get_abs_path("../../auth.dat")
        options.restapi = None
        parser = MagicMock()

        out = StringIO()
        oldstdout = sys.stdout
        sys.stdout = out
        res = main("create", options, [get_abs_path("../files/test.radl")], parser)
        self.assertEquals(res, True)
        output = out.getvalue().strip()
        self.assertIn("Infrastructure successfully created with ID: inf1", output)
        sys.stdout = oldstdout

        out = StringIO()
        sys.stdout = out
        options.xmlrpc = None
        options.restapi = "https://localhost:8800"
        requests.side_effect = self.get_response
        res = main("create", options, [get_abs_path("../files/test.radl")], parser)
        self.assertEquals(res, True)
        output = out.getvalue().strip()
        self.assertIn("Infrastructure successfully created with ID: inf1", output)
        sys.stdout = oldstdout
Example #20
0
 def test_redirect_to_course_position(self):
     mock_module = MagicMock()
     mock_module.descriptor.id = 'Underwater Basketweaving'
     mock_module.position = 3
     mock_module.get_display_items.return_value = []
     self.assertRaises(Http404, views.redirect_to_course_position,
                       mock_module, views.CONTENT_DEPTH)
Example #21
0
    def test_getcontmsg(self, server_proxy, requests):
        """
        Test getcontmsg operation
        """
        proxy = MagicMock()
        proxy.GetInfrastructureContMsg.return_value = (True, "contmsg")
        server_proxy.return_value = proxy
        options = MagicMock()
        options.auth_file = get_abs_path("../../auth.dat")
        options.restapi = None
        parser = MagicMock()

        out = StringIO()
        oldstdout = sys.stdout
        sys.stdout = out
        res = main("getcontmsg", options, ["infid"], parser)
        self.assertEquals(res, True)
        output = out.getvalue().strip()
        self.assertIn("Msg Contextualizator: \n\ncontmsg", output)

        out = StringIO()
        sys.stdout = out
        options.xmlrpc = None
        options.restapi = "https://localhost:8800"
        requests.side_effect = self.get_response
        res = main("getcontmsg", options, ["infid"], parser)
        self.assertEquals(res, True)
        output = out.getvalue().strip()
        self.assertIn("Msg Contextualizator: \n\ncontmsg", output)
        sys.stdout = oldstdout
Example #22
0
    def test_get_view(self):
        mocked_index = MagicMock()
        mocked_current = MagicMock()
        mocked_view = MagicMock(return_value=mocked_current)

        router, mocks = self.get_new_router()

        router.register([
            ("/history", mocked_view),
            ("/current", mocked_view),
            ("/", MagicMock(return_value=mocked_index)),
        ])
        with patch('gitfs.router.lru_cache') as mocked_cache:
            mocked_cache.get_if_exists.return_value = None

            view, path = router.get_view("/current")
            assert view == mocked_current
            assert path == "/"
            asserted_call = {
                'repo': mocks['repo'],
                'ignore': mocks['repo'].ignore,
                'repo_path': mocks['repo_path'],
                'mount_path': mocks['mount_path'],
                'regex': "/current",
                'relative_path': "/",
                'uid': 1,
                'gid': 1,
                'branch': mocks['branch'],
                'mount_time': 0,
                'queue': mocks['queue'],
                'max_size': mocks['max_size'],
                'max_offset': mocks['max_offset'],
            }
            mocked_view.assert_called_once_with(**asserted_call)
            mocked_cache.get_if_exists.assert_called_once_with("/current")
Example #23
0
    def test_getinfo(self, server_proxy, requests):
        """
        Test getinfo operation
        """
        proxy = MagicMock()
        proxy.GetVMInfo.return_value = (True, "radltest")
        proxy.GetInfrastructureInfo.return_value = (True, ["vm1"])
        server_proxy.return_value = proxy
        options = MagicMock()
        options.auth_file = get_abs_path("../../auth.dat")
        options.restapi = None
        parser = MagicMock()

        out = StringIO()
        oldstdout = sys.stdout
        sys.stdout = out
        res = main("getinfo", options, ["infid"], parser)
        self.assertEquals(res, True)
        output = out.getvalue().strip()
        self.assertIn("Info about VM with ID: vm1\nradltest", output)

        out = StringIO()
        sys.stdout = out
        options.xmlrpc = None
        options.restapi = "https://localhost:8800"
        requests.side_effect = self.get_response
        res = main("getinfo", options, ["infid"], parser)
        self.assertEquals(res, True)
        output = out.getvalue().strip()
        self.assertIn("Info about VM with ID: vm1\nradltest", output)
        sys.stdout = oldstdout
Example #24
0
    def test_remove_response(self, c, review_id, side_effect=None, err_type=None, err_msg=None):
        # Create mocks
        review_manager.Review = MagicMock()
        rev_object = MagicMock()
        self.offering.owner_organization = self.org
        self.org.managers = [self.user.pk]
        rev_object.offering = self.offering
        review_manager.Review.objects.get.return_value = rev_object

        # Call the side effect if needed
        if side_effect:
            side_effect(self)

        error = None
        try:
            rm = review_manager.ReviewManager()
            rm.remove_response(self.user, review_id)
        except Exception as e:
            error = e

        if not err_type:
            self.assertEquals(error, None)
            # Check calls
            rev_object.response.delete.assert_called_with()
        else:
            self.assertTrue(isinstance(error, err_type))
            self.assertEquals(unicode(error), err_msg)
Example #25
0
    def test_getversion(self, server_proxy, requests):
        """
        Test getversion operation
        """
        proxy = MagicMock()
        proxy.GetVersion.return_value = (True, "1.0")
        server_proxy.return_value = proxy
        options = MagicMock()
        options.auth_file = get_abs_path("../../auth.dat")
        options.restapi = None
        parser = MagicMock()

        out = StringIO()
        oldstdout = sys.stdout
        sys.stdout = out
        res = main("getversion", options, [], parser)
        self.assertEquals(res, True)
        output = out.getvalue().strip()
        self.assertIn("1.0", output)

        out = StringIO()
        sys.stdout = out
        options.xmlrpc = None
        options.restapi = "https://localhost:8800"
        requests.side_effect = self.get_response
        res = main("getversion", options, [], parser)
        self.assertEquals(res, True)
        output = out.getvalue().strip()
        self.assertIn("1.0", output)
        sys.stdout = oldstdout
Example #26
0
 def test_disabled(self, mock_django_timezone: mock.MagicMock,
                   mock_queue_digest_recipient: mock.MagicMock) -> None:
     cutoff = timezone_now()
     # A Tuesday
     mock_django_timezone.return_value = datetime.datetime(year=2016, month=1, day=5)
     enqueue_emails(cutoff)
     mock_queue_digest_recipient.assert_not_called()
Example #27
0
    def test_sshvm_key(self, server_proxy):
        """
        Test sshvm operation
        """
        proxy = MagicMock()

        radl = open(get_abs_path("../files/test_priv.radl"), 'r').read()
        proxy.GetVMInfo.return_value = (True, radl)
        server_proxy.return_value = proxy
        options = MagicMock()
        options.auth_file = get_abs_path("../../auth.dat")
        options.restapi = None
        parser = MagicMock()

        out = StringIO()
        oldstdout = sys.stdout
        oldstderr = sys.stderr
        sys.stdout = out
        sys.stderr = out
        res = main("sshvm", options, ["infid", "vmid", "1"], parser)
        self.assertEquals(res, True)
        output = out.getvalue().strip()
        self.assertIn("ssh -p 1022 -i /tmp/", output)
        self.assertIn(" -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no ubuntu@10.0.0.1", output)
        sys.stdout = oldstdout
        sys.stderr = oldstderr
 def test_on_taskrun_submit_event(self, mock_update_feed,
                                  mock_add_user,
                                  mock_is_task,
                                  mock_update_task,
                                  mock_create_result,
                                  mock_push):
     """Test on_taskrun_submit is called."""
     conn = MagicMock()
     target = MagicMock()
     target.id = 1
     target.project_id = 1
     target.task_id = 2
     target.user_id = 3
     tmp = Project(id=1, name='name', short_name='short_name',
                   info=dict(container=1, thumbnail="avatar.png"),
                   published=True,
                   webhook='http://localhost.com')
     conn.execute.return_value = [tmp]
     on_taskrun_submit(None, conn, target)
     obj = tmp.to_public_json()
     obj['action_updated'] = 'TaskCompleted'
     mock_add_user.assert_called_with(conn, target.user_id, obj)
     mock_update_task.assert_called_with(conn, target.task_id)
     mock_update_feed.assert_called_once_with(obj)
     obj_with_webhook = tmp.to_public_json()
     obj_with_webhook['webhook'] = tmp.webhook
     obj_with_webhook['action_updated'] = 'TaskCompleted'
     mock_push.assert_called_with(obj_with_webhook, target.task_id, 1)
    def test_wait_for_providers_task(self, mock_export_run):
        mock_run_uid = str(uuid.uuid4())

        mock_provider_task = Mock(status=TaskStates.SUCCESS.value)
        mock_export_run.objects.filter().first.return_value = Mock()
        mock_export_run.objects.filter().first().provider_tasks.filter.return_value = [mock_provider_task]

        callback_task = MagicMock()
        apply_args = {"arg1": "example_value"}

        wait_for_providers_task(run_uid=mock_run_uid, callback_task=callback_task, apply_args=apply_args)
        callback_task.apply_async.assert_called_once_with(**apply_args)

        callback_task.reset_mock()

        mock_provider_task = Mock(status=TaskStates.RUNNING.value)
        mock_export_run.objects.filter().first.return_value = Mock()
        mock_export_run.objects.filter().first().provider_tasks.filter.return_value = [mock_provider_task]

        wait_for_providers_task(run_uid=mock_run_uid, callback_task=callback_task, apply_args=apply_args)
        callback_task.apply_async.assert_not_called()

        with self.assertRaises(Exception):
            mock_export_run.reset_mock()
            mock_export_run.objects.filter().first().__nonzero__.return_value = False
            wait_for_providers_task(run_uid=mock_run_uid, callback_task=callback_task, apply_args=apply_args)
    def test_copy_metadata_main_missing_directory(self, m_logger, m_exit,
            m_exists, m_isdir, m_process_all_files, m_argparser):
        """
        Test main() function. Mock CustomArgumentParser to return values
        desired for test but with missing `src_directory`. Verify correct
        behavior by asserting calls on logger, usage_message, and exit.
        """
        m_exists.return_value = True
        m_isdir.return_value = True

        # Mock up the proper return values.
        m_parse_args = MagicMock(
            src_directory=None,
            dst_directory="/def",
            simon_sez=True,
            verbose=False,
        )

        attrs = {
            'parse_args.return_value': m_parse_args,
            'usage_message.return_value': None,
        }

        # This one configured to return m_parse_args.
        m_parse_args_container = MagicMock()
        m_parse_args_container.configure_mock(**attrs)
        m_argparser.return_value = m_parse_args_container

        # Invoke the unit.
        retval = main()

        # Confirm expected behavior
        m_logger.error.assert_called()
        m_parse_args_container.usage_message.assert_called_once()
        m_exit.assert_called_once_with(1)