Python pyfakefs.fake_filesystem.FakeFilesystem() Examples

The following are 30 code examples of pyfakefs.fake_filesystem.FakeFilesystem(). 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 pyfakefs.fake_filesystem , or try the search function .
Example #1
Source File: deploy_impl_test.py    From loaner with Apache License 2.0 7 votes vote down vote up
def setUp(self):
    super(DeployImplTest, self).setUp()
    # Save the real modules for clean up.
    self.real_open = builtins.open
    # Create a fake file system and stub out builtin modules.
    self.fs = fake_filesystem.FakeFilesystem()
    self.os = fake_filesystem.FakeOsModule(self.fs)
    self.open = fake_filesystem.FakeFileOpen(self.fs)
    self.shutil = fake_filesystem_shutil.FakeShutilModule(self.fs)
    self.stubs = mox3_stubout.StubOutForTesting()
    self.stubs.SmartSet(builtins, 'open', self.open)
    self.stubs.SmartSet(deploy_impl, 'os', self.os)
    self.stubs.SmartSet(deploy_impl, 'shutil', self.shutil)
    # Populate the fake file system with the expected directories and files.
    self.fs.CreateDirectory('/this/is/a/workspace/loaner/web_app/frontend/dist')
    self.fs.CreateDirectory('/this/is/a/workspace/loaner/chrome_app/dist')
    self.fs.CreateFile('/this/is/a/workspace/loaner/web_app/app.yaml')
    self.fs.CreateFile('/this/is/a/workspace/loaner/web_app/endpoints.yaml') 
Example #2
Source File: test_deploy_script.py    From raiden-contracts with MIT License 6 votes vote down vote up
def test_store_and_verify_services(
    fs_reload_deployer: FakeFilesystem,
    deployer: ContractDeployer,
    deployed_service_info: DeployedContracts,
    token_address: HexAddress,
    token_network_registry_contract: Contract,
) -> None:
    """ Store some service contract deployment information and verify them """
    fs_reload_deployer.add_real_directory(
        contracts_precompiled_path(version=None).parent, read_only=False
    )
    deployed_contracts_info = deployed_service_info
    deployer.verify_service_contracts_deployment_data(
        token_address=token_address,
        deployed_contracts_info=deployed_contracts_info,
        user_deposit_whole_balance_limit=DEPOSIT_LIMIT,
        token_network_registry_address=token_network_registry_contract.address,
    )
    deployer.store_and_verify_deployment_info_services(
        token_address=token_address,
        deployed_contracts_info=deployed_contracts_info,
        user_deposit_whole_balance_limit=DEPOSIT_LIMIT,
        token_network_registry_address=token_network_registry_contract.address,
    ) 
Example #3
Source File: test_deploy_script.py    From raiden-contracts with MIT License 6 votes vote down vote up
def test_store_and_verify_raiden(
    fs_reload_deployer: FakeFilesystem,
    deployed_raiden_info: DeployedContracts,
    deployer: ContractDeployer,
) -> None:
    """ Store some raiden contract deployment information and verify them """
    fs_reload_deployer.add_real_directory(
        contracts_precompiled_path(version=None).parent, read_only=False
    )
    deployed_contracts_info = deployed_raiden_info
    deployer.store_and_verify_deployment_info_raiden(
        deployed_contracts_info=deployed_contracts_info
    )
    deployer.store_and_verify_deployment_info_raiden(
        deployed_contracts_info=deployed_contracts_info
    ) 
Example #4
Source File: utils.py    From ara-archive with GNU General Public License v3.0 6 votes vote down vote up
def playbook_treeview(playbook):
    """
    Creates a fake filesystem with playbook files and uses generate_tree() to
    recurse and return a JSON structure suitable for bootstrap-treeview.
    """
    fs = fake_filesystem.FakeFilesystem()
    mock_os = fake_filesystem.FakeOsModule(fs)

    files = models.File.query.filter(models.File.playbook_id.in_([playbook]))

    paths = {}
    for file in files:
        fs.CreateFile(file.path)
        paths[file.path] = file.id

    return jsonutils.dumps(generate_tree('/', paths, mock_os),
                           sort_keys=True,
                           indent=2) 
Example #5
Source File: config_model_test.py    From loaner with Apache License 2.0 6 votes vote down vote up
def setUp(self):
    super(ConfigurationTest, self).setUp()
    # Save the real modules for clean up.
    self.real_open = __builtin__.open
    self.real_file = __builtin__.file
    self.fs = fake_filesystem.FakeFilesystem()
    self.os = fake_filesystem.FakeOsModule(self.fs)
    self.open = fake_filesystem.FakeFileOpen(self.fs)
    self.stubs = mox3_stubout.StubOutForTesting()
    self.stubs.SmartSet(__builtin__, 'open', self.open)
    self.stubs.SmartSet(os, 'path', self.os.path)

    config_file = constants.CONFIG_DEFAULTS_PATH
    self.fs.CreateFile(config_file, contents=_config_defaults_yaml)

    config_model.Config(id='string_config', string_value='config value 1').put()
    config_model.Config(id='integer_config', integer_value=1).put()
    config_model.Config(id='bool_config', bool_value=True).put()
    config_model.Config(id='list_config', list_value=['email1', 'email2']).put() 
Example #6
Source File: auth_test.py    From loaner with Apache License 2.0 6 votes vote down vote up
def setUp(self):
    super(AuthTest, self).setUp()
    self._test_project = 'test_project'
    self._test_client_id = 'test_client_id'
    self._test_client_secret = 'test_client_secret'
    self._test_config = common.ProjectConfig(
        'test_key', self._test_project, self._test_client_id,
        self._test_client_secret, None, '/test/path.yaml')
    # Save the real modules for clean up.
    self.real_open = builtins.open
    # Create a fake file system and stub out builtin modules.
    self.fs = fake_filesystem.FakeFilesystem()
    self.os = fake_filesystem.FakeOsModule(self.fs)
    self.open = fake_filesystem.FakeFileOpen(self.fs)
    self.stubs = mox3_stubout.StubOutForTesting()
    self.stubs.SmartSet(builtins, 'open', self.open)
    self.stubs.SmartSet(auth, 'os', self.os) 
Example #7
Source File: installer_test.py    From glazier with Apache License 2.0 6 votes vote down vote up
def testBuildInfoSave(self, build_info, sv):
    fs = fake_filesystem.FakeFilesystem()
    installer.open = fake_filesystem.FakeFileOpen(fs)
    installer.os = fake_filesystem.FakeOsModule(fs)
    timer_root = r'{0}\{1}'.format(installer.constants.REG_ROOT, 'Timers')
    fs.CreateFile(
        '{}/build_info.yaml'.format(installer.constants.SYS_CACHE),
        contents='{BUILD: {opt 1: true, TIMER_opt 2: some value, opt 3: 12345}}\n'
    )
    s = installer.BuildInfoSave(None, build_info)
    s.Run()
    sv.assert_has_calls([
        mock.call('opt 1', True, 'HKLM', installer.constants.REG_ROOT),
        mock.call('TIMER_opt 2', 'some value', 'HKLM', timer_root),
        mock.call('opt 3', 12345, 'HKLM', installer.constants.REG_ROOT),
    ], any_order=True)
    s.Run() 
Example #8
Source File: gng_impl_test.py    From loaner with Apache License 2.0 5 votes vote down vote up
def setUp(self):
    super(ManagerTest, self).setUp()
    # Save the real modules for clean up.
    self.real_open = builtins.open
    # Create a fake file system and stub out builtin modules.
    self.fs = fake_filesystem.FakeFilesystem()
    self.os = fake_filesystem.FakeOsModule(self.fs)
    self.open = fake_filesystem.FakeFileOpen(self.fs)
    self.stdout = StringIO()
    self.stubs = mox3_stubout.StubOutForTesting()
    self.stubs.SmartSet(builtins, 'open', self.open)
    self.stubs.SmartSet(common, 'os', self.os)
    self.stubs.SmartSet(sys, 'stdout', self.stdout)

    # Setup Testdata.
    self._testdata_path = '/testdata'
    self._valid_config_path = self._testdata_path + '/valid_config.yaml'
    self._blank_config_path = self._testdata_path + '/blank_config.yaml'

    self.fs.CreateFile(self._valid_config_path, contents=_VALID_CONFIG)
    self.fs.CreateFile(self._blank_config_path, contents=_BLANK_CONFIG)

    # Load the default config.
    self._valid_default_config = common.ProjectConfig.from_yaml(
        common.DEFAULT, self._valid_config_path)

    # Create test constants.
    self._constants = {
        'test': app_constants.Constant(
            'test', 'message', '',
            parser=utils.StringParser(allow_empty_string=False),),
        'other': app_constants.Constant('other', 'other message', 'value'),
    }

    # Mock out the authentication credentials.
    self.auth_patcher = mock.patch.object(auth, 'CloudCredentials')
    self.mock_creds = self.auth_patcher.start()
    self.mock_creds.return_value.get_credentials.return_value = (
        credentials.AnonymousCredentials()) 
Example #9
Source File: chooser_test.py    From glazier with Apache License 2.0 5 votes vote down vote up
def setUp(self, tk):
    super(ChooserTest, self).setUp()
    self.ui = chooser.Chooser(_TEST_CONF, preload=False)
    self.tk = tk
    v1 = mock.Mock()
    v1.Value.return_value = 'value1'
    v2 = mock.Mock()
    v2.Value.return_value = 'value2'
    v3 = mock.Mock()
    v3.Value.return_value = 'value3'
    self.ui.fields = {'field1': v1, 'field2': v2, 'field3': v3}

    self.fs = fake_filesystem.FakeFilesystem()
    chooser.resources.os = fake_filesystem.FakeOsModule(self.fs)
    self.fs.CreateFile('/resources/logo.gif') 
Example #10
Source File: file_util_test.py    From glazier with Apache License 2.0 5 votes vote down vote up
def setUp(self):
    super(FileUtilTest, self).setUp()
    self.filesystem = fake_filesystem.FakeFilesystem()
    file_util.os = fake_filesystem.FakeOsModule(self.filesystem)
    file_util.open = fake_filesystem.FakeFileOpen(self.filesystem) 
Example #11
Source File: test_deploy_script.py    From raiden-contracts with MIT License 5 votes vote down vote up
def fs_reload_deployer() -> Generator[FakeFilesystem, None, None]:
    patcher = Patcher(
        modules_to_reload=[raiden_contracts.contract_manager, raiden_contracts.deploy.__main__]
    )
    patcher.setUp()
    yield patcher.fs
    patcher.tearDown() 
Example #12
Source File: common_test.py    From googleads-python-lib with Apache License 2.0 5 votes vote down vote up
def setUp(self):
    self.filesystem = fake_filesystem.FakeFilesystem()
    self.tempfile = fake_tempfile.FakeTempfileModule(self.filesystem)
    self.fake_open = fake_filesystem.FakeFileOpen(self.filesystem)
    self.uri1 = 'http://h1:1'
    self.uri1_w_creds = 'http://username:password@h1:1'
    self.uri2 = 'http://h2:2'
    self.uplink_uri = 'http://127.0.0.1:999'
    self.test1_name = 'Test1'
    self.test2_name = 'Test2'
    self.test2_version = 'testing'
    self.fake_version = 'ignored'
    locale_patcher = mock.patch('googleads.common.locale.getdefaultlocale',
                                return_value=('en_us', 'UTF-8'))
    self.locale_patcher = locale_patcher.start()

    @googleads.common.RegisterUtility(self.test1_name)
    class Test1(object):

      def test(self):
        pass

    @googleads.common.RegisterUtility(self.test2_name,
                                      {'test': self.test2_version})
    class Test2(object):

      def test(self):
        pass

    self.test1 = Test1
    self.test2 = Test2 
Example #13
Source File: conftest.py    From torchvideo with Mozilla Public License 2.0 5 votes vote down vote up
def dataset_dir(fs: FakeFilesystem):
    path = "/tmp/dataset"
    fs.create_dir(path)
    return path 
Example #14
Source File: base_config_unittest.py    From Jandroid with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def testIterDependenciesStaleGlob(self, open_mock, exists_mock, json_mock):
    json_mock.load.return_value = self.one_dep_dict
    config = self.config_class('file_path')

    abspath = os.path.abspath
    should_match = set(map(abspath, [
        'dep_all_the_variables_0123456789abcdef0123456789abcdef01234567',
        'dep_all_the_variables_123456789abcdef0123456789abcdef012345678']))
    # Not testing case changes, because Windows is case-insensitive.
    should_not_match = set(map(abspath, [
        # A configuration that doesn't unzip shouldn't clear any stale unzips.
        'dep_plat1_arch1_0123456789abcdef0123456789abcdef01234567',
        # "Hash" component less than 40 characters (not a valid SHA1 hash).
        'dep_all_the_variables_0123456789abcdef0123456789abcdef0123456',
        # "Hash" component greater than 40 characters (not a valid SHA1 hash).
        'dep_all_the_variables_0123456789abcdef0123456789abcdef012345678',
        # "Hash" component not comprised of hex (not a valid SHA1 hash).
        'dep_all_the_variables_0123456789gggggg0123456789gggggg01234567']))

    # Create a fake filesystem just for glob to use
    fake_fs = fake_filesystem.FakeFilesystem()
    fake_glob = fake_filesystem_glob.FakeGlobModule(fake_fs)
    for stale_dir in set.union(should_match, should_not_match):
      fake_fs.CreateDirectory(stale_dir)
      fake_fs.CreateFile(os.path.join(stale_dir, 'some_file'))

    for dep_info in config.IterDependencyInfo():
      if dep_info.platform == 'all_the_variables':
        cs_info = dep_info.cloud_storage_info
        actual_glob = cs_info._archive_info._stale_unzip_path_glob
        actual_matches = set(fake_glob.glob(actual_glob))
        self.assertItemsEqual(should_match, actual_matches) 
Example #15
Source File: base_config_unittest.py    From Jandroid with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def testIterDependenciesStaleGlob(self, open_mock, exists_mock, json_mock):
    json_mock.load.return_value = self.one_dep_dict
    config = self.config_class('file_path')

    abspath = os.path.abspath
    should_match = set(map(abspath, [
        'dep_all_the_variables_0123456789abcdef0123456789abcdef01234567',
        'dep_all_the_variables_123456789abcdef0123456789abcdef012345678']))
    # Not testing case changes, because Windows is case-insensitive.
    should_not_match = set(map(abspath, [
        # A configuration that doesn't unzip shouldn't clear any stale unzips.
        'dep_plat1_arch1_0123456789abcdef0123456789abcdef01234567',
        # "Hash" component less than 40 characters (not a valid SHA1 hash).
        'dep_all_the_variables_0123456789abcdef0123456789abcdef0123456',
        # "Hash" component greater than 40 characters (not a valid SHA1 hash).
        'dep_all_the_variables_0123456789abcdef0123456789abcdef012345678',
        # "Hash" component not comprised of hex (not a valid SHA1 hash).
        'dep_all_the_variables_0123456789gggggg0123456789gggggg01234567']))

    # Create a fake filesystem just for glob to use
    fake_fs = fake_filesystem.FakeFilesystem()
    fake_glob = fake_filesystem_glob.FakeGlobModule(fake_fs)
    for stale_dir in set.union(should_match, should_not_match):
      fake_fs.CreateDirectory(stale_dir)
      fake_fs.CreateFile(os.path.join(stale_dir, 'some_file'))

    for dep_info in config.IterDependencyInfo():
      if dep_info.platform == 'all_the_variables':
        cs_info = dep_info.cloud_storage_info
        actual_glob = cs_info._archive_info._stale_unzip_path_glob
        actual_matches = set(fake_glob.glob(actual_glob))
        self.assertItemsEqual(should_match, actual_matches) 
Example #16
Source File: base_config_unittest.py    From Jandroid with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def testIterDependenciesStaleGlob(self, open_mock, exists_mock, json_mock):
    json_mock.load.return_value = self.one_dep_dict
    config = self.config_class('file_path')

    abspath = os.path.abspath
    should_match = set(map(abspath, [
        'dep_all_the_variables_0123456789abcdef0123456789abcdef01234567',
        'dep_all_the_variables_123456789abcdef0123456789abcdef012345678']))
    # Not testing case changes, because Windows is case-insensitive.
    should_not_match = set(map(abspath, [
        # A configuration that doesn't unzip shouldn't clear any stale unzips.
        'dep_plat1_arch1_0123456789abcdef0123456789abcdef01234567',
        # "Hash" component less than 40 characters (not a valid SHA1 hash).
        'dep_all_the_variables_0123456789abcdef0123456789abcdef0123456',
        # "Hash" component greater than 40 characters (not a valid SHA1 hash).
        'dep_all_the_variables_0123456789abcdef0123456789abcdef012345678',
        # "Hash" component not comprised of hex (not a valid SHA1 hash).
        'dep_all_the_variables_0123456789gggggg0123456789gggggg01234567']))

    # Create a fake filesystem just for glob to use
    fake_fs = fake_filesystem.FakeFilesystem()
    fake_glob = fake_filesystem_glob.FakeGlobModule(fake_fs)
    for stale_dir in set.union(should_match, should_not_match):
      fake_fs.CreateDirectory(stale_dir)
      fake_fs.CreateFile(os.path.join(stale_dir, 'some_file'))

    for dep_info in config.IterDependencyInfo():
      if dep_info.platform == 'all_the_variables':
        cs_info = dep_info.cloud_storage_info
        actual_glob = cs_info._archive_info._stale_unzip_path_glob
        actual_matches = set(fake_glob.glob(actual_glob))
        self.assertItemsEqual(should_match, actual_matches) 
Example #17
Source File: powershell_test.py    From glazier with Apache License 2.0 5 votes vote down vote up
def setUp(self):
    super(PowershellTest, self).setUp()
    self.fs = fake_filesystem.FakeFilesystem()
    powershell.os = fake_filesystem.FakeOsModule(self.fs)
    powershell.resources.os = fake_filesystem.FakeOsModule(self.fs)
    self.path = '/resources/bin/script.ps1'
    self.fs.CreateFile(self.path)
    self.ps = powershell.PowerShell() 
Example #18
Source File: identifier_test.py    From glazier with Apache License 2.0 5 votes vote down vote up
def setUp(self):
    super(IdentifierTest, self).setUp()
    mock_wmi = mock.patch.object(
        identifier.hw_info.wmi_query, 'WMIQuery', autospec=True)
    self.addCleanup(mock_wmi.stop)
    mock_wmi.start()
    self.fs = fake_filesystem.FakeFilesystem()
    identifier.open = fake_filesystem.FakeFileOpen(self.fs)
    identifier.os = fake_filesystem.FakeOsModule(self.fs) 
Example #19
Source File: beyondcorp_test.py    From glazier with Apache License 2.0 5 votes vote down vote up
def setUp(self):
    super(BeyondcorpTest, self).setUp()
    self.__saved_flags = flagsaver.save_flag_values()
    mock_wmi = mock.patch.object(
        beyondcorp.hw_info.wmi_query, 'WMIQuery', autospec=True)
    self.addCleanup(mock_wmi.stop)
    mock_wmi.start()
    self.filesystem = fake_filesystem.FakeFilesystem()
    self.filesystem.CreateFile(r'C:\seed.json', contents=_TEST_SEED)
    self.filesystem.CreateFile(beyondcorp.constants.USB_WIM, contents=_TEST_WIM)
    beyondcorp.os = fake_filesystem.FakeOsModule(self.filesystem)
    beyondcorp.open = fake_filesystem.FakeFileOpen(self.filesystem)
    self.beyondcorp = beyondcorp.BeyondCorp() 
Example #20
Source File: common_test.py    From loaner with Apache License 2.0 5 votes vote down vote up
def setUp(self):
    super(CommonTest, self).setUp()
    # Save the real modules for clean up.
    self.real_open = builtins.open
    # Create a fake file system and stub out builtin modules.
    self.fs = fake_filesystem.FakeFilesystem()
    self.os = fake_filesystem.FakeOsModule(self.fs)
    self.open = fake_filesystem.FakeFileOpen(self.fs)
    self.stubs = mox3_stubout.StubOutForTesting()
    self.stubs.SmartSet(builtins, 'open', self.open)
    self.stubs.SmartSet(common, 'os', self.os) 
Example #21
Source File: files_test.py    From glazier with Apache License 2.0 5 votes vote down vote up
def setUp(self):
    super(FilesTest, self).setUp()
    self.filesystem = fake_filesystem.FakeFilesystem()
    files.open = fake_filesystem.FakeFileOpen(self.filesystem)
    files.file_util.shutil = fake_filesystem_shutil.FakeShutilModule(
        self.filesystem)
    files.WindowsError = Exception

  # TODO: Split into separate tests. 
Example #22
Source File: autobuild_test.py    From glazier with Apache License 2.0 5 votes vote down vote up
def setUp(self, logs):
    super(BuildInfoTest, self).setUp()
    self.autobuild = autobuild.AutoBuild()
    autobuild.logging = logs.logging
    autobuild.logging.fatal.side_effect = LogFatalError()
    self.filesystem = fake_filesystem.FakeFilesystem()
    autobuild.os = fake_filesystem.FakeOsModule(self.filesystem) 
Example #23
Source File: buildinfo_test.py    From glazier with Apache License 2.0 5 votes vote down vote up
def setUp(self):
    super(BuildInfoTest, self).setUp()
    # fake filesystem
    self.filesystem = fake_filesystem.FakeFilesystem()
    self.filesystem.CreateDirectory('/dev')
    buildinfo.os = fake_filesystem.FakeOsModule(self.filesystem)
    buildinfo.open = fake_filesystem.FakeFileOpen(self.filesystem)
    # setup
    mock_wmi = mock.patch.object(
        buildinfo.hw_info.wmi_query, 'WMIQuery', autospec=True)
    self.addCleanup(mock_wmi.stop)
    mock_wmi.start()
    self.buildinfo = buildinfo.BuildInfo() 
Example #24
Source File: runner_test.py    From glazier with Apache License 2.0 5 votes vote down vote up
def setUp(self):
    super(ConfigRunnerTest, self).setUp()
    self.buildinfo = buildinfo.BuildInfo()
    constants.FLAGS.verify_urls = None
    # filesystem
    self.filesystem = fake_filesystem.FakeFilesystem()
    runner.os = fake_filesystem.FakeOsModule(self.filesystem)
    runner.open = fake_filesystem.FakeFileOpen(self.filesystem)
    runner.shutil = fake_filesystem_shutil.FakeShutilModule(self.filesystem)
    self.cr = runner.ConfigRunner(self.buildinfo)
    self.cr._task_list_path = '/tmp/task_list.yaml' 
Example #25
Source File: files_test.py    From glazier with Apache License 2.0 5 votes vote down vote up
def setUp(self):
    super(FilesTest, self).setUp()
    self.filesystem = fake_filesystem.FakeFilesystem()
    files.open = fake_filesystem.FakeFileOpen(self.filesystem)
    files.file_util.os = fake_filesystem.FakeOsModule(self.filesystem) 
Example #26
Source File: resources_test.py    From glazier with Apache License 2.0 5 votes vote down vote up
def setUp(self):
    super(ResourcesTest, self).setUp()
    self.fs = fake_filesystem.FakeFilesystem()
    resources.os = fake_filesystem.FakeOsModule(self.fs)
    self.fs.CreateFile('/test/file.txt')
    self.fs.CreateFile('/test2/resources/file.txt') 
Example #27
Source File: cache_test.py    From glazier with Apache License 2.0 5 votes vote down vote up
def setUp(self):
    super(CacheTest, self).setUp()
    self.cache = cache.Cache()
    fs = fake_filesystem.FakeFilesystem()
    fs.CreateDirectory(r'C:\Directory')
    os_module = fake_filesystem.FakeOsModule(fs)
    self.mock_open = fake_filesystem.FakeFileOpen(fs)
    cache.os = os_module
    cache.open = self.mock_open 
Example #28
Source File: execute_test.py    From glazier with Apache License 2.0 5 votes vote down vote up
def setUp(self):
    super(ExecuteTest, self).setUp()
    self.fs = fake_filesystem.FakeFilesystem()
    execute.os = fake_filesystem.FakeOsModule(self.fs)
    execute.open = fake_filesystem.FakeFileOpen(self.fs)
    self.binary = r'C:\foo.exe'
    self.fs.CreateFile(self.binary) 
Example #29
Source File: sysprep_test.py    From glazier with Apache License 2.0 5 votes vote down vote up
def setUp(self):
    super(SysprepTest, self).setUp()
    fs = fake_filesystem.FakeFilesystem()
    fs.CreateDirectory('/windows/panther')
    fs.CreateFile('/windows/panther/unattend.xml', contents=UNATTEND_XML)
    self.fake_open = fake_filesystem.FakeFileOpen(fs)
    sysprep.os = fake_filesystem.FakeOsModule(fs)
    sysprep.open = self.fake_open 
Example #30
Source File: oauth2_test.py    From googleads-python-lib with Apache License 2.0 4 votes vote down vote up
def setUp(self):
    self.scope = 'scope'
    self.private_key = b'IT\'S A SECRET TO EVERYBODY.'
    self.delegated_account = 'delegated_account@delegated.com'

    # Mock out filesystem and file for testing.
    filesystem = fake_filesystem.FakeFilesystem()
    tempfile = fake_tempfile.FakeTempfileModule(filesystem)
    self.fake_open = fake_filesystem.FakeFileOpen(filesystem)
    self.key_file_path = tempfile.NamedTemporaryFile(delete=False).name
    self.cert_file_path = tempfile.NamedTemporaryFile(
        delete=False, prefix='cert_', suffix='.pem').name

    with self.fake_open(self.key_file_path, 'wb') as file_handle:
      file_handle.write(self.private_key)

    self.access_token_unrefreshed = 'a'
    self.access_token_refreshed = 'b'

    # Mock out google.auth.transport.Request for testing.
    self.mock_req = mock.Mock(spec=Request)
    self.mock_req.return_value = mock.Mock()
    self.mock_req_instance = self.mock_req.return_value

    # Mock out service account credentials for testing.
    self.mock_credentials = mock.Mock()
    self.mock_credentials.from_service_account_file.return_value = mock.Mock()
    self.mock_credentials_instance = (
        self.mock_credentials.from_service_account_file.return_value
    )
    self.mock_credentials_instance.token = 'x'
    self.mock_credentials_instance.expiry = datetime.datetime(
        1980, 1, 1, 12)
    self.mock_credentials_instance.expired = True

    def apply(headers, token=None):
      headers['authorization'] = ('Bearer %s'
                                  % self.mock_credentials_instance.token)

    def refresh(request):
      self.mock_credentials_instance.token = (
          self.access_token_unrefreshed if
          self.mock_credentials_instance.token is 'x'
          else self.access_token_refreshed)
      self.mock_credentials_instance.token_expiry = datetime.datetime.utcnow()

    self.mock_credentials_instance.apply = mock.Mock(side_effect=apply)
    self.mock_credentials_instance.refresh = mock.Mock(side_effect=refresh)
    with mock.patch('builtins.open', self.fake_open):
      with mock.patch('google.oauth2.service_account.Credentials',
                      self.mock_credentials):
        self.sa_client = googleads.oauth2.GoogleServiceAccountClient(
            self.key_file_path, self.scope)
      # Undo the call count for the auto-refresh
      self.mock_credentials_instance.refresh.reset_mock()