Python six.moves.builtins.open() Examples

The following are 21 code examples of six.moves.builtins.open(). 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 six.moves.builtins , 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: mount_base.py    From stash with MIT License 6 votes vote down vote up
def open(patch, name, mode="r", buffering=0):
    """
	Open a file, returning an object of the file type described in section
	File Objects.
	If the file cannot be opened, IOError is raised.
	When opening a file, its preferable to use open() instead of invoking
	the file constructor directly.
	"""
    path = os.path.abspath(os.path.join(os.getcwd(), name))
    manager = get_manager()
    fsi, relpath, readonly = manager.get_fsi(path)
    if fsi is None:
        return _org_open(relpath, mode, buffering)
    elif (("w" in mode) or ("a" in mode) or ("+" in mode)) and readonly:
        raise IOError("[Errno 1] Operation not permitted: '{p}'".format(p=path))
    else:
        try:
            return fsi.open(relpath, mode, buffering)
        except OperationFailure:
            raise os.error("[Errno 2] No such file or directory: '{p}'".format(p=path)) 
Example #3
Source File: deploy_impl_test.py    From loaner with Apache License 2.0 5 votes vote down vote up
def tearDown(self):
    super(DeployImplTest, self).tearDown()
    self.stubs.UnsetAll()
    builtins.open = self.real_open 
Example #4
Source File: pathutils.py    From os-win with Apache License 2.0 5 votes vote down vote up
def get_file_id(self, path):
        """Return a dict containing the file id and volume id."""
        handle = None
        info = kernel32_def.FILE_ID_INFO()

        try:
            handle = self._io_utils.open(
                path,
                desired_access=0,
                share_mode=(w_const.FILE_SHARE_READ |
                            w_const.FILE_SHARE_WRITE |
                            w_const.FILE_SHARE_DELETE),
                creation_disposition=w_const.OPEN_EXISTING)
            self._win32_utils.run_and_check_output(
                kernel32.GetFileInformationByHandleEx,
                handle,
                w_const.FileIdInfo,
                ctypes.byref(info),
                ctypes.sizeof(info),
                kernel32_lib_func=True)
        finally:
            if handle:
                self._io_utils.close_handle(handle)

        return dict(volume_serial_number=info.VolumeSerialNumber,
                    file_id=bytearray(info.FileId.Identifier)) 
Example #5
Source File: pathutils.py    From os-win with Apache License 2.0 5 votes vote down vote up
def temporary_file(self, suffix=None, *args, **kwargs):
        """Creates a random, temporary, closed file, returning the file's

        path. It's different from tempfile.NamedTemporaryFile which returns
        an open file descriptor.
        """

        tmp_file_path = None
        try:
            tmp_file_path = self.create_temporary_file(suffix, *args, **kwargs)
            yield tmp_file_path
        finally:
            if tmp_file_path:
                fileutils.delete_if_exists(tmp_file_path) 
Example #6
Source File: pathutils.py    From os-win with Apache License 2.0 5 votes vote down vote up
def open(self, path, mode):
        """Wrapper on __builtin__.open used to simplify unit testing."""
        from six.moves import builtins
        return builtins.open(path, mode) 
Example #7
Source File: gzip.py    From apitools with Apache License 2.0 5 votes vote down vote up
def open(filename, mode="rb", compresslevel=9):
    """Shorthand for GzipFile(filename, mode, compresslevel).

    The filename argument is required; mode defaults to 'rb'
    and compresslevel defaults to 9.

    """
    return GzipFile(filename, mode, compresslevel) 
Example #8
Source File: sandbox.py    From PhonePi_SampleServer with MIT License 5 votes vote down vote up
def open(self, file, flags, mode=0o777, *args, **kw):
        """Called for low-level os.open()"""
        if flags & WRITE_FLAGS and not self._ok(file):
            self._violation("os.open", file, flags, mode, *args, **kw)
        return _os.open(file, flags, mode, *args, **kw) 
Example #9
Source File: sandbox.py    From PhonePi_SampleServer with MIT License 5 votes vote down vote up
def _open(self, path, mode='r', *args, **kw):
        if mode not in ('r', 'rt', 'rb', 'rU', 'U') and not self._ok(path):
            self._violation("open", path, mode, *args, **kw)
        return _open(path, mode, *args, **kw) 
Example #10
Source File: sandbox.py    From PhonePi_SampleServer with MIT License 5 votes vote down vote up
def run(self, func):
        """Run 'func' under os sandboxing"""
        try:
            self._copy(self)
            if _file:
                builtins.file = self._file
            builtins.open = self._open
            self._active = True
            return func()
        finally:
            self._active = False
            if _file:
                builtins.file = _file
            builtins.open = _open
            self._copy(_os) 
Example #11
Source File: sandbox.py    From PhonePi_SampleServer with MIT License 5 votes vote down vote up
def _execfile(filename, globals, locals=None):
    """
    Python 3 implementation of execfile.
    """
    mode = 'rb'
    with open(filename, mode) as stream:
        script = stream.read()
    # compile() function in Python 2.6 and 3.1 requires LF line endings.
    if sys.version_info[:2] < (2, 7) or sys.version_info[:2] >= (3, 0) and sys.version_info[:2] < (3, 2):
        script = script.replace(b'\r\n', b'\n')
        script = script.replace(b'\r', b'\n')
    if locals is None:
        locals = globals
    code = compile(script, filename, 'exec')
    exec(code, globals, locals) 
Example #12
Source File: test_versions.py    From masakari with Apache License 2.0 5 votes vote down vote up
def test_release_file(self):
        version.loaded = False
        real_open = builtins.open
        real_find_file = cfg.CONF.find_file

        def fake_find_file(self, name):
            if name == "release":
                return "/etc/masakari/release"
            return real_find_file(self, name)

        def fake_open(path, *args, **kwargs):
            if path == "/etc/masakari/release":
                data = """[Masakari]
vendor = ACME Corporation
product = ACME Masakari
package = 1337"""
                return six.StringIO(data)

            return real_open(path, *args, **kwargs)

        self.stub_out('six.moves.builtins.open', fake_open)
        self.stub_out('oslo_config.cfg.ConfigOpts.find_file', fake_find_file)

        self.assertEqual(version.vendor_string(), "ACME Corporation")
        self.assertEqual(version.product_string(), "ACME Masakari")
        self.assertEqual(version.package_string(), "1337") 
Example #13
Source File: fs.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def open(path, *args, **kwargs):  # pylint: disable=redefined-builtin
  return builtins.open(extend(path), *args, **kwargs)


## os 
Example #14
Source File: sandbox.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def open(self, file, flags, mode=0o777, *args, **kw):
        """Called for low-level os.open()"""
        if flags & WRITE_FLAGS and not self._ok(file):
            self._violation("os.open", file, flags, mode, *args, **kw)
        return _os.open(file, flags, mode, *args, **kw) 
Example #15
Source File: sandbox.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def _open(self, path, mode='r', *args, **kw):
        if mode not in ('r', 'rt', 'rb', 'rU', 'U') and not self._ok(path):
            self._violation("open", path, mode, *args, **kw)
        return _open(path, mode, *args, **kw) 
Example #16
Source File: sandbox.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def run(self, func):
        """Run 'func' under os sandboxing"""
        try:
            self._copy(self)
            if _file:
                builtins.file = self._file
            builtins.open = self._open
            self._active = True
            return func()
        finally:
            self._active = False
            if _file:
                builtins.file = _file
            builtins.open = _open
            self._copy(_os) 
Example #17
Source File: sandbox.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def _execfile(filename, globals, locals=None):
    """
    Python 3 implementation of execfile.
    """
    mode = 'rb'
    with open(filename, mode) as stream:
        script = stream.read()
    # compile() function in Python 2.6 and 3.1 requires LF line endings.
    if sys.version_info[:2] < (2, 7) or sys.version_info[:2] >= (3, 0) and sys.version_info[:2] < (3, 2):
        script = script.replace(b'\r\n', b'\n')
        script = script.replace(b'\r', b'\n')
    if locals is None:
        locals = globals
    code = compile(script, filename, 'exec')
    exec(code, globals, locals) 
Example #18
Source File: gng_impl_test.py    From loaner with Apache License 2.0 5 votes vote down vote up
def tearDown(self):
    super(ManagerTest, self).tearDown()
    self.stubs.UnsetAll()
    builtins.open = self.real_open

    self.auth_patcher.stop() 
Example #19
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 #20
Source File: deploy_impl_test.py    From loaner with Apache License 2.0 5 votes vote down vote up
def testManifestCheck(self, mock_rawinput):
    """Test the manifest file check opens and loads json data."""
    file_name = '/this/is/a/workspace/loaner/chrome_app/manifest.json'
    self.fs.CreateFile(file_name, contents=_CORRECT_JSON)
    test_chrome_app_config = self.CreateTestChromeAppConfig()
    test_chrome_app_config._ManifestCheck()
    assert mock_rawinput.call_count == 1
    with open(file_name, 'r') as f:
      data = json.load(f)
      assert data['version'] == '1.0' 
Example #21
Source File: fs.py    From luci-py with Apache License 2.0 4 votes vote down vote up
def readlink(path):
    """Reads a symlink on Windows."""
    path = six.text_type(path)
    # Interestingly, when using FILE_FLAG_OPEN_REPARSE_POINT and the destination
    # is not a reparse point, the actual file will be opened. It's the
    # DeviceIoControl() below that will fail with 4390.
    handle = windll.kernel32.CreateFileW(
        extend(path),
        FILE_READ_EA,
        FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
        None,
        OPEN_ALWAYS,
        FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OPEN_REPARSE_POINT,
        None)
    if handle == INVALID_HANDLE_VALUE:
      # pylint: disable=undefined-variable
      raise WindowsError(
          u'readlink(%r): failed to open: %s' % (path, ctypes.GetLastError()))
    try:
      buf = REPARSE_DATA_BUFFER()
      returned = wintypes.DWORD()
      ret = DeviceIoControl(
          handle, FSCTL_GET_REPARSE_POINT, None, 0, ctypes.byref(buf),
          ctypes.sizeof(buf), ctypes.byref(returned), None)
      if not ret:
        err = ctypes.GetLastError()
        # ERROR_MORE_DATA(234) should not happen because we preallocate the
        # maximum size.
        if err == 4390:
          # pylint: disable=undefined-variable
          raise WindowsError(
              u'readlink(%r): failed to read: ERROR_NOT_A_REPARSE_POINT(4390)' %
              path)
        # pylint: disable=undefined-variable
        raise WindowsError(
            u'readlink(%r): failed to read: %s' % (path, err))
      if buf.ReparseTag == IO_REPARSE_TAG_SYMLINK:
        actual = buf.ReparseBuffer.SymbolicLinkReparseBuffer
      elif buf.ReparseTag == IO_REPARSE_TAG_MOUNT_POINT:
        actual = buf.ReparseBuffer.MountPointReparseBuffer
      else:
        raise WindowsError(  # pylint: disable=undefined-variable
            u'readlink(%r): succeeded but doesn\'t know how to parse result!' %
            path)
      off = actual.PrintNameOffset / 2
      end = off + actual.PrintNameLength / 2
      return actual.PathBuffer[off:end]
    finally:
      windll.kernel32.CloseHandle(handle)