Esempio n. 1
0
    def test_create_for_failure(self):
        """
        Test create for failure!
        """
        source = mox.MockObject(core_model.Resource)
        source.attributes = {'occi.core.id': 'bar'}
        target = mox.MockObject(core_model.Resource)
        target.identifier = '/network/admin'

        link = core_model.Link('foo', None, [], source, target)

        self.mox.ReplayAll()

        self.assertRaises(AttributeError, self.backend.create, link,
                          self.sec_obj)

        self.mox.VerifyAll()

        # should have pool name in attribute...
        target.identifier = '/network/public'
        link = core_model.Link('foo', None, [os_addon.OS_NET_LINK], source,
                               target)

        self.mox.ReplayAll()
        self.assertRaises(AttributeError, self.backend.create, link,
                          self.sec_obj)

        self.mox.VerifyAll()
    def test_delete_for_sanity(self):
        """
        Test deattachement.
        """
        source = mox.MockObject(core_model.Resource)
        source.attributes = {'occi.core.id': 'foo'}
        target = mox.MockObject(core_model.Resource)
        target.attributes = {'occi.core.id': 'bar'}

        link = core_model.Link('foo', None, [], source, target)

        self.mox.StubOutWithMock(nova_glue.storage, 'get_storage')
        nova_glue.storage.get_storage(mox.IsA(object),
                                      mox.IsA(object)).\
            AndReturn({'status': 'available', 'size': '1'})

        self.mox.StubOutWithMock(nova_glue.vm, 'detach_volume')
        nova_glue.vm.detach_volume(mox.IsA(object), mox.IsA(object),
                                   mox.IsA(object))

        self.mox.ReplayAll()

        self.backend.delete(link, self.sec_obj)

        self.mox.VerifyAll()
    def testSettings(self):
        ac = launcher.AppController(self.app)
        failures = [0]

        def failure_accum(a, b):
            failures[0] += 1

        ac._FailureMessage = failure_accum
        # First make sure we choke if !=1 project is selected
        for projectlist in ((), (1, 2, 4)):
            failures = [0]
            frame_mock = mox.MockObject(launcher.MainFrame)
            frame_mock.SelectedProjects().AndReturn(projectlist)
            mox.Replay(frame_mock)
            ac.SetModelsViews(frame=frame_mock)
            ac.Settings(self, None)
            mox.Verify(frame_mock)
            self.assertEqual(1, failures[0])
        # Now test things look fine with 1 project.
        frame_mock = mox.MockObject(launcher.MainFrame)
        frame_mock.SelectedProjects().AndReturn((1, ))
        frame_mock.RefreshView(None)
        mox.Replay(frame_mock)
        table_mock = mox.MockObject(launcher.MainTable)
        table_mock.SaveProjects()
        table_mock._projects = None
        mox.Replay(table_mock)
        ac.SetModelsViews(frame=frame_mock, table=table_mock)
        controller_mock = mox.MockObject(launcher.SettingsController)
        controller_mock.ShowModal().AndReturn(wx.ID_OK)
        mox.Replay(controller_mock)
        ac.Settings(None, settings_controller=controller_mock)
        mox.Verify(frame_mock)
        mox.Verify(table_mock)
        mox.Verify(controller_mock)
 def testRemove(self):
     """Test Remove with both single and multiple projects."""
     # Simulate with both positive and negative responses.
     # These functions will replace  launcher.Controller_ConfirmRemove().
     confirm_functions = (lambda a, b: True, lambda a, b: False)
     for confirm_function in confirm_functions:
         plists = (self.Projects(1), self.Projects(4))
         for projectlist in plists:
             frame_mock = mox.MockObject(launcher.MainFrame)
             frame_mock.SelectedProjects().AndReturn(projectlist)
             table_mock = mox.MockObject(launcher.MainTable)
             table_mock._projects = None
             # Only if _ConfirmRemove() will return True do we tell our
             # mock to expect deletes to happen (RemoveProject() calls).
             if confirm_function(0, 0):
                 for p in projectlist:
                     table_mock.RemoveProject(p).InAnyOrder()
                 frame_mock.UnselectAll()
                 frame_mock.RefreshView(None)
             mox.Replay(frame_mock)
             mox.Replay(table_mock)
             controller = launcher.AppController(self.app)
             controller._ConfirmRemove = confirm_function
             controller.SetModelsViews(frame=frame_mock, table=table_mock)
             controller.Remove(None)
             mox.Verify(frame_mock)
 def setUp(self):
   self._http_signaler = mox.MockObject(HttpSignaler)
   self._status_health_check = StatusHealthCheck()
   self._http_health_check = HttpHealthCheck(self._http_signaler)
   self._smart_health_check = InstanceWatcherHealthCheck(self._http_signaler)
   self._health_check_a = mox.MockObject(HealthCheck)
   self._health_check_b = mox.MockObject(HealthCheck)
    def test_create_for_sanity(self):
        """
        Test attachement.
        """
        source = mox.MockObject(core_model.Resource)
        source.attributes = {'occi.core.id': 'foo'}
        target = mox.MockObject(core_model.Resource)
        target.attributes = {'occi.core.id': 'bar'}

        link = core_model.Link('foo', None, [], source, target)
        link.attributes = {'occi.storagelink.deviceid': '/dev/sda'}

        self.mox.StubOutWithMock(nova_glue.vm, 'attach_volume')
        nova_glue.vm.attach_volume(mox.IsA(object), mox.IsA(object),
                                   mox.IsA(object), mox.IsA(object)).\
            AndReturn({})

        self.mox.ReplayAll()

        self.backend.create(link, self.sec_obj)

        # verify all attrs.
        self.assertEqual(link.attributes['occi.storagelink.deviceid'],
                         '/dev/sda')
        self.assertIn('occi.storagelink.mountpoint', link.attributes)
        self.assertEqual(link.attributes['occi.storagelink.state'], 'active')

        self.mox.VerifyAll()
Esempio n. 7
0
    def setUp(self):
        self.commandPrepend = os.path.join(getWMBASE(),'src','python','WMCore','Storage','Plugins','DCCPFNAL','wrapenv.sh')
        self.runMocker  = mox.MockObject(RunCommandThing)
        self.copyMocker = mox.MockObject(ourFallbackPlugin)
        def runCommandStub(command):
            (num1, num2) =  self.runMocker.runCommand(command)
            return (num1, num2)
        def getImplStub(command, useNewVersion = None):
            return self.copyMocker

        pass
Esempio n. 8
0
 def setUp(self):
     self._clock = FakeClock()
     self._event = FakeEvent(self._clock)
     self._scheduler = mox.MockObject(SchedulerProxyApiSpec)
     self._job_key = JobKey(role='mesos', name='jimbob', environment='test')
     self._health_check = mox.MockObject(HealthCheck)
     self._watcher = InstanceWatcher(self._scheduler,
                                     self._job_key,
                                     self.WATCH_SECS,
                                     health_check_interval_seconds=3,
                                     clock=self._clock,
                                     terminating_event=self._event)
 def testDeploy(self):
     projects = self.Projects(5)
     tc = launcher.TaskController(FakeAppController())
     frame_mock = mox.MockObject(launcher.MainFrame)
     frame_mock.SelectedProjects().MultipleTimes().AndReturn(projects)
     mox.Replay(frame_mock)
     deploy_controller = mox.MockObject(launcher.DeployController)
     deploy_controller.InitiateDeployment()
     mox.Replay(deploy_controller)
     tc.SetModelsViews(frame=frame_mock)
     tc.Deploy(None, deploy_controller)
     mox.Verify(deploy_controller)
     mox.Verify(frame_mock)
 def setUp(self):
   self._role = 'mesos'
   self._env = 'test'
   self._name = 'jimbob'
   self._clock = FakeClock()
   self._scheduler = mox.MockObject(scheduler_client)
   job_key = JobKey(name=self._name, environment=self._env, role=self._role)
   self._health_check = mox.MockObject(HealthCheck)
   self._watcher = InstanceWatcher(self._scheduler,
                                job_key,
                                self.RESTART_THRESHOLD,
                                self.WATCH_SECS,
                                health_check_interval_seconds=3,
                                clock=self._clock)
 def setUp(self):
     super(TestNexentaISCSIDriver, self).setUp()
     self.configuration = mox_lib.MockObject(conf.Configuration)
     self.configuration.nexenta_host = '1.1.1.1'
     self.configuration.nexenta_user = '******'
     self.configuration.nexenta_password = '******'
     self.configuration.nexenta_volume = 'cinder'
     self.configuration.nexenta_rest_port = 2000
     self.configuration.nexenta_rest_protocol = 'http'
     self.configuration.nexenta_iscsi_target_portal_port = 3260
     self.configuration.nexenta_target_prefix = 'iqn:'
     self.configuration.nexenta_target_group_prefix = 'cinder/'
     self.configuration.nexenta_blocksize = '8K'
     self.configuration.nexenta_sparse = True
     self.configuration.nexenta_rrmgr_compression = 1
     self.configuration.nexenta_rrmgr_tcp_buf_size = 1024
     self.configuration.nexenta_rrmgr_connections = 2
     self.nms_mock = self.mox.CreateMockAnything()
     for mod in ['volume', 'zvol', 'iscsitarget', 'appliance',
                 'stmf', 'scsidisk', 'snapshot']:
         setattr(self.nms_mock, mod, self.mox.CreateMockAnything())
     self.stubs.Set(jsonrpc, 'NexentaJSONProxy',
                    lambda *_, **__: self.nms_mock)
     self.drv = iscsi.NexentaISCSIDriver(configuration=self.configuration)
     self.drv.do_setup({})
    def setUp(self):
        super(HpSanISCSITestCase, self).setUp()
        self.stubs.Set(HpSanISCSIDriver, "_cliq_run", self._fake_cliq_run)
        self.stubs.Set(HpSanISCSIDriver, "_get_iscsi_properties",
                       self._fake_get_iscsi_properties)
        configuration = mox.MockObject(conf.Configuration)
        configuration.san_is_local = False
        configuration.san_ip = "10.0.0.1"
        configuration.san_login = "******"
        configuration.san_password = "******"
        configuration.san_ssh_port = 16022
        configuration.san_clustername = "CloudCluster1"
        configuration.san_thin_provision = True
        configuration.append_config_values(mox.IgnoreArg())

        self.driver = HpSanISCSIDriver(configuration=configuration)
        self.volume_name = "fakevolume"
        self.snapshot_name = "fakeshapshot"
        self.connector = {
            'ip': '10.0.0.2',
            'initiator': 'iqn.1993-08.org.debian:01:222',
            'host': 'fakehost'
        }
        self.properties = {
            'target_discoverd': True,
            'target_portal': '10.0.1.6:3260',
            'target_iqn':
            'iqn.2003-10.com.lefthandnetworks:group01:25366:fakev',
            'volume_id': 1
        }
Esempio n. 13
0
    def test_create_for_sanity(self):
        """
        Test creation.
        """
        res = mox.MockObject(core_model.Resource)
        res.attributes = {'occi.storage.size': '1'}

        self.mox.StubOutWithMock(nova_glue.storage, 'create_storage')
        nova_glue.storage.create_storage(mox.IsA(object),
                                         mox.IsA(object),
                                         mox.IsA(object)).\
            AndReturn({'id': '1'})
        self.mox.StubOutWithMock(nova_glue.storage, 'get_storage')
        nova_glue.storage.get_storage(mox.IsA(object),
                                      mox.IsA(object)).\
            AndReturn({'status': 'available'})

        self.mox.ReplayAll()

        self.backend.create(res, self.sec_obj)

        # verify all attrs.
        self.assertEqual(res.attributes['occi.storage.state'], 'active')
        self.assertListEqual([
            infrastructure.OFFLINE, infrastructure.BACKUP,
            infrastructure.SNAPSHOT, infrastructure.RESIZE
        ], res.actions)

        self.mox.VerifyAll()
Esempio n. 14
0
 def setUp(self):
     self.m = mox.Mox()
     self.m_conn = self.m.CreateMock(VShare)
     self.m_conn.basic = self.m.CreateMock(XGSession)
     self.m_conn.lun = self.m.CreateMock(LUNManager)
     self.m_conn.iscsi = self.m.CreateMock(ISCSIManager)
     self.m_conn.igroup = self.m.CreateMock(IGroupManager)
     self.config = mox.MockObject(conf.Configuration)
     self.config.append_config_values(mox.IgnoreArg())
     self.config.gateway_vip = '1.1.1.1'
     self.config.gateway_mga = '2.2.2.2'
     self.config.gateway_mgb = '3.3.3.3'
     self.config.gateway_user = '******'
     self.config.gateway_password = ''
     self.config.use_thin_luns = False
     self.config.use_igroups = False
     self.config.volume_backend_name = 'violin'
     self.config.gateway_iscsi_target_prefix = 'iqn.2004-02.com.vmem:'
     self.driver = violin.ViolinDriver(configuration=self.config)
     self.driver.vmem_vip = self.m_conn
     self.driver.vmem_mga = self.m_conn
     self.driver.vmem_mgb = self.m_conn
     self.driver.container = 'myContainer'
     self.driver.gateway_iscsi_ip_addresses_mga = '1.2.3.4'
     self.driver.gateway_iscsi_ip_addresses_mgb = '1.2.3.4'
     self.driver.array_info = [{
         "node": 'hostname_mga',
         "addr": '1.2.3.4',
         "conn": self.driver.vmem_mga
     }, {
         "node": 'hostname_mgb',
         "addr": '1.2.3.4',
         "conn": self.driver.vmem_mgb
     }]
  def verifyLogLevels(self, levels):
    Level = api_backend.LogMessagesRequest.LogMessage.Level
    message = 'Test message.'
    logger_name = api_backend_service.__name__

    log = mox.MockObject(logging.Logger)
    self.mox.StubOutWithMock(logging, 'getLogger')
    logging.getLogger(logger_name).AndReturn(log)

    for level in levels:
      if level is None:
        level = 'info'
      record = logging.LogRecord(name=logger_name,
                                 level=getattr(logging, level.upper()),
                                 pathname='', lineno='', msg=message,
                                 args=None, exc_info=None)
      log.handle(record)
    self.mox.ReplayAll()

    requestMessages = []
    for level in levels:
      if level:
        requestMessage = api_backend.LogMessagesRequest.LogMessage(
            level=getattr(Level, level), message=message)
      else:
        requestMessage = api_backend.LogMessagesRequest.LogMessage(
            message=message)
      requestMessages.append(requestMessage)

    request = api_backend.LogMessagesRequest(messages=requestMessages)
    self.service.logMessages(request)
    self.mox.VerifyAll()
Esempio n. 16
0
    def test_do_setup(self):
        mock = mox.Mox()
        mock.StubOutWithMock(driver, 'xenapi_lib')
        mock.StubOutWithMock(driver, 'xenapi_opts')

        configuration = mox.MockObject(conf.Configuration)
        configuration.xenapi_connection_url = 'url'
        configuration.xenapi_connection_username = '******'
        configuration.xenapi_connection_password = '******'
        configuration.append_config_values(mox.IgnoreArg())

        session_factory = object()
        nfsops = object()

        driver.xenapi_lib.SessionFactory('url', 'user',
                                         'pass').AndReturn(session_factory)

        driver.xenapi_lib.NFSBasedVolumeOperations(session_factory).AndReturn(
            nfsops)

        drv = driver.XenAPINFSDriver(configuration=configuration)

        mock.ReplayAll()
        drv.do_setup('context')
        mock.VerifyAll()

        self.assertEquals(nfsops, drv.nfs_ops)
Esempio n. 17
0
    def testShowModal(self):
        project = launcher.Project('path', 9000)
        for (wx_rtn, updated_calls) in ((wx.ID_OK, 1), (wx.ID_CANCEL, 0)):
            sc = launcher.SettingsController(project)
            settings_dialog = project_dialogs.ProjectSettingsDialog
            dialog_mock = mox.MockObject(settings_dialog)
            dialog_mock.ShowModal().AndReturn(wx_rtn)
            mox.Replay(dialog_mock)
            sc.dialog = dialog_mock
            actual_updated = [0]

            def plusone():
                """Must use mutable to modify var in enclosing scope."""
                actual_updated[0] += 1

            sc._UpdateProject = plusone
            rtn = sc.ShowModal()
            self.assertEqual(wx_rtn, rtn)
            mox.Verify(dialog_mock)
            self.assertEqual(updated_calls, actual_updated[0])
            # SettingsController needs to Destroy() its dialog.
            # That is done in SettingsController's __del__.
            # But that's past the mox.Verify(), so we can't expect it.
            # We can, however, make sure it doesn't cause mox
            # to yell.
            sc.dialog = None
Esempio n. 18
0
 def testFindsSuperclassMethods(self):
   """Mock should be able to mock superclasses methods."""
   self.mock_object = mox.MockObject(ChildClass)
   self.assert_('ValidCall' in self.mock_object._known_methods)
   self.assert_('OtherValidCall' in self.mock_object._known_methods)
   self.assert_('MyClassMethod' in self.mock_object._known_methods)
   self.assert_('ChildValidCall' in self.mock_object._known_methods)
Esempio n. 19
0
 def setUp(self):
     self._mox = mox.Mox()
     self.configuration = mox.MockObject(conf.Configuration)
     self.configuration.volume_group_name = 'fake-volumes'
     super(BrickLvmTestCase, self).setUp()
     self.stubs.Set(processutils, 'execute', self.fake_execute)
     self.vg = brick.LVM(self.configuration.volume_group_name)
Esempio n. 20
0
def get_configured_driver(server='ignore_server', path='ignore_path'):
    configuration = mox.MockObject(conf.Configuration)
    configuration.xenapi_nfs_server = server
    configuration.xenapi_nfs_serverpath = path
    configuration.append_config_values(mox.IgnoreArg())
    configuration.volume_dd_blocksize = '1M'
    return driver.XenAPINFSDriver(configuration=configuration)
Esempio n. 21
0
    def test_create_for_failure(self):
        """
        Test attachement.
        """
        # msg size attribute
        res = mox.MockObject(core_model.Resource)
        res.attributes = {}
        self.assertRaises(AttributeError, self.backend.create, res,
                          self.sec_obj)

        # error in volume creation
        res.attributes = {'occi.storage.size': '1'}

        self.mox.StubOutWithMock(nova_glue.storage, 'create_storage')
        nova_glue.storage.create_storage(mox.IsA(object),
                                         mox.IsA(object),
                                         mox.IsA(object)).\
            AndReturn({'id': '1'})
        self.mox.StubOutWithMock(nova_glue.storage, 'get_storage')
        nova_glue.storage.get_storage(mox.IsA(object),
                                      mox.IsA(object)).\
            AndReturn({'status': 'error'})

        self.mox.ReplayAll()

        self.assertRaises(exceptions.HTTPError, self.backend.create, res,
                          self.sec_obj)

        self.mox.VerifyAll()
 def testOnPreferences(self):
     ac = launcher.AppController(self.app)
     pref_controller_mock = mox.MockObject(launcher.PrefController)
     pref_controller_mock.ShowModal()
     mox.Replay(pref_controller_mock)
     ac.OnPreferences(None, pref_controller_mock)
     mox.Verify(pref_controller_mock)
Esempio n. 23
0
    def test_leave(self):
        real_typepad_client = typepad.client
        typepad.client = mox.MockObject(httplib2.Http)
        try:
            resp = httplib2.Response({
                'status':           200,
                'etag':             '7',
                'content-type':     'application/json',
                'content-location': 'http://127.0.0.1:8000/relationships/6r00d83451ce6b69e20120a81fb3a4970c/status.json',
            })
            typepad.client.request(
                uri='http://127.0.0.1:8000/relationships/6r00d83451ce6b69e20120a81fb3a4970c/status.json',
                headers={'accept': 'application/json'},
            ).AndReturn((resp, """{"types": ["tag:api.typepad.com,2009:Member"]}"""))
            resp = httplib2.Response({
                'status':           200,
                'etag':             '9',
                'content-type':     'application/json',
                'content-location': 'http://127.0.0.1:8000/relationships/6r00d83451ce6b69e20120a81fb3a4970c/status.json',
            })
            typepad.client.request(
                uri='http://127.0.0.1:8000/relationships/6r00d83451ce6b69e20120a81fb3a4970c/status.json',
                method='PUT',
                headers={'if-match': '7', 'accept': 'application/json', 'content-type': 'application/json'},
                body=mox.Func(json_equals_func({"types": []})),
            ).AndReturn((resp, """{"types": []}"""))
            mox.Replay(typepad.client)

            r = typepad.Relationship.get('http://127.0.0.1:8000/relationships/6r00d83451ce6b69e20120a81fb3a4970c.json')
            r.leave()

            mox.Verify(typepad.client)

        finally:
            typepad.client = real_typepad_client
Esempio n. 24
0
    def test_slice_filter(self):
        class Toybox(self.cls):
            pass

        h = mox.MockObject(httplib2.Http)
        mox.Replay(h)

        b = Toybox.get('http://example.com/foo', http=h)
        self.assertEquals(b._location, 'http://example.com/foo')

        j = b[0:10]
        self.assert_(isinstance(j, Toybox))
        self.assertEquals(j._location,
                          'http://example.com/foo?limit=10&offset=0')

        j = b[300:370]
        self.assert_(isinstance(j, Toybox))
        self.assertEquals(j._location,
                          'http://example.com/foo?limit=70&offset=300')

        j = b[1:]
        self.assert_(isinstance(j, Toybox))
        self.assertEquals(j._location, 'http://example.com/foo?offset=1')

        j = b[:10]
        self.assert_(isinstance(j, Toybox))
        self.assertEquals(j._location, 'http://example.com/foo?limit=10')

        # Nobody did any HTTP, right?
        mox.Verify(h)
 def setUp(self):
     TestBase.setUp(self)
     provider.duo_web = mox.MockObject(DuoWebMock)
     appenginetest.DatastoreTest.setUp(self)
     appenginetest.UsersTest.setUp(self,
                                   user_email='*****@*****.**',
                                   user_is_admin='')
Esempio n. 26
0
def test_record_messages():
    conn = mox.MockObject(impl_kombu.Connection)
    conn.declare_topic_consumer('notifications.info',
                                mox.IsA(types.FunctionType))
    conn.consume()
    mox.Replay(conn)
    notificationclient.record_messages(conn, 'notifications.info', StringIO())
    mox.Verify(conn)
Esempio n. 27
0
  def testVerify(self):
    """Verify should be called for all objects.

    This should throw an exception because the expected behavior did not occur.
    """
    mock_obj = mox.MockObject(TestClass)
    mock_obj.ValidCall()
    mock_obj._Replay()
    self.assertRaises(mox.ExpectedMethodCallsError, mox.Verify, mock_obj)
Esempio n. 28
0
    def test_readdir_dir_not_exists(self):
        DIRPATH = '/DIR'

        cacheManagerMock = self.sut.cacheManager = mox.MockObject(
            cachefs.CacheManager)
        cacheManagerMock.exists(DIRPATH).AndReturn(False)
        mox.Replay(cacheManagerMock)

        self.assertEqual(None, self.sut.readdir(DIRPATH).next())
Esempio n. 29
0
    def test_opendir_path_not_exists(self):
        DIRPATH = '/DIR'

        cacheManagerMock = self.sut.cacheManager = mox.MockObject(
            cachefs.CacheManager)
        cacheManagerMock.exists(DIRPATH).AndReturn(False)
        mox.Replay(cacheManagerMock)

        self.assertEqual(-errno.ENOENT, self.sut.opendir(DIRPATH))
Esempio n. 30
0
    def setUp(self):
        """Initialize IVM XIV Driver."""
        super(XIVVolumeDriverTest, self).setUp()

        configuration = mox.MockObject(conf.Configuration)
        configuration.san_is_local = False
        configuration.append_config_values(mox.IgnoreArg())

        self.driver = xiv.XIVDriver(configuration=configuration)