Exemple #1
0
 def test_batchassets_set_assets(self):
     self.mock_self.renderer = mock.Mock()
     self.mock_self._assets = mock.create_autospec(Assets)
     AzureBatchAssets.set_assets(self.mock_self)
     self.mock_self._configure_renderer.assert_called_with()
     self.mock_self._assets.gather.assert_called_with()
     self.mock_self._assets.extend.assert_called_with(mock.ANY)
Exemple #2
0
    def init_after_account_selected(self):
        try:
            if not hasattr(self, "submission"):
                self.submission = AzureBatchSubmission(
                    self.tab_index['SUBMIT'], self.frame, self.call)
            if not hasattr(self, "assets"):
                self.assets = AzureBatchAssets(self.tab_index['ASSETS'],
                                               self.frame, self.call)
            if not hasattr(self, "pools"):
                self.pools = AzureBatchPools(self.tab_index['POOLS'],
                                             self.frame, self.call)
            if not hasattr(self, "jobhistory"):
                self.jobhistory = AzureBatchJobHistory(
                    self.tab_index['JOBHISTORY'], self.frame, self.call)
            if not hasattr(self, "env"):
                self.env = AzureBatchEnvironment(self.tab_index['ENV'],
                                                 self.frame, self.call)

            self.config.auth = True
            self.start()
        except Exception as exp:
            if (maya.window("AzureBatch", q=1, exists=1)):
                maya.delete_ui("AzureBatch")
            message = "Batch Plugin Failed to Start: {0}".format(exp)
            maya.error(message)
            raise
Exemple #3
0
 def test_batchassets_add_files(self):
     self.mock_self.ui = mock.Mock()
     self.mock_self._assets = mock.create_autospec(Assets)
     AzureBatchAssets.add_files(self.mock_self, ["a", "b"], "layout",
                                "scroll")
     self.mock_self._assets.add_asset.assert_any_call(
         "a", self.mock_self.ui, "layout", "scroll")
     self.mock_self._assets.add_asset.assert_any_call(
         "b", self.mock_self.ui, "layout", "scroll")
Exemple #4
0
 def test_batchassets_add_dir(self):
     test_dir = os.path.join(os.path.dirname(__file__), "data")
     self.mock_self._assets = mock.create_autospec(Assets)
     self.mock_self.ui = mock.Mock()
     AzureBatchAssets.add_dir(self.mock_self, [test_dir], "layout",
                              "scroll")
     self.mock_self._assets.add_asset.assert_any_call(
         os.path.join(test_dir, "modules", "default.py"), self.mock_self.ui,
         "layout", "scroll")
     self.assertTrue(self.mock_self._assets.add_asset.call_count >= 4)
Exemple #5
0
    def test_batchassets_configure_renderer(self, mock_maya, mock_default):
        mock_default.return_value = mock.Mock(render_engine="default")
        mock_maya.get_attr.return_value = "test_renderer"

        renderer = mock.Mock(render_engine="my_renderer")
        self.mock_self.modules = [renderer, "test", None]

        AzureBatchAssets._configure_renderer(self.mock_self)
        self.assertEqual(self.mock_self.renderer, mock_default.return_value)

        renderer = mock.Mock(render_engine="test_renderer")
        self.mock_self.modules.append(renderer)

        AzureBatchAssets._configure_renderer(self.mock_self)
        self.assertEqual(self.mock_self.renderer, renderer)
Exemple #6
0
 def test_batchassets_set_searchpaths(self, mock_maya, mock_syspaths):
     mock_maya.file.return_value = "testscene.mb"
     mock_maya.workspace.return_value = "/test/directory"
     mock_syspaths = ["a", "b", "c"]
     paths = AzureBatchAssets._set_searchpaths(self.mock_self)
     self.assertEqual(
         sorted(paths),
         ["/test/directory", "/test/directory\\sourceimages",
          os.getcwd()])
Exemple #7
0
 def __init__(self):
     """Initialize all the tabs and attempt to authenticate using cached
     credentials if available.
     """
     self._log = logging.getLogger('AzureBatchMaya')
     try:
         self.frame = AzureBatchUI(self)
         self.config = AzureBatchConfig(self.tab_index['AUTH'], self.frame, self.start)
         self.submission = AzureBatchSubmission(self.tab_index['SUBMIT'], self.frame, self.call)
         self.assets = AzureBatchAssets(self.tab_index['ASSETS'], self.frame, self.call)
         self.pools = AzureBatchPools(self.tab_index['POOLS'], self.frame, self.call)
         self.jobhistory =  AzureBatchJobHistory(self.tab_index['JOBHISTORY'], self.frame, self.call)
         self.env =  AzureBatchEnvironment(self.tab_index['ENV'], self.frame, self.call)
         self.start()
     except Exception as exp:
         if (maya.window("AzureBatch", q=1, exists=1)):
             maya.delete_ui("AzureBatch")
         message = "Batch Plugin Failed to Start: {0}".format(exp)
         maya.error(message)
         raise
Exemple #8
0
    def test_batchassets_callback_refresh(self):
        self.mock_self.ui = mock.create_autospec(AssetsUI)
        self.mock_self.frame = mock.Mock()
        self.mock_self.frame.selected_tab = lambda: 1
        self.mock_self.ui.ready = False

        AzureBatchAssets._callback_refresh(self.mock_self)
        self.assertEqual(self.mock_self.ui.refresh.call_count, 0)
        self.assertFalse(self.mock_self.ui.ready)

        self.mock_self.ui.ready = True
        AzureBatchAssets._callback_refresh(self.mock_self)
        self.assertEqual(self.mock_self.ui.refresh.call_count, 0)
        self.assertFalse(self.mock_self.ui.ready)

        self.mock_self.frame.selected_tab = lambda: 3
        AzureBatchAssets._callback_refresh(self.mock_self)
        self.assertEqual(self.mock_self.ui.refresh.call_count, 1)
Exemple #9
0
class AzureBatchSettings(object):

    tab_index = {
        'AUTH': 1,
        'SUBMIT': 2,
        'ASSETS': 3,
        'POOLS': 4,
        'JOBHISTORY': 5,
        'ENV': 6
    }

    @staticmethod
    def starter():
        """Called by the mel script when the shelf button is clicked."""
        AzureBatchSettings()

    def __init__(self):
        """Initialize all the tabs and attempt to authenticate using cached
        credentials if available.
        """
        self._log = logging.getLogger('AzureBatchMaya')
        try:
            self.frame = AzureBatchUI(self)
            self.config = AzureBatchConfig(self.tab_index['AUTH'], self.frame, self.start)
            self.submission = AzureBatchSubmission(self.tab_index['SUBMIT'], self.frame, self.call)
            self.assets = AzureBatchAssets(self.tab_index['ASSETS'], self.frame, self.call)
            self.pools = AzureBatchPools(self.tab_index['POOLS'], self.frame, self.call)
            self.jobhistory =  AzureBatchJobHistory(self.tab_index['JOBHISTORY'], self.frame, self.call)
            self.env =  AzureBatchEnvironment(self.tab_index['ENV'], self.frame, self.call)
            self.start()
        except Exception as exp:
            if (maya.window("AzureBatch", q=1, exists=1)):
                maya.delete_ui("AzureBatch")
            message = "Batch Plugin Failed to Start: {0}".format(exp)
            maya.error(message)
            raise

    def start(self):
        """Start the plugin UI. Depending on whether auto-authentication was
        successful, the plugin will start by displaying the submission tab.
        Otherwise the UI will be disabled, and the login tab will be displayed.
        """
        try:
            self._log.debug("Starting AzureBatchShared...")
            if self.config.auth:
                self.frame.is_logged_in()
                self.env.configure(self.config)
                self.jobhistory.configure(self.config)
                self.assets.configure(self.config)
                self.pools.configure(self.config, self.env)
                self.submission.start(self.config, self.assets, self.pools, self.env)
            else:
                self.frame.is_logged_out()
        except Exception as exp:
            self._log.warning(exp)
            if (maya.window("AzureBatch", q=1, exists=1)):
                maya.delete_ui("AzureBatch")
            maya.error("Batch Plugin UI failed to load:\n{0}".format(exp))

    def call(self, command, *args, **kwargs):
        """Wrap all Batch and Storage API calls in order to handle errors.
        Some errors we anticipate and raise without a dialog (e.g. PoolNotFound).
        Others we raise and display to the user.
        """
        try:
            return command(*args, **kwargs)
        except BatchErrorException as exp:
            if exp.error.code in ACCEPTED_ERRORS:
                self._log.info("Call failed: {}".format(exp.error.code))
                raise
            else:
                message = exp.error.message.value
                if exp.error.values:
                    message += "Details:\n"
                    for detail in exp.error.values:
                        message += "{}: {}".format(detail.key, detail.value)
                raise ValueError(message)
        except Exception as exp:
            if (maya.window("AzureBatch", q=1, exists=1)):
                maya.delete_ui("AzureBatch")
            exc_type, exc_value, exc_traceback = sys.exc_info()
            self._log.error("".join(traceback.format_exception(exc_type, exc_value, exc_traceback)))
            raise ValueError("Error: {0}".format(exp))
Exemple #10
0
class AzureBatchSettings(object):

    tab_index = {
        'AUTH': 1,
        'SUBMIT': 2,
        'ASSETS': 3,
        'POOLS': 4,
        'JOBHISTORY': 5,
        'ENV': 6
    }

    @staticmethod
    def starter():
        """Called by the mel script when the shelf button is clicked."""
        AzureBatchSettings()

    def __init__(self):
        """Initialize all the tabs and attempt to authenticate using cached
        credentials if available.
        """
        self._log = logging.getLogger('AzureBatchMaya')
        try:
            self.frame = AzureBatchUI(self)
            self.config = AzureBatchConfig(self.tab_index['AUTH'], self,
                                           self.frame, self.start, self.call)

            if (self.config.can_init_from_config):
                self.init_after_account_selected()

        except Exception as exp:
            if (maya.window("AzureBatch", q=1, exists=1)):
                maya.delete_ui("AzureBatch")
            message = "Batch Plugin Failed to Start: {0}".format(exp)
            maya.error(message)
            raise

    def init_after_account_selected(self):
        try:
            if not hasattr(self, "submission"):
                self.submission = AzureBatchSubmission(
                    self.tab_index['SUBMIT'], self.frame, self.call)
            if not hasattr(self, "assets"):
                self.assets = AzureBatchAssets(self.tab_index['ASSETS'],
                                               self.frame, self.call)
            if not hasattr(self, "pools"):
                self.pools = AzureBatchPools(self.tab_index['POOLS'],
                                             self.frame, self.call)
            if not hasattr(self, "jobhistory"):
                self.jobhistory = AzureBatchJobHistory(
                    self.tab_index['JOBHISTORY'], self.frame, self.call)
            if not hasattr(self, "env"):
                self.env = AzureBatchEnvironment(self.tab_index['ENV'],
                                                 self.frame, self.call)

            self.config.auth = True
            self.start()
        except Exception as exp:
            if (maya.window("AzureBatch", q=1, exists=1)):
                maya.delete_ui("AzureBatch")
            message = "Batch Plugin Failed to Start: {0}".format(exp)
            maya.error(message)
            raise

    def start(self):
        """Start the plugin UI. Depending on whether auto-authentication was
        successful, the plugin will start by displaying the submission tab.
        Otherwise the UI will be disabled, and the login tab will be displayed.
        """
        try:
            self._log.debug("Starting AzureBatchShared...")
            if self.config.auth:
                self.frame.is_logged_in()
                self.env.configure(self.config, self.submission, self.assets)
                self.jobhistory.configure(self.config)
                self.assets.configure(self.config, self.submission, self.env)
                self.pools.configure(self.config, self.env)
                self.submission.start(self.config, self.assets, self.pools,
                                      self.env)
            else:
                self.frame.is_logged_out()
        except Exception as exp:
            self._log.warning(exp)
            if (maya.window("AzureBatch", q=1, exists=1)):
                maya.delete_ui("AzureBatch")
            maya.error("Batch Plugin UI failed to load:\n{0}".format(exp))

    def call(self, command, *args, **kwargs):
        """Wrap all Batch and Storage API calls in order to handle errors.
        Some errors we anticipate and raise without a dialog (e.g. PoolNotFound).
        Others we raise and display to the user.
        """
        try:
            result = command(*args, **kwargs)
            return self.ensure_iter_called(result)
        except BatchErrorException as exp:
            #if auth error (401) refresh tokens and recreate clients, before repeating the call
            if exp.response.status_code in [401]:
                self.config.refresh_auth_tokens(self.config.batch_auth_token,
                                                self.config.mgmt_auth_token)
                self.config.update_batch_and_storage_client_creds(
                    self.config.batch_auth_token, self.config.mgmt_auth_token)

                result = command(*args, **kwargs)
                try:
                    return self.ensure_iter_called(result)
                except BatchErrorException as exp:
                    self.handle_batch_exception(exp)
            else:
                self.handle_batch_exception(exp)

        except Exception as exp:
            if (maya.window("AzureBatch", q=1, exists=1)):
                maya.delete_ui("AzureBatch")
            exc_type, exc_value, exc_traceback = sys.exc_info()
            self._log.error("".join(
                traceback.format_exception(exc_type, exc_value,
                                           exc_traceback)))
            raise ValueError("Error: {0}".format(exp))

    def handle_batch_exception(self, exp):
        if exp.error.code in ACCEPTED_ERRORS:
            self._log.info("Call failed: {}".format(exp.error.code))
            raise
        else:
            message = exp.error.message.value
            if exp.error.values:
                message += "Details:\n"
                for detail in exp.error.values:
                    message += "{}: {}".format(detail.key, detail.value)
            raise ValueError(message)

    def ensure_iter_called(self, result):
        if isinstance(result, collections.Iterator):
            #peek at the first result to force the first call and make sure any auth errors are raised here
            try:
                peek = result.next()
                result.reset()
            except StopIteration:
                pass
        return result
Exemple #11
0
 def test_batchassets_upload(self, mock_maya, mock_prog, mock_asset):
     # TODO
     self.mock_self.ui = mock.create_autospec(AssetsUI)
     self.mock_self.ui.upload_button = mock.create_autospec(ProcButton)
     self.mock_self._assets = mock.create_autospec(Assets)
     AzureBatchAssets.upload(self.mock_self)
Exemple #12
0
 def test_batchassets_get_assets(self):
     self.mock_self._assets = mock.create_autospec(Assets)
     self.mock_self._assets.refs = ["file1", "file2"]
     assets = AzureBatchAssets.get_assets(self.mock_self)
     self.assertEqual(assets, ["file1", "file2"])
Exemple #13
0
 def test_batchassets_collect_modules(self):
     mods = AzureBatchAssets._collect_modules(self.mock_self)
     self.assertEqual(len(mods), 4)
Exemple #14
0
 def test_batchassets_configure(self, mock_assets):
     session = mock.Mock(batch="batch")
     AzureBatchAssets.configure(self.mock_self, session)
     mock_assets.assert_called_with("batch")
     self.assertEqual(self.mock_self._set_searchpaths.call_count, 1)
Exemple #15
0
 def test_batchassets_create(self, mock_ui, mock_call, mock_collect):
     assets = AzureBatchAssets(3, "frame", "call")
     mock_ui.assert_called_with(assets, "frame")
     mock_collect.assert_called_with()