Python fixtures.TempDir() Examples

The following are 30 code examples of fixtures.TempDir(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module fixtures , or try the search function .
Example #1
Source File: test_baseline.py    From bandit with Apache License 2.0 6 votes vote down vote up
def test_initialize_dirty_repo(self):
        # Test that bandit does not run when the current git repository is
        # 'dirty' when calling the initialize method
        repo_directory = self.useFixture(fixtures.TempDir()).path
        git_repo = git.Repo.init(repo_directory)
        git_repo.index.commit('Initial Commit')
        os.chdir(repo_directory)

        # make the git repo 'dirty'
        with open('dirty_file.py', 'wt') as fd:
            fd.write(self.temp_file_contents)
        git_repo.index.add(['dirty_file.py'])

        return_value = baseline.initialize()

        # assert bandit did not run due to dirty repo
        self.assertEqual((None, None, None), return_value) 
Example #2
Source File: test_chartbuilder.py    From armada with Apache License 2.0 6 votes vote down vote up
def test_get_files_always_fails_to_read_binary_file_raises_exc(self):
        chart_dir = self.useFixture(fixtures.TempDir())
        self.addCleanup(shutil.rmtree, chart_dir.path)
        for filename in ['foo', 'bar', 'Chart.yaml', 'values.yaml']:
            self._write_temporary_file_contents(
                chart_dir.path, filename, "DIRC^@^@^@^B^@^@^@×Z®<86>F.1")

        chartbuilder = ChartBuilder.from_chart_doc(
            self._get_test_chart(chart_dir))

        # Confirm it failed for both encodings.
        error_re = (
            r'.*A str exception occurred while trying to read file:'
            r'.*Details:\n.*\(encoding=utf-8\).*\n\(encoding=latin1\)')
        with mock.patch("builtins.open", mock.mock_open(read_data="")) \
                as mock_file:
            mock_file.return_value.read.side_effect = self.exc_to_raise
            self.assertRaisesRegexp(
                chartbuilder_exceptions.FilesLoadException, error_re,
                chartbuilder.get_files) 
Example #3
Source File: fixtures.py    From armada with Apache License 2.0 6 votes vote down vote up
def _setUp(self):
        super(RealPolicyFixture, self)._setUp()
        self.policy_dir = self.useFixture(fixtures.TempDir())
        self.policy_file = os.path.join(self.policy_dir.path,
                                        'policy.yaml')
        # Load the fake_policy data and add the missing default rules.
        policy_rules = yaml.safe_load(fake_policy.policy_data)
        self.add_missing_default_rules(policy_rules)
        with open(self.policy_file, 'w') as f:
            yaml.safe_dump(policy_rules, f)

        policy_opts.set_defaults(CONF)
        self.useFixture(
            ConfPatcher(policy_dirs=[], policy_file=self.policy_file,
                        group='oslo_policy'))

        armada.common.policy.reset_policy()
        armada.common.policy.setup_policy()
        self.addCleanup(armada.common.policy.reset_policy)

        if self.verify:
            self._install_policy_verification_hook() 
Example #4
Source File: test_chartbuilder.py    From armada with Apache License 2.0 6 votes vote down vote up
def test_get_helm_chart_with_values(self):
        chart_dir = self.useFixture(fixtures.TempDir())
        self.addCleanup(shutil.rmtree, chart_dir.path)

        self._write_temporary_file_contents(chart_dir.path, 'Chart.yaml',
                                            self.chart_yaml)
        self._write_temporary_file_contents(chart_dir.path, 'values.yaml',
                                            self.chart_value)

        ch = yaml.safe_load(self.chart_stream)['chart']
        ch['source_dir'] = (chart_dir.path, '')

        test_chart = ch
        chartbuilder = ChartBuilder(test_chart)
        helm_chart = chartbuilder.get_helm_chart()

        self.assertIsInstance(helm_chart, Chart)
        self.assertTrue(hasattr(helm_chart, 'metadata'))
        self.assertTrue(hasattr(helm_chart, 'values'))
        self.assertTrue(hasattr(helm_chart.values, 'raw'))
        self.assertEqual(self.chart_value, helm_chart.values.raw) 
Example #5
Source File: test_chartbuilder.py    From armada with Apache License 2.0 6 votes vote down vote up
def test_get_helm_chart_with_values(self):
        chart_dir = self.useFixture(fixtures.TempDir())
        self.addCleanup(shutil.rmtree, chart_dir.path)

        self._write_temporary_file_contents(
            chart_dir.path, 'Chart.yaml', self.chart_yaml)
        self._write_temporary_file_contents(
            chart_dir.path, 'values.yaml', self.chart_value)

        ch = yaml.safe_load(self.chart_stream)
        ch['data']['source_dir'] = (chart_dir.path, '')

        test_chart = ch
        chartbuilder = ChartBuilder.from_chart_doc(test_chart)
        helm_chart = chartbuilder.get_helm_chart()

        self.assertIsInstance(helm_chart, Chart)
        self.assertTrue(hasattr(helm_chart, 'metadata'))
        self.assertTrue(hasattr(helm_chart, 'values'))
        self.assertTrue(hasattr(helm_chart.values, 'raw'))
        self.assertEqual(self.chart_value, helm_chart.values.raw) 
Example #6
Source File: test_chartbuilder.py    From armada with Apache License 2.0 6 votes vote down vote up
def test_get_files_fails_once_to_read_binary_file_passes(self):
        chart_dir = self.useFixture(fixtures.TempDir())
        self.addCleanup(shutil.rmtree, chart_dir.path)
        files = ['foo', 'bar']
        for filename in files:
            self._write_temporary_file_contents(
                chart_dir.path, filename, "DIRC^@^@^@^B^@^@^@×Z®<86>F.1")

        test_chart = {'source_dir': (chart_dir.path, '')}
        chartbuilder = ChartBuilder(test_chart)

        side_effects = [self.exc_to_raise, "", ""]
        with mock.patch("builtins.open", mock.mock_open(read_data="")) \
                as mock_file:
            mock_file.return_value.read.side_effect = side_effects
            chartbuilder.get_files() 
Example #7
Source File: test_baseline.py    From bandit with Apache License 2.0 6 votes vote down vote up
def test_main_git_command_failure(self):
        # Test that bandit does not run when the Git command fails
        repo_directory = self.useFixture(fixtures.TempDir()).path
        git_repo = git.Repo.init(repo_directory)
        git_repo.index.commit('Initial Commit')
        os.chdir(repo_directory)

        additional_content = 'additional_file.py'
        with open(additional_content, 'wt') as fd:
            fd.write(self.temp_file_contents)
        git_repo.index.add([additional_content])
        git_repo.index.commit('Additional Content')

        with mock.patch('git.Repo.commit') as mock_git_repo_commit:
            mock_git_repo_commit.side_effect = git.exc.GitCommandError(
                'commit', '')

            # assert the system exits with code 2
            self.assertRaisesRegex(SystemExit, '2', baseline.main) 
Example #8
Source File: test_filesystem_store.py    From glance_store with Apache License 2.0 6 votes vote down vote up
def test_configure_add_with_multi_datadirs(self):
        """
        Tests multiple filesystem specified by filesystem_store_datadirs
        are parsed correctly.
        """
        store_map = [self.useFixture(fixtures.TempDir()).path,
                     self.useFixture(fixtures.TempDir()).path]
        self.conf.set_override('filesystem_store_datadir',
                               override=None,
                               group='glance_store')
        self.conf.set_override('filesystem_store_datadirs',
                               [store_map[0] + ":100",
                                store_map[1] + ":200"],
                               group='glance_store')
        self.store.configure_add()

        expected_priority_map = {100: [store_map[0]], 200: [store_map[1]]}
        expected_priority_list = [200, 100]
        self.assertEqual(expected_priority_map, self.store.priority_data_map)
        self.assertEqual(expected_priority_list, self.store.priority_list) 
Example #9
Source File: fixtures.py    From armada with Apache License 2.0 6 votes vote down vote up
def _setUp(self):
        super(RealPolicyFixture, self)._setUp()
        self.policy_dir = self.useFixture(fixtures.TempDir())
        self.policy_file = os.path.join(self.policy_dir.path, 'policy.yaml')
        # Load the fake_policy data and add the missing default rules.
        policy_rules = yaml.safe_load(fake_policy.policy_data)
        self.add_missing_default_rules(policy_rules)
        with open(self.policy_file, 'w') as f:
            yaml.safe_dump(policy_rules, f)

        policy_opts.set_defaults(CONF)
        self.useFixture(
            ConfPatcher(
                policy_dirs=[],
                policy_file=self.policy_file,
                group='oslo_policy'))

        armada.common.policy.reset_policy()
        armada.common.policy.setup_policy()
        self.addCleanup(armada.common.policy.reset_policy)

        if self.verify:
            self._install_policy_verification_hook() 
Example #10
Source File: test_baseline.py    From bandit with Apache License 2.0 6 votes vote down vote up
def test_initialize_git_command_failure(self):
        # Test that bandit does not run when the Git command fails
        repo_directory = self.useFixture(fixtures.TempDir()).path
        git_repo = git.Repo.init(repo_directory)
        git_repo.index.commit('Initial Commit')
        os.chdir(repo_directory)

        additional_content = 'additional_file.py'
        with open(additional_content, 'wt') as fd:
            fd.write(self.temp_file_contents)
        git_repo.index.add([additional_content])
        git_repo.index.commit('Additional Content')

        with mock.patch('git.Repo') as mock_git_repo:
            mock_git_repo.side_effect = git.exc.GitCommandNotFound('clone', '')

            return_value = baseline.initialize()

            # assert bandit did not run due to git command failure
            self.assertEqual((None, None, None), return_value) 
Example #11
Source File: test_packaging.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
def _setUp(self):
        tmpdir = self.useFixture(fixtures.TempDir()).path
        package_dirs = {}
        for pkg_name in self.packages:
            pkg_path = os.path.join(tmpdir, pkg_name)
            package_dirs[pkg_name] = pkg_path
            os.mkdir(pkg_path)
            for cf in ['setup.py', 'setup.cfg']:
                if cf in self.packages[pkg_name]:
                    contents = self.packages[pkg_name].pop(cf)
                else:
                    contents = self.defaults[cf].format(pkg_name=pkg_name)
                self._writeFile(pkg_path, cf, contents)

            for cf in self.packages[pkg_name]:
                self._writeFile(pkg_path, cf, self.packages[pkg_name][cf])
            self.useFixture(TestRepo(pkg_path)).commit()
        self.addCleanup(delattr, self, 'package_dirs')
        self.package_dirs = package_dirs
        return package_dirs 
Example #12
Source File: test_baseline.py    From bandit with Apache License 2.0 6 votes vote down vote up
def test_initialize_existing_report_file(self):
        # Test that bandit does not run when the output file exists (and the
        # provided output format does not match the default format) when
        # calling the initialize method
        repo_directory = self.useFixture(fixtures.TempDir()).path
        git_repo = git.Repo.init(repo_directory)
        git_repo.index.commit('Initial Commit')
        os.chdir(repo_directory)

        # create an existing version of output report file
        existing_report = "{}.{}".format(baseline.report_basename, 'txt')
        with open(existing_report, 'wt') as fd:
            fd.write(self.temp_file_contents)

        return_value = baseline.initialize()

        # assert bandit did not run due to existing report file
        self.assertEqual((None, None, None), return_value) 
Example #13
Source File: test_filesystem_store.py    From glance_store with Apache License 2.0 6 votes vote down vote up
def test_configure_add_same_dir_multiple_times(self):
        """
        Tests BadStoreConfiguration exception is raised if same directory
        is specified multiple times in filesystem_store_datadirs.
        """
        store_map = [self.useFixture(fixtures.TempDir()).path,
                     self.useFixture(fixtures.TempDir()).path]
        self.conf.clear_override('filesystem_store_datadir',
                                 group='glance_store')
        self.conf.set_override('filesystem_store_datadirs',
                               [store_map[0] + ":100",
                                store_map[1] + ":200",
                                store_map[0] + ":300"],
                               group='glance_store')
        self.assertRaises(exceptions.BadStoreConfiguration,
                          self.store.configure_add) 
Example #14
Source File: test_multistore_filesystem.py    From glance_store with Apache License 2.0 6 votes vote down vote up
def test_configure_add_same_dir_multiple_times(self):
        """Tests handling of same dir in config multiple times.

        Tests BadStoreConfiguration exception is raised if same directory
        is specified multiple times in filesystem_store_datadirs with different
        priorities.
        """
        store_map = [self.useFixture(fixtures.TempDir()).path,
                     self.useFixture(fixtures.TempDir()).path]
        self.conf.clear_override('filesystem_store_datadir',
                                 group='file1')
        self.conf.set_override('filesystem_store_datadirs',
                               [store_map[0] + ":100",
                                store_map[1] + ":200",
                                store_map[0] + ":300"],
                               group='file1')
        self.assertRaises(exceptions.BadStoreConfiguration,
                          self.store.configure_add) 
Example #15
Source File: test_main.py    From bandit with Apache License 2.0 6 votes vote down vote up
def test_main_handle_ini_options(self):
        # Test that bandit handles cmdline args from a bandit.yaml file
        temp_directory = self.useFixture(fixtures.TempDir()).path
        os.chdir(temp_directory)
        with open('bandit.yaml', 'wt') as fd:
            fd.write(bandit_config_content)
        with mock.patch('bandit.cli.main._get_options_from_ini'
                        ) as mock_get_opts:
            mock_get_opts.return_value = {"exclude": "/tmp",
                                          "skips": "skip_test",
                                          "tests": "some_test"}

            with mock.patch('bandit.cli.main.LOG.error') as err_mock:
                # SystemExit with code 2 when test not found in profile
                self.assertRaisesRegex(SystemExit, '2', bandit.main)
                self.assertEqual(str(err_mock.call_args[0][0]),
                                 'Unknown test found in profile: some_test') 
Example #16
Source File: test_setup.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
def setUp(self):
        super(SkipFileWrites, self).setUp()
        self.temp_path = self.useFixture(fixtures.TempDir()).path
        self.root_dir = os.path.abspath(os.path.curdir)
        self.git_dir = os.path.join(self.root_dir, ".git")
        if not os.path.exists(self.git_dir):
            self.skipTest("%s is missing; skipping git-related checks"
                          % self.git_dir)
            return
        self.filename = os.path.join(self.temp_path, self.filename)
        self.option_dict = dict()
        if self.option_key is not None:
            self.option_dict[self.option_key] = ('setup.cfg',
                                                 self.option_value)
        self.useFixture(
            fixtures.EnvironmentVariable(self.env_key, self.env_value)) 
Example #17
Source File: test_multistore_cinder.py    From glance_store with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        super(TestMultiCinderStore, self).setUp()
        enabled_backends = {
            "cinder1": "cinder",
            "cinder2": "cinder"
        }
        self.conf = self._CONF
        self.conf(args=[])
        self.conf.register_opt(cfg.DictOpt('enabled_backends'))
        self.config(enabled_backends=enabled_backends)
        store.register_store_opts(self.conf)
        self.config(default_backend='cinder1', group='glance_store')

        # Ensure stores + locations cleared
        location.SCHEME_TO_CLS_BACKEND_MAP = {}
        store.create_multi_stores(self.conf)

        self.addCleanup(setattr, location, 'SCHEME_TO_CLS_BACKEND_MAP',
                        dict())
        self.test_dir = self.useFixture(fixtures.TempDir()).path
        self.addCleanup(self.conf.reset)

        self.store = cinder.Store(self.conf, backend="cinder1")
        self.store.configure()
        self.register_store_backend_schemes(self.store, 'cinder', 'cinder1')
        self.store.READ_CHUNKSIZE = 4096
        self.store.WRITE_CHUNKSIZE = 4096

        fake_sc = [{u'endpoints': [{u'publicURL': u'http://foo/public_url'}],
                    u'endpoints_links': [],
                    u'name': u'cinder',
                    u'type': u'volumev2'}]
        self.context = FakeObject(service_catalog=fake_sc,
                                  user='fake_user',
                                  auth_token='fake_token',
                                  tenant='fake_tenant') 
Example #18
Source File: test_swift_store_multibackend.py    From glance_store with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        super(TestChunkReader, self).setUp()
        enabled_backends = {
            "swift1": "swift",
            "swift2": "swift",
        }
        self.conf = self._CONF
        self.conf(args=[])
        self.conf.register_opt(cfg.DictOpt('enabled_backends'))
        self.config(enabled_backends=enabled_backends)
        store.register_store_opts(self.conf)
        self.config(default_backend='swift1', group='glance_store')

        # Ensure stores + locations cleared
        location.SCHEME_TO_CLS_BACKEND_MAP = {}

        store.create_multi_stores(self.conf)
        self.addCleanup(setattr, location, 'SCHEME_TO_CLS_BACKEND_MAP',
                        dict())
        self.test_dir = self.useFixture(fixtures.TempDir()).path

        config = copy.deepcopy(SWIFT_CONF)
        self.store = Store(self.conf, backend="swift1")
        self.config(group="swift1", **config)
        self.store.configure()
        self.register_store_backend_schemes(self.store, 'swift', 'swift1')

        self.addCleanup(self.conf.reset) 
Example #19
Source File: test_swift_store_multibackend.py    From glance_store with Apache License 2.0 5 votes vote down vote up
def test_single_tenant_location_http(self):
        conf_file = "glance-swift.conf"
        test_dir = self.useFixture(fixtures.TempDir()).path
        self.swift_config_file = self.copy_data_file(conf_file, test_dir)
        self.config(group="swift1", swift_store_container='container',
                    default_swift_reference='ref2',
                    swift_store_config_file=self.swift_config_file)

        store = swift.SingleTenantStore(self.conf, backend="swift1")
        store.configure()
        location = store.create_location('image-id')
        self.assertEqual('swift+http', location.scheme)
        self.assertEqual('http://example.com', location.swift_url) 
Example #20
Source File: test_baseline.py    From bandit with Apache License 2.0 5 votes vote down vote up
def test_initialize_with_output_argument(self):
        # Test that bandit does not run when the '-o' (output) argument is
        # specified
        repo_directory = self.useFixture(fixtures.TempDir()).path
        git_repo = git.Repo.init(repo_directory)
        git_repo.index.commit('Initial Commit')
        os.chdir(repo_directory)

        return_value = baseline.initialize()

        # assert bandit did not run due to provided -o (--ouput) argument
        self.assertEqual((None, None, None), return_value) 
Example #21
Source File: test_main.py    From bandit with Apache License 2.0 5 votes vote down vote up
def test_get_options_from_ini_empty_directory_no_target(self):
        # Test that no config options are loaded when an empty directory is
        # provided as the ini path and no target directory is provided
        ini_directory = self.useFixture(fixtures.TempDir()).path
        self.assertIsNone(bandit._get_options_from_ini(ini_directory, [])) 
Example #22
Source File: test_main.py    From bandit with Apache License 2.0 5 votes vote down vote up
def test_get_options_from_ini_no_ini_path_no_bandit_files(self):
        # Test that no config options are loaded when no ini path is provided
        # and the target directory contains no bandit config files (.bandit)
        target_directory = self.useFixture(fixtures.TempDir()).path
        self.assertIsNone(bandit._get_options_from_ini(None,
                          [target_directory])) 
Example #23
Source File: test_swift_store_multibackend.py    From glance_store with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        super(TestMultiTenantStoreConnections, self).setUp()
        enabled_backends = {
            "swift1": "swift",
            "swift2": "swift",
        }
        self.conf = self._CONF
        self.conf(args=[])
        self.conf.register_opt(cfg.DictOpt('enabled_backends'))
        self.config(enabled_backends=enabled_backends)
        store.register_store_opts(self.conf)
        self.config(default_backend='swift1', group='glance_store')

        # Ensure stores + locations cleared
        location.SCHEME_TO_CLS_BACKEND_MAP = {}

        store.create_multi_stores(self.conf)
        self.addCleanup(setattr, location, 'SCHEME_TO_CLS_BACKEND_MAP',
                        dict())
        self.test_dir = self.useFixture(fixtures.TempDir()).path

        self.useFixture(fixtures.MockPatch(
            'swiftclient.Connection', FakeConnection))
        self.context = mock.MagicMock(
            user='tenant:user1', tenant='tenant', auth_token='0123')
        self.store = swift.MultiTenantStore(self.conf, backend="swift1")
        specs = {'scheme': 'swift',
                 'auth_or_store_url': 'example.com',
                 'container': 'cont',
                 'obj': 'object'}
        self.location = swift.StoreLocation(specs, self.conf,
                                            backend_group="swift1")
        self.addCleanup(self.conf.reset) 
Example #24
Source File: test_swift_store_multibackend.py    From glance_store with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        """Establish a clean test environment."""
        super(TestStoreAuthV1, self).setUp()
        enabled_backends = {
            "swift1": "swift",
            "swift2": "swift",
        }
        self.conf = self._CONF
        self.conf(args=[])
        self.conf.register_opt(cfg.DictOpt('enabled_backends'))
        self.config(enabled_backends=enabled_backends)
        store.register_store_opts(self.conf)
        self.config(default_backend='swift1', group='glance_store')

        # Ensure stores + locations cleared
        location.SCHEME_TO_CLS_BACKEND_MAP = {}

        store.create_multi_stores(self.conf)
        self.addCleanup(setattr, location, 'SCHEME_TO_CLS_BACKEND_MAP',
                        dict())
        self.test_dir = self.useFixture(fixtures.TempDir()).path

        config = self.getConfig()

        conf_file = 'glance-swift.conf'
        self.swift_config_file = self.copy_data_file(conf_file, self.test_dir)
        config.update({'swift_store_config_file': self.swift_config_file})

        self.stub_out_swiftclient(config['swift_store_auth_version'])
        self.mock_keystone_client()
        self.store = Store(self.conf, backend="swift1")
        self.config(group="swift1", **config)
        self.store.configure()

        self.register_store_backend_schemes(self.store, 'swift', 'swift1')
        self.addCleanup(self.conf.reset) 
Example #25
Source File: test_swift_store_utils.py    From glance_store with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        super(TestSwiftParams, self).setUp()
        conf_file = "glance-swift.conf"
        test_dir = self.useFixture(fixtures.TempDir()).path
        self.swift_config_file = self.copy_data_file(conf_file, test_dir)
        self.config(swift_store_config_file=self.swift_config_file) 
Example #26
Source File: test_endpoint.py    From txacme with MIT License 5 votes vote down vote up
def test_create_key(self):
        """
        `~txacme.endpoint.load_or_create_client_key` creates a new key if one
        does not exist.
        """
        tempdir = self.useFixture(TempDir()).path
        temp_path = FilePath(tempdir)
        key_path = temp_path.child('client.key')
        self.assertThat(key_path.isfile(), Equals(False))
        self.assertThat(
            load_or_create_client_key(temp_path),
            Equals(JWKRSA(key=load_pem_private_key(
                    key_path.getContent(),
                    password=None,
                    backend=default_backend())))) 
Example #27
Source File: test_multistore_filesystem.py    From glance_store with Apache License 2.0 5 votes vote down vote up
def test_configure_add_with_file_perm(self):
        """Tests adding with permissions.

        Tests filesystem specified by filesystem_store_file_perm
        are parsed correctly.
        """
        store = self.useFixture(fixtures.TempDir()).path
        self.conf.set_override('filesystem_store_datadir', store,
                               group='file1')
        self.conf.set_override('filesystem_store_file_perm', 700,  # -rwx------
                               group='file1')
        self.store.configure_add()
        self.assertEqual(self.store.datadir, store) 
Example #28
Source File: test_multistore_filesystem.py    From glance_store with Apache License 2.0 5 votes vote down vote up
def test_add_with_multiple_dirs_storage_full(self):
        """Tests adding dirs with storage full.

        Test StorageFull exception is raised if no filesystem directory
        is found that can store an image.
        """
        store_map = [self.useFixture(fixtures.TempDir()).path,
                     self.useFixture(fixtures.TempDir()).path]
        self.conf.set_override('filesystem_store_datadir',
                               override=None,
                               group='file1')
        self.conf.set_override('filesystem_store_datadirs',
                               [store_map[0] + ":100",
                                store_map[1] + ":200"],
                               group='file1')

        self.store.configure_add()

        def fake_get_capacity_info(mount_point):
            return 0

        with mock.patch.object(self.store, '_get_capacity_info') as capacity:
            capacity.return_value = 0

            filesystem.ChunkedFile.CHUNKSIZE = units.Ki
            expected_image_id = str(uuid.uuid4())
            expected_file_size = 5 * units.Ki  # 5K
            expected_file_contents = b"*" * expected_file_size
            image_file = six.BytesIO(expected_file_contents)

            self.assertRaises(exceptions.StorageFull, self.store.add,
                              expected_image_id, image_file,
                              expected_file_size) 
Example #29
Source File: test_multistore_filesystem.py    From glance_store with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        """Establish a clean test environment."""
        super(TestMultiStore, self).setUp()
        self.enabled_backends = {
            "file1": "file",
            "file2": "file",
        }
        self.conf = self._CONF
        self.conf(args=[])
        self.conf.register_opt(cfg.DictOpt('enabled_backends'))
        self.config(enabled_backends=self.enabled_backends)
        store.register_store_opts(self.conf)
        self.config(default_backend='file1', group='glance_store')

        # Ensure stores + locations cleared
        location.SCHEME_TO_CLS_BACKEND_MAP = {}
        store.create_multi_stores(self.conf)

        self.addCleanup(setattr, location, 'SCHEME_TO_CLS_BACKEND_MAP',
                        dict())
        self.test_dir = self.useFixture(fixtures.TempDir()).path
        self.addCleanup(self.conf.reset)

        self.store = filesystem.Store(self.conf, backend='file1')
        self.config(filesystem_store_datadir=self.test_dir,
                    filesystem_store_chunk_size=10,
                    group="file1")
        self.store.configure()
        self.register_store_backend_schemes(self.store, 'file', 'file1') 
Example #30
Source File: test_filesystem_store.py    From glance_store with Apache License 2.0 5 votes vote down vote up
def test_add_with_file_perm_for_owner_users_access(self):
        """
        Test that we can add an image via the filesystem backend with a
        required image file permission.
        """
        store = self.useFixture(fixtures.TempDir()).path
        self.conf.set_override('filesystem_store_datadir', store,
                               group='glance_store')
        self.conf.set_override('filesystem_store_file_perm', 600,  # -rw-------
                               group='glance_store')

        # -rwx------
        os.chmod(store, 0o700)
        self.assertEqual(0o700, stat.S_IMODE(os.stat(store)[stat.ST_MODE]))

        self.store.configure_add()

        filesystem.Store.WRITE_CHUNKSIZE = units.Ki
        expected_image_id = str(uuid.uuid4())
        expected_file_size = 5 * units.Ki  # 5K
        expected_file_contents = b"*" * expected_file_size
        expected_checksum = hashlib.md5(expected_file_contents).hexdigest()
        expected_multihash = hashlib.sha256(expected_file_contents).hexdigest()
        expected_location = "file://%s/%s" % (store,
                                              expected_image_id)
        image_file = six.BytesIO(expected_file_contents)

        location, size, checksum, multihash, _ = self.store.add(
            expected_image_id, image_file, expected_file_size, self.hash_algo)

        self.assertEqual(expected_location, location)
        self.assertEqual(expected_file_size, size)
        self.assertEqual(expected_checksum, checksum)
        self.assertEqual(expected_multihash, multihash)

        # -rwx------ for store directory
        self.assertEqual(0o700, stat.S_IMODE(os.stat(store)[stat.ST_MODE]))
        # -rw------- for image file
        mode = os.stat(expected_location[len('file:/'):])[stat.ST_MODE]
        perm = int(str(self.conf.glance_store.filesystem_store_file_perm), 8)
        self.assertEqual(perm, stat.S_IMODE(mode))