def setUp(self): super(TestCfnHup, self).setUp() self.m = mox.Mox() self.logger = self.useFixture(fixtures.FakeLogger()) self.stack_name = self.getUniqueString() self.resource = self.getUniqueString() self.region = self.getUniqueString() self.creds = tempfile.NamedTemporaryFile() self.metadata = cfn_helper.Metadata(self.stack_name, self.resource, credentials_file=self.creds.name, region=self.region) self.init_content = self.getUniqueString() self.init_temp = tempfile.NamedTemporaryFile() self.service_name = self.getUniqueString() self.init_section = { 'AWS::CloudFormation::Init': { 'config': { 'services': { 'sysvinit': { self.service_name: { 'enabled': True, 'ensureRunning': True, } } }, 'files': { self.init_temp.name: { 'content': self.init_content } } } } }
def _init(self): self.mock = mox.Mox() self.instance_id = 500 context = trove_testtools.TroveTestContext(self) self.db_info = DBInstance.create( name="instance", flavor_id=OLD_FLAVOR_ID, tenant_id=999, volume_size=None, datastore_version_id=test_config.dbaas_datastore_version_id, task_status=InstanceTasks.RESIZING) self.server = self.mock.CreateMock(Server) self.instance = models.BuiltInstanceTasks( context, self.db_info, self.server, datastore_status=InstanceServiceStatus.create( instance_id=self.db_info.id, status=rd_instance.ServiceStatuses.RUNNING)) self.instance.server.flavor = {'id': OLD_FLAVOR_ID} self.guest = self.mock.CreateMock(guest.API) self.instance._guest = self.guest self.instance.refresh_compute_server_info = lambda: None self.instance._refresh_datastore_status = lambda: None self.mock.StubOutWithMock(self.instance, 'update_db') self.mock.StubOutWithMock(self.instance, 'set_datastore_status_to_paused') self.poll_until_mocked = False self.action = None
def setUp(self): super(TestClient, self).setUp() self.mock = mox.Mox() self.mock.StubOutWithMock(requests.Session, 'request') self.endpoint = 'http://example.com:9292' self.client = http.HTTPClient(self.endpoint, token=u'abc123')
def test_json_credentials_storage(self): access_token = 'foo' client_id = 'some_client_id' client_secret = 'cOuDdkfjxxnv+' refresh_token = '1/0/a.df219fjls0' token_expiry = datetime.datetime.utcnow() user_agent = 'refresh_checker/1.0' credentials = OAuth2Credentials( access_token, client_id, client_secret, refresh_token, token_expiry, GOOGLE_TOKEN_URI, user_agent) m = mox.Mox() m.StubOutWithMock(keyring, 'get_password') m.StubOutWithMock(keyring, 'set_password') keyring.get_password('my_unit_test', 'me').AndReturn(None) keyring.set_password('my_unit_test', 'me', credentials.to_json()) keyring.get_password('my_unit_test', 'me').AndReturn(credentials.to_json()) m.ReplayAll() s = Storage('my_unit_test', 'me') self.assertEquals(None, s.get()) s.put(credentials) restored = s.get() self.assertEqual('foo', restored.access_token) self.assertEqual('some_client_id', restored.client_id) m.UnsetStubs() m.VerifyAll()
def test_interval_adjustment(self): """Ensure the interval is adjusted to account for task duration.""" self.num_runs = 3 now = time.time() second = 1 smidgen = 0.01 m = mox.Mox() m.StubOutWithMock(greenthread, 'sleep') greenthread.sleep(mox.IsAlmost(0.02)) greenthread.sleep(mox.IsAlmost(0.0)) greenthread.sleep(mox.IsAlmost(0.0)) m.StubOutWithMock(loopingcall, '_ts') loopingcall._ts().AndReturn(now) loopingcall._ts().AndReturn(now + second - smidgen) loopingcall._ts().AndReturn(now) loopingcall._ts().AndReturn(now + second + second) loopingcall._ts().AndReturn(now) loopingcall._ts().AndReturn(now + second + smidgen) loopingcall._ts().AndReturn(now) m.ReplayAll() timer = loopingcall.FixedIntervalLoopingCall(self._wait_for_zero) timer.start(interval=1.01).wait() m.UnsetStubs() m.VerifyAll()
def test_fail_refresh(self): m = mox.Mox() httplib2_response = m.CreateMock(object) httplib2_response.status = 400 httplib2_request = m.CreateMock(object) httplib2_request.__call__(( 'http://metadata.google.internal/0.1/meta-data/service-accounts/' 'default/acquire' '?scope=http%3A%2F%2Fexample.com%2Fa%20http%3A%2F%2Fexample.com%2Fb' )).AndReturn((httplib2_response, '{"accessToken": "this-is-a-token"}')) m.ReplayAll() c = AppAssertionCredentials( scope=['http://example.com/a', 'http://example.com/b']) try: c._refresh(httplib2_request) self.fail('Should have raised exception on 400') except AccessTokenRefreshError: pass m.UnsetStubs() m.VerifyAll()
def setUp(self): """Run before each test method to initialize test environment.""" super(TestCase, self).setUp() self.mox = mox.Mox() self.setup_config() self.addCleanup(cfg.CONF.reset) config.setup_logging() test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0) try: test_timeout = int(test_timeout) except ValueError: # If timeout value is invalid do not set a timeout. test_timeout = 0 if test_timeout > 0: self.useFixture(fixtures.Timeout(test_timeout, gentle=True)) self.useFixture(fixtures.NestedTempfile()) self.useFixture(fixtures.TempHomeDir()) self.addCleanup(mock.patch.stopall) if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES: stdout = self.useFixture(fixtures.StringStream('stdout')).stream self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout)) if os.environ.get('OS_STDERR_CAPTURE') in _TRUE_VALUES: stderr = self.useFixture(fixtures.StringStream('stderr')).stream self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr)) self.log_fixture = self.useFixture(fixtures.FakeLogger()) self.policy = self.useFixture(policy_fixture.PolicyFixture())
def setUp(self): super(TestHTTPClientMixin, self).setUp() self.clazz, self.http = self.initialize() self.mox = mox.Mox() self.addCleanup(self.mox.UnsetStubs) self.mox.StubOutWithMock(self.clazz, '_request')
def setUp(self): super(TestScrubber, self).setUp() glance_store.register_opts(CONF) self.config(group='glance_store', default_store='file', filesystem_store_datadir=self.test_dir) glance_store.create_stores() self.mox = mox.Mox()
def setUp(self): super(NfsDriverTestCase, self).setUp() self.mox = mox_lib.Mox() self.stubs = stubout.StubOutForTesting() self.configuration = mox_lib.MockObject(conf.Configuration) self.configuration.append_config_values(mox_lib.IgnoreArg()) self.configuration.nfs_shares_config = None self.configuration.nfs_sparsed_volumes = True self.configuration.nfs_used_ratio = 0.95 self.configuration.nfs_oversub_ratio = 1.0 self.configuration.nfs_mount_point_base = self.TEST_MNT_POINT_BASE self.configuration.nfs_mount_options = None self.configuration.nfs_mount_attempts = 3 self.configuration.nfs_qcow2_volumes = False self.configuration.nas_secure_file_permissions = 'false' self.configuration.nas_secure_file_operations = 'false' self.configuration.nas_ip = None self.configuration.nas_share_path = None self.configuration.nas_mount_options = None self.configuration.reserved_percentage = 0 self.configuration.volume_dd_blocksize = '1M' self._driver = nfs.NfsDriver(configuration=self.configuration) self._driver.shares = {} self.addCleanup(self.stubs.UnsetAll) self.addCleanup(self.mox.UnsetStubs)
def setUp(self): super(TestBittorrentStore, self).setUp() self.store = bittorrent.BittorrentStore() self.mox = mox.Mox() self.flags(torrent_base_url='http://foo', connection_url='test_url', connection_password='******', group='xenserver') self.context = context.RequestContext('user', 'project', auth_token='foobar') fake.reset() stubs.stubout_session(self.stubs, fake.SessionBase) def mock_iter_eps(namespace): return [] self.stubs.Set(pkg_resources, 'iter_entry_points', mock_iter_eps) driver = xenapi_conn.XenAPIDriver(False) self.session = driver._session self.stubs.Set(vm_utils, 'get_sr_path', lambda *a, **kw: '/fake/sr/path')
def test_get_access_token(self): m = mox.Mox() httplib2_response = m.CreateMock(object) httplib2_response.status = 200 httplib2_request = m.CreateMock(object) httplib2_request.__call__( ('http://metadata.google.internal/0.1/meta-data/service-accounts/' 'default/acquire?scope=dummy_scope')).AndReturn( (httplib2_response, '{"accessToken": "this-is-a-token"}')) m.ReplayAll() credentials = AppAssertionCredentials(['dummy_scope']) http = httplib2.Http() http.request = httplib2_request token = credentials.get_access_token(http=http) self.assertEqual('this-is-a-token', token.access_token) self.assertEqual(None, token.expires_in) m.UnsetStubs() m.VerifyAll()
def setUp(self, plurals=None): """Prepare the test environment.""" super(CLITestV20Base, self).setUp() client.Client.EXTED_PLURALS.update(constants.PLURALS) if plurals is not None: client.Client.EXTED_PLURALS.update(plurals) self.metadata = { 'plurals': client.Client.EXTED_PLURALS, 'xmlns': constants.XML_NS_V20, constants.EXT_NS: { 'prefix': 'http://xxxx.yy.com' } } self.mox = mox.Mox() self.endurl = ENDURL self.fake_stdout = FakeStdout() self.useFixture(fixtures.MonkeyPatch('sys.stdout', self.fake_stdout)) self.useFixture( fixtures.MonkeyPatch( 'neutronclient.neutron.v2_0.find_resourceid_by_name_or_id', self._find_resourceid)) self.useFixture( fixtures.MonkeyPatch( 'neutronclient.neutron.v2_0.find_resourceid_by_id', self._find_resourceid)) self.useFixture( fixtures.MonkeyPatch( 'neutronclient.v2_0.client.Client.get_attr_metadata', self._get_attr_metadata)) self.client = client.Client(token=TOKEN, endpoint_url=self.endurl)
def test_get_tags(self): self.m = mox.Mox() self.addCleanup(self.m.UnsetStubs) fake_tags = {'foo': 'fee', 'apple': 'red'} md_data = { "uuid": "f9431d18-d971-434d-9044-5b38f5b4646f", "availability_zone": "nova", "hostname": "as-wikidatabase-4ykioj3lgi57.novalocal", "launch_index": 0, "meta": fake_tags, "public_keys": { "heat_key": "ssh-rsa etc...\n" }, "name": "as-WikiDatabase-4ykioj3lgi57" } tags_expect = fake_tags tags_expect['InstanceId'] = md_data['uuid'] md = cfn_helper.Metadata('teststack', None) self.m.StubOutWithMock(md, 'get_nova_meta') md.get_nova_meta().AndReturn(md_data) self.m.ReplayAll() tags = md.get_tags() self.assertEqual(tags_expect, tags) self.m.VerifyAll()
def test_nova_meta_wget_corrupt(self): url = 'http://169.254.169.254/openstack/2012-08-10/meta_data.json' temp_home = tempfile.mkdtemp() cache_path = os.path.join(temp_home, 'meta_data.json') def cleanup_temp_home(thome): os.unlink(cache_path) os.rmdir(thome) self.m = mox.Mox() self.addCleanup(self.m.UnsetStubs) self.addCleanup(cleanup_temp_home, temp_home) md_str = "this { is not really json" def write_cache_file(*params, **kwargs): with open(cache_path, 'w+') as cache_file: cache_file.write(md_str) cache_file.flush() self.assertThat(cache_file.name, ttm.FileContains(md_str)) self.m.StubOutWithMock(subprocess, 'Popen') subprocess.Popen(['su', 'root', '-c', 'wget -O %s %s' % (cache_path, url)], cwd=None, env=None, stderr=-1, stdout=-1)\ .WithSideEffects(write_cache_file)\ .AndReturn(FakePOpen('Downloaded', '', 0)) self.m.ReplayAll() md = cfn_helper.Metadata('teststack', None) meta_out = md.get_nova_meta(cache_path=cache_path) self.assertEqual(None, meta_out) self.m.VerifyAll()
def test_backup_volume(self): self.mox = mox_lib.Mox() self._driver.db = self.mox.CreateMockAnything() self.mox.StubOutWithMock(self._driver.db, 'volume_get') volume = {'id': '2', 'name': self.TEST_VOLNAME} self._driver.db.volume_get(context, volume['id']).AndReturn(volume) info = imageutils.QemuImgInfo() info.file_format = 'raw' self.mox.StubOutWithMock(image_utils, 'qemu_img_info') image_utils.qemu_img_info(self.TEST_VOLPATH).AndReturn(info) self.mox.StubOutWithMock(utils, 'temporary_chown') mock_tempchown = mock.MagicMock() utils.temporary_chown(self.TEST_VOLPATH).AndReturn(mock_tempchown) self.mox.StubOutWithMock(fileutils, 'file_open') mock_fileopen = mock.MagicMock() fileutils.file_open(self.TEST_VOLPATH).AndReturn(mock_fileopen) backup = {'volume_id': volume['id']} mock_servicebackup = self.mox.CreateMockAnything() mock_servicebackup.backup(backup, mox_lib.IgnoreArg()) self.mox.ReplayAll() self._driver.backup_volume(context, backup, mock_servicebackup)
def setUp(self): super(OpenStackAuthTestsWebSSO, self).setUp() self.mox = mox.Mox() self.addCleanup(self.mox.VerifyAll) self.addCleanup(self.mox.UnsetStubs) self.data = data_v3.generate_test_data() self.ks_client_module = client_v3 self.idp_id = uuid.uuid4().hex self.idp_oidc_id = uuid.uuid4().hex self.idp_saml2_id = uuid.uuid4().hex settings.OPENSTACK_API_VERSIONS['identity'] = 3 settings.OPENSTACK_KEYSTONE_URL = 'http://localhost:5000/v3' settings.WEBSSO_ENABLED = True settings.WEBSSO_CHOICES = ( ('credentials', 'Keystone Credentials'), ('oidc', 'OpenID Connect'), ('saml2', 'Security Assertion Markup Language'), (self.idp_oidc_id, 'IDP OIDC'), (self.idp_saml2_id, 'IDP SAML2') ) settings.WEBSSO_IDP_MAPPING = { self.idp_oidc_id: (self.idp_id, 'oidc'), self.idp_saml2_id: (self.idp_id, 'saml2') } self.mox.StubOutClassWithMocks(token_endpoint, 'Token') self.mox.StubOutClassWithMocks(v3_auth, 'Token') self.mox.StubOutClassWithMocks(v3_auth, 'Password') self.mox.StubOutClassWithMocks(client_v3, 'Client')
def setUp(self): super(ShellTest, self).setUp() self.mox = mox.Mox() for var in self.FAKE_ENV: self.useFixture( fixtures.EnvironmentVariable( var, self.FAKE_ENV[var]))
def setUp(self): super(TestSSL, self).setUp() self.useFixture(fixtures.EnvironmentVariable('OS_TOKEN', AUTH_TOKEN)) self.useFixture(fixtures.EnvironmentVariable('OS_URL', END_URL)) self.mox = mox.Mox() self.addCleanup(self.mox.UnsetStubs)
def __init__(self, *args, **kwargs): self.__expect = [] self.__output = [] self.__error = [] self.__popen = [] self.__call = [] self.mox = mox.Mox() CLI.__init__(self, *args, **kwargs)
def setUp(self): """ Create mock oauth object """ self.mox = mox.Mox() self.oauth = PlurkOAuth("CONSUMER_KEY", "CONSUMER_SECRET") self.oauth_response = \ 'oauth_token_secret=O7WqqqWHA61f4ZE5izQdTQmK&oauth_token=ReqXBFOswcyR&oauth_callback_confirmed=true' # NOQA self.golden_token = dict(parse_qsl(self.oauth_response)) self.mox.StubOutWithMock(PlurkOAuth, 'request')
def setUp(self): super(TestCase, self).setUp() self.mox = mox.Mox() self.logger = self.useFixture(fixtures.FakeLogger(level=logging.DEBUG)) self.time_patcher = mock.patch.object(time, 'time', lambda: 1234) self.time_patcher.start() self.requests = self.useFixture(fixture.Fixture())
def setUp(self): super(TestClient, self).setUp() self.mock = mox.Mox() self.mock.StubOutWithMock(http_client.HTTPConnection, 'request') self.mock.StubOutWithMock(http_client.HTTPConnection, 'getresponse') self.endpoint = 'http://example.com:9292' self.client = http.HTTPClient(self.endpoint, token=u'abc123')
def setUp(self): self.data_dir = tempfile.mkdtemp() self.config(scrubber_datadir=self.data_dir) glance_store.register_opts(CONF) glance_store.create_stores() self.config(group='glance_store', default_store='file') self.mox = mox.Mox() super(TestScrubber, self).setUp()
def setUp(self): super(MoxStubout, self).setUp() self.mox = mox.Mox() self.stubs = stubout.StubOutForTesting() self.addCleanup(self.mox.UnsetStubs) self.addCleanup(self.stubs.UnsetAll) self.addCleanup(self.stubs.SmartUnsetAll) self.addCleanup(self.mox.VerifyAll)
def setUp(self): self.ais = aprslib.IS("LZ1DEV-99") self.ais._connected = True self.m = mox.Mox() self.m.StubOutWithMock(self.ais, "_socket_readlines") self.m.StubOutWithMock(self.ais, "_parse") self.m.StubOutWithMock(self.ais, "connect") self.m.StubOutWithMock(self.ais, "close")
def setUp(self): # Create execution path self.environment_path = tempfile.mkdtemp() self.child_path = tempfile.mkdtemp() self.mox = mox.Mox() self.dvcs = self.mox.CreateMock(DepotOperations()) self.depot = Depot(self.environment_path, None, self.dvcs)
def setUp(self): super(MoxStubout, self).setUp() # emulate some of the mox stuff, we can't use the metaclass # because it screws with our generators self.mox = mox.Mox() self.stubs = self.mox.stubs self.addCleanup(self.mox.UnsetStubs) self.addCleanup(self.mox.VerifyAll)
def setUp(self): super(TestHTTPClient, self).setUp() self.mox = mox.Mox() self.mox.StubOutWithMock(HTTPClient, 'request') self.addCleanup(self.mox.UnsetStubs) self.http = HTTPClient(token=AUTH_TOKEN, endpoint_url=END_URL)
def setUp(self): """Prepare the test environment.""" super(CLITestNameorID, self).setUp() self.mox = mox.Mox() self.endurl = test_cli20.ENDURL self.client = client.Client(token=test_cli20.TOKEN, endpoint_url=self.endurl) self.addCleanup(self.mox.VerifyAll) self.addCleanup(self.mox.UnsetStubs)