Python os.O_WRONLY Examples

The following are 30 code examples of os.O_WRONLY(). 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 os , or try the search function .
Example #1
Source File: test_io.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_flush_error_on_close(self):
        # raw file
        # Issue #5700: io.FileIO calls flush() after file closed
        self.check_flush_error_on_close(support.TESTFN, 'wb', buffering=0)
        fd = os.open(support.TESTFN, os.O_WRONLY|os.O_CREAT)
        self.check_flush_error_on_close(fd, 'wb', buffering=0)
        fd = os.open(support.TESTFN, os.O_WRONLY|os.O_CREAT)
        self.check_flush_error_on_close(fd, 'wb', buffering=0, closefd=False)
        os.close(fd)
        # buffered io
        self.check_flush_error_on_close(support.TESTFN, 'wb')
        fd = os.open(support.TESTFN, os.O_WRONLY|os.O_CREAT)
        self.check_flush_error_on_close(fd, 'wb')
        fd = os.open(support.TESTFN, os.O_WRONLY|os.O_CREAT)
        self.check_flush_error_on_close(fd, 'wb', closefd=False)
        os.close(fd)
        # text io
        self.check_flush_error_on_close(support.TESTFN, 'w')
        fd = os.open(support.TESTFN, os.O_WRONLY|os.O_CREAT)
        self.check_flush_error_on_close(fd, 'w')
        fd = os.open(support.TESTFN, os.O_WRONLY|os.O_CREAT)
        self.check_flush_error_on_close(fd, 'w', closefd=False)
        os.close(fd) 
Example #2
Source File: render_utils.py    From ObjectPoseEstimationSummary with MIT License 6 votes vote down vote up
def render_without_output(use_antialiasing=True):
    # redirect output to log file
    logfile = 'blender_render.log'
    open(logfile, 'a').close()
    old = os.dup(1)
    sys.stdout.flush()
    os.close(1)
    os.open(logfile, os.O_WRONLY)
    # Render
    bpy.context.scene.render.use_antialiasing = use_antialiasing
    bpy.ops.render.render(write_still=True)
    # disable output redirection
    os.close(1)
    os.dup(old)
    os.close(old)


# Creating a lamp with an appropriate energy 
Example #3
Source File: pidlockfile.py    From kobo-predict with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def write_pid_to_pidfile(pidfile_path):
    """ Write the PID in the named PID file.

        Get the numeric process ID (“PID”) of the current process
        and write it to the named file as a line of text.

        """
    open_flags = (os.O_CREAT | os.O_EXCL | os.O_WRONLY)
    open_mode = 0o644
    pidfile_fd = os.open(pidfile_path, open_flags, open_mode)
    pidfile = os.fdopen(pidfile_fd, 'w')

    # According to the FHS 2.3 section on PID files in /var/run:
    #
    #   The file must consist of the process identifier in
    #   ASCII-encoded decimal, followed by a newline character. For
    #   example, if crond was process number 25, /var/run/crond.pid
    #   would contain three characters: two, five, and newline.

    pid = os.getpid()
    pidfile.write("%s\n" % pid)
    pidfile.close() 
Example #4
Source File: pidlockfile.py    From jbox with MIT License 6 votes vote down vote up
def write_pid_to_pidfile(pidfile_path):
    """ Write the PID in the named PID file.

        Get the numeric process ID (“PID”) of the current process
        and write it to the named file as a line of text.

        """
    open_flags = (os.O_CREAT | os.O_EXCL | os.O_WRONLY)
    open_mode = 0o644
    pidfile_fd = os.open(pidfile_path, open_flags, open_mode)
    pidfile = os.fdopen(pidfile_fd, 'w')

    # According to the FHS 2.3 section on PID files in /var/run:
    #
    #   The file must consist of the process identifier in
    #   ASCII-encoded decimal, followed by a newline character. For
    #   example, if crond was process number 25, /var/run/crond.pid
    #   would contain three characters: two, five, and newline.

    pid = os.getpid()
    pidfile.write("%s\n" % pid)
    pidfile.close() 
Example #5
Source File: pidlockfile.py    From recruit with Apache License 2.0 6 votes vote down vote up
def write_pid_to_pidfile(pidfile_path):
    """ Write the PID in the named PID file.

        Get the numeric process ID (“PID”) of the current process
        and write it to the named file as a line of text.

        """
    open_flags = (os.O_CREAT | os.O_EXCL | os.O_WRONLY)
    open_mode = 0o644
    pidfile_fd = os.open(pidfile_path, open_flags, open_mode)
    pidfile = os.fdopen(pidfile_fd, 'w')

    # According to the FHS 2.3 section on PID files in /var/run:
    #
    #   The file must consist of the process identifier in
    #   ASCII-encoded decimal, followed by a newline character. For
    #   example, if crond was process number 25, /var/run/crond.pid
    #   would contain three characters: two, five, and newline.

    pid = os.getpid()
    pidfile.write("%s\n" % pid)
    pidfile.close() 
Example #6
Source File: fbx2joints3d.py    From 2D-Motion-Retargeting with MIT License 6 votes vote down vote up
def clear_scene_and_import_fbx(filepath):
    """
    Clear the whole scene and import fbx file into the empty scene.

    :param filepath: filepath for fbx file
    """
    # redirect blender output info
    logfile = 'blender_render.log'
    open(logfile, 'w').close()
    old = os.dup(1)
    sys.stdout.flush()
    os.close(1)
    os.open(logfile, os.O_WRONLY)

    bpy.ops.wm.read_homefile(filepath=HOME_FILE_PATH)
    bpy.ops.import_scene.fbx(filepath=filepath)

    os.close(1)
    os.dup(old)
    os.close(old) 
Example #7
Source File: test_plug.py    From octavia with Apache License 2.0 6 votes vote down vote up
def test__interface_by_mac_not_found(self, mock_ipr):
        mock_ipr_instance = mock.MagicMock()
        mock_ipr_instance.link_lookup.return_value = []
        mock_ipr().__enter__.return_value = mock_ipr_instance

        fd_mock = mock.mock_open()
        open_mock = mock.Mock()
        isfile_mock = mock.Mock()
        with mock.patch('os.open', open_mock), mock.patch.object(
                os, 'fdopen', fd_mock), mock.patch.object(
                os.path, 'isfile', isfile_mock):
            self.assertRaises(wz_exceptions.HTTPException,
                              self.test_plug._interface_by_mac,
                              FAKE_MAC_ADDRESS.upper())
        open_mock.assert_called_once_with('/sys/bus/pci/rescan', os.O_WRONLY)
        fd_mock().write.assert_called_once_with('1') 
Example #8
Source File: plug.py    From octavia with Apache License 2.0 6 votes vote down vote up
def _interface_by_mac(self, mac):
        try:
            with pyroute2.IPRoute() as ipr:
                idx = ipr.link_lookup(address=mac)[0]
                addr = ipr.get_links(idx)[0]
                for attr in addr['attrs']:
                    if attr[0] == 'IFLA_IFNAME':
                        return attr[1]
        except Exception as e:
            LOG.info('Unable to find interface with MAC: %s, rescanning '
                     'and returning 404. Reported error: %s', mac, str(e))

        # Poke the kernel to re-enumerate the PCI bus.
        # We have had cases where nova hot plugs the interface but
        # the kernel doesn't get the memo.
        filename = '/sys/bus/pci/rescan'
        flags = os.O_WRONLY
        if os.path.isfile(filename):
            with os.fdopen(os.open(filename, flags), 'w') as rescan_file:
                rescan_file.write('1')
        raise exceptions.HTTPException(
            response=webob.Response(json=dict(
                details="No suitable network interface found"), status=404)) 
Example #9
Source File: loadbalancer.py    From octavia with Apache License 2.0 6 votes vote down vote up
def upload_certificate(self, lb_id, filename):
        self._check_ssl_filename_format(filename)

        # create directory if not already there
        if not os.path.exists(self._cert_dir(lb_id)):
            os.makedirs(self._cert_dir(lb_id))

        stream = Wrapped(flask.request.stream)
        file = self._cert_file_path(lb_id, filename)
        flags = os.O_WRONLY | os.O_CREAT
        # mode 00600
        mode = stat.S_IRUSR | stat.S_IWUSR
        with os.fdopen(os.open(file, flags, mode), 'wb') as crt_file:
            b = stream.read(BUFFER)
            while b:
                crt_file.write(b)
                b = stream.read(BUFFER)

        resp = webob.Response(json=dict(message='OK'))
        resp.headers['ETag'] = stream.get_md5()
        return resp 
Example #10
Source File: util.py    From octavia with Apache License 2.0 6 votes vote down vote up
def install_netns_systemd_service():
    os_utils = osutils.BaseOS.get_os_util()

    flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC
    # mode 00644
    mode = (stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH)

    # TODO(bcafarel): implement this for other init systems
    # netns handling depends on a separate unit file
    netns_path = os.path.join(consts.SYSTEMD_DIR,
                              consts.AMP_NETNS_SVC_PREFIX + '.service')

    jinja_env = jinja2.Environment(
        autoescape=True, loader=jinja2.FileSystemLoader(os.path.dirname(
            os.path.realpath(__file__)
        ) + consts.AGENT_API_TEMPLATES))

    if not os.path.exists(netns_path):
        with os.fdopen(os.open(netns_path, flags, mode), 'w') as text_file:
            text = jinja_env.get_template(
                consts.AMP_NETNS_SVC_PREFIX + '.systemd.j2').render(
                    amphora_nsname=consts.AMPHORA_NAMESPACE,
                    HasIFUPAll=os_utils.has_ifup_all())
            text_file.write(text) 
Example #11
Source File: server.py    From octavia with Apache License 2.0 6 votes vote down vote up
def upload_config(self):
        try:
            stream = flask.request.stream
            file_path = cfg.find_config_files(project=CONF.project,
                                              prog=CONF.prog)[0]
            flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC
            # mode 00600
            mode = stat.S_IRUSR | stat.S_IWUSR
            with os.fdopen(os.open(file_path, flags, mode), 'wb') as cfg_file:
                b = stream.read(BUFFER)
                while b:
                    cfg_file.write(b)
                    b = stream.read(BUFFER)

            CONF.mutate_config_files()
        except Exception as e:
            LOG.error("Unable to update amphora-agent configuration: "
                      "{}".format(str(e)))
            return webob.Response(json=dict(
                message="Unable to update amphora-agent configuration.",
                details=str(e)), status=500)

        return webob.Response(json={'message': 'OK'}, status=202) 
Example #12
Source File: parallel.py    From avocado-vt with GNU General Public License v2.0 6 votes vote down vote up
def redirect_io(log_file='/dev/null'):
    # Always redirect stdin.
    in_fd = os.open('/dev/null', os.O_RDONLY)
    try:
        os.dup2(in_fd, 0)
    finally:
        os.close(in_fd)

    out_fd = os.open(log_file, os.O_WRONLY | os.O_CREAT)
    try:
        os.dup2(out_fd, 2)
        os.dup2(out_fd, 1)
    finally:
        os.close(out_fd)

    sys.stdin = os.fdopen(0, 'r')
    sys.stdout = os.fdopen(1, 'w')
    sys.stderr = os.fdopen(2, 'w') 
Example #13
Source File: pathlib.py    From python-netsurv with MIT License 6 votes vote down vote up
def create_cleanup_lock(p):
    """crates a lock to prevent premature folder cleanup"""
    lock_path = get_lock_path(p)
    try:
        fd = os.open(str(lock_path), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644)
    except OSError as e:
        if e.errno == errno.EEXIST:
            raise EnvironmentError(
                "cannot create lockfile in {path}".format(path=p)
            ) from e

        else:
            raise
    else:
        pid = os.getpid()
        spid = str(pid).encode()
        os.write(fd, spid)
        os.close(fd)
        if not lock_path.is_file():
            raise EnvironmentError("lock path got renamed after successful creation")
        return lock_path 
Example #14
Source File: __init__.py    From python-netsurv with MIT License 6 votes vote down vote up
def touch(self, mode=0o666, exist_ok=True):
        """
        Create this file with the given access mode, if it doesn't exist.
        """
        if self._closed:
            self._raise_closed()
        if exist_ok:
            # First try to bump modification time
            # Implementation note: GNU touch uses the UTIME_NOW option of
            # the utimensat() / futimens() functions.
            try:
                self._accessor.utime(self, None)
            except OSError:
                # Avoid exception chaining
                pass
            else:
                return
        flags = os.O_CREAT | os.O_WRONLY
        if not exist_ok:
            flags |= os.O_EXCL
        fd = self._raw_open(flags, mode)
        os.close(fd) 
Example #15
Source File: pathlib.py    From python-netsurv with MIT License 6 votes vote down vote up
def create_cleanup_lock(p):
    """crates a lock to prevent premature folder cleanup"""
    lock_path = get_lock_path(p)
    try:
        fd = os.open(str(lock_path), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644)
    except OSError as e:
        if e.errno == errno.EEXIST:
            raise EnvironmentError(
                "cannot create lockfile in {path}".format(path=p)
            ) from e

        else:
            raise
    else:
        pid = os.getpid()
        spid = str(pid).encode()
        os.write(fd, spid)
        os.close(fd)
        if not lock_path.is_file():
            raise EnvironmentError("lock path got renamed after successful creation")
        return lock_path 
Example #16
Source File: __init__.py    From python-netsurv with MIT License 6 votes vote down vote up
def touch(self, mode=0o666, exist_ok=True):
        """
        Create this file with the given access mode, if it doesn't exist.
        """
        if self._closed:
            self._raise_closed()
        if exist_ok:
            # First try to bump modification time
            # Implementation note: GNU touch uses the UTIME_NOW option of
            # the utimensat() / futimens() functions.
            try:
                self._accessor.utime(self, None)
            except OSError:
                # Avoid exception chaining
                pass
            else:
                return
        flags = os.O_CREAT | os.O_WRONLY
        if not exist_ok:
            flags |= os.O_EXCL
        fd = self._raw_open(flags, mode)
        os.close(fd) 
Example #17
Source File: test_vyper.py    From vyper with MIT License 6 votes vote down vote up
def _init_dirs(self):
        test_dirs = ["a a", "b", "D_"]
        config = "improbable"
        root = tempfile.mkdtemp()

        def cleanup():
            try:
                os.removedirs(root)
            except (FileNotFoundError, OSError):
                pass

        os.chdir(root)

        for dir_ in test_dirs:
            os.mkdir(dir_, 0o0750)

            f = "{0}.toml".format(config)
            flags = os.O_WRONLY | os.O_CREAT
            rel_path = "{0}/{1}".format(dir_, f)
            abs_file_path = os.path.join(root, rel_path)
            with os.fdopen(os.open(abs_file_path, flags, 0o0640), "w") as fp:
                fp.write('key = "value is {0}"\n'.format(dir_))

        return root, config, cleanup 
Example #18
Source File: test_posix.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_path_with_null_byte(self):
        fn = test_support.TESTFN
        fn_with_NUL = fn + '\0'
        self.addCleanup(test_support.unlink, fn)
        test_support.unlink(fn)
        fd = None
        try:
            with self.assertRaises(TypeError):
                fd = os.open(fn_with_NUL, os.O_WRONLY | os.O_CREAT) # raises
        finally:
            if fd is not None:
                os.close(fd)
        self.assertFalse(os.path.exists(fn))
        self.assertRaises(TypeError, os.mkdir, fn_with_NUL)
        self.assertFalse(os.path.exists(fn))
        open(fn, 'wb').close()
        self.assertRaises(TypeError, os.stat, fn_with_NUL) 
Example #19
Source File: conn.py    From SkPy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def writeToken(self):
        """
        Store details of the current connection in the named file.

        This can be used by :meth:`readToken` to re-authenticate at a later time.
        """
        # Write token file privately.
        with os.fdopen(os.open(self.tokenFile, os.O_WRONLY | os.O_CREAT, 0o600), "w") as f:
            # When opening files via os, truncation must be done manually.
            f.truncate()
            f.write(self.userId + "\n")
            f.write(self.tokens["skype"] + "\n")
            f.write(str(int(time.mktime(self.tokenExpiry["skype"].timetuple()))) + "\n")
            f.write(self.tokens["reg"] + "\n")
            f.write(str(int(time.mktime(self.tokenExpiry["reg"].timetuple()))) + "\n")
            f.write(self.msgsHost + "\n") 
Example #20
Source File: test_posix.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_path_with_null_unicode(self):
        fn = test_support.TESTFN_UNICODE
        try:
            fn.encode(test_support.TESTFN_ENCODING)
        except (UnicodeError, TypeError):
            self.skipTest("Requires unicode filenames support")
        fn_with_NUL = fn + u'\0'
        self.addCleanup(test_support.unlink, fn)
        test_support.unlink(fn)
        fd = None
        try:
            with self.assertRaises(TypeError):
                fd = os.open(fn_with_NUL, os.O_WRONLY | os.O_CREAT) # raises
        finally:
            if fd is not None:
                os.close(fd)
        self.assertFalse(os.path.exists(fn))
        self.assertRaises(TypeError, os.mkdir, fn_with_NUL)
        self.assertFalse(os.path.exists(fn))
        open(fn, 'wb').close()
        self.assertRaises(TypeError, os.stat, fn_with_NUL) 
Example #21
Source File: pyfakewebcam.py    From pyfakewebcam with GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, video_device, width, height, channels=3, input_pixfmt='RGB'):
        
        if channels != 3:
            raise NotImplementedError('Code only supports inputs with 3 channels right now. You tried to intialize with {} channels'.format(channels))

        if input_pixfmt != 'RGB':
            raise NotImplementedError('Code only supports RGB pixfmt. You tried to intialize with {}'.format(input_pixfmt))
        
        if not os.path.exists(video_device):
            sys.stderr.write('\n--- Make sure the v4l2loopback kernel module is loaded ---\n')
            sys.stderr.write('sudo modprobe v4l2loopback devices=1\n\n')
            raise FileNotFoundError('device does not exist: {}'.format(video_device))

        self._channels = channels
        self._video_device = os.open(video_device, os.O_WRONLY | os.O_SYNC)
                    
        self._settings = _v4l2.v4l2_format()
        self._settings.type = _v4l2.V4L2_BUF_TYPE_VIDEO_OUTPUT
        self._settings.fmt.pix.pixelformat = _v4l2.V4L2_PIX_FMT_YUYV
        self._settings.fmt.pix.width = width
        self._settings.fmt.pix.height = height
        self._settings.fmt.pix.field = _v4l2.V4L2_FIELD_NONE
        self._settings.fmt.pix.bytesperline = width * 2
        self._settings.fmt.pix.sizeimage = width * height * 2
        self._settings.fmt.pix.colorspace = _v4l2.V4L2_COLORSPACE_JPEG

        self._buffer = np.zeros((self._settings.fmt.pix.height, 2*self._settings.fmt.pix.width), dtype=np.uint8)

        self._yuv = np.zeros((self._settings.fmt.pix.height, self._settings.fmt.pix.width, 3), dtype=np.uint8)
        self._ones = np.ones((self._settings.fmt.pix.height, self._settings.fmt.pix.width, 1), dtype=np.uint8)
        self._rgb2yuv = np.array([[0.299, 0.587, 0.114, 0],
                                  [-0.168736, -0.331264, 0.5, 128],
                                  [0.5, -0.418688, -0.081312, 128]])
        
        fcntl.ioctl(self._video_device, _v4l2.VIDIOC_S_FMT, self._settings) 
Example #22
Source File: pidlockfile.py    From Python24 with MIT License 6 votes vote down vote up
def write_pid_to_pidfile(pidfile_path):
    """ Write the PID in the named PID file.

        Get the numeric process ID (“PID”) of the current process
        and write it to the named file as a line of text.

        """
    open_flags = (os.O_CREAT | os.O_EXCL | os.O_WRONLY)
    open_mode = 0o644
    pidfile_fd = os.open(pidfile_path, open_flags, open_mode)
    pidfile = os.fdopen(pidfile_fd, 'w')

    # According to the FHS 2.3 section on PID files in /var/run:
    #
    #   The file must consist of the process identifier in
    #   ASCII-encoded decimal, followed by a newline character. For
    #   example, if crond was process number 25, /var/run/crond.pid
    #   would contain three characters: two, five, and newline.

    pid = os.getpid()
    pidfile.write("%s\n" % pid)
    pidfile.close() 
Example #23
Source File: test_subprocess.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_no_leaking(self):
        # Make sure we leak no resources
        if not mswindows:
            max_handles = 1026 # too much for most UNIX systems
        else:
            max_handles = 2050 # too much for (at least some) Windows setups
        handles = []
        try:
            for i in range(max_handles):
                try:
                    handles.append(os.open(test_support.TESTFN,
                                           os.O_WRONLY | os.O_CREAT))
                except OSError as e:
                    if e.errno != errno.EMFILE:
                        raise
                    break
            else:
                self.skipTest("failed to reach the file descriptor limit "
                    "(tried %d)" % max_handles)
            # Close a couple of them (should be enough for a subprocess)
            for i in range(10):
                os.close(handles.pop())
            # Loop creating some subprocesses. If one of them leaks some fds,
            # the next loop iteration will fail by reaching the max fd limit.
            for i in range(15):
                p = subprocess.Popen([sys.executable, "-c",
                                      "import sys;"
                                      "sys.stdout.write(sys.stdin.read())"],
                                     stdin=subprocess.PIPE,
                                     stdout=subprocess.PIPE,
                                     stderr=subprocess.PIPE)
                data = p.communicate(b"lime")[0]
                self.assertEqual(data, b"lime")
        finally:
            for h in handles:
                os.close(h)
            test_support.unlink(test_support.TESTFN) 
Example #24
Source File: test_gzip.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_fileobj_from_io_open(self):
        fd = os.open(self.filename, os.O_WRONLY | os.O_CREAT)
        with io.open(fd, "wb") as f:
            with gzip.GzipFile(fileobj=f, mode="w") as g:
                self.assertEqual(g.name, "") 
Example #25
Source File: test_gzip.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_fileobj_from_fdopen(self):
        # Issue #13781: Creating a GzipFile using a fileobj from os.fdopen()
        # should not embed the fake filename "<fdopen>" in the output file.
        fd = os.open(self.filename, os.O_WRONLY | os.O_CREAT)
        with os.fdopen(fd, "wb") as f:
            with gzip.GzipFile(fileobj=f, mode="w") as g:
                self.assertEqual(g.name, "") 
Example #26
Source File: test_zipfile.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def requiresWriteAccess(self, path):
        if not os.access(path, os.W_OK):
            self.skipTest('requires write access to the installed location')
        filename = os.path.join(path, 'test_zipfile.try')
        try:
            fd = os.open(filename, os.O_WRONLY | os.O_CREAT)
            os.close(fd)
        except Exception:
            self.skipTest('requires write access to the installed location')
        unlink(filename) 
Example #27
Source File: test_posix.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_osshlock(self):
        fd1 = os.open(test_support.TESTFN,
                      os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
        fd2 = os.open(test_support.TESTFN,
                      os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
        os.close(fd2)
        os.close(fd1)

        if hasattr(posix, "O_EXLOCK"):
            fd = os.open(test_support.TESTFN,
                         os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
            self.assertRaises(OSError, os.open, test_support.TESTFN,
                              os.O_RDONLY|os.O_EXLOCK|os.O_NONBLOCK)
            os.close(fd) 
Example #28
Source File: test_local.py    From octavia with Apache License 2.0 5 votes vote down vote up
def _store_cert(self):
        fd_mock = mock.mock_open()
        open_mock = mock.Mock()
        # Attempt to store the cert
        with mock.patch('os.open', open_mock), mock.patch.object(
                os, 'fdopen', fd_mock):
            cert_id = local_cert_mgr.LocalCertManager.store_cert(
                context=None,
                certificate=self.certificate,
                intermediates=self.intermediates,
                private_key=self.private_key,
                private_key_passphrase=self.private_key_passphrase
            )

        # Check that something came back
        self.assertIsNotNone(cert_id)

        # Verify the correct files were opened
        flags = os.O_WRONLY | os.O_CREAT
        mode = stat.S_IRUSR | stat.S_IWUSR  # mode 0600
        open_mock.assert_has_calls([
            mock.call(
                os.path.join('/tmp/{0}.crt'.format(cert_id)), flags, mode),
            mock.call(
                os.path.join('/tmp/{0}.key'.format(cert_id)), flags, mode),
            mock.call(
                os.path.join('/tmp/{0}.int'.format(cert_id)), flags, mode),
            mock.call(
                os.path.join('/tmp/{0}.pass'.format(cert_id)), flags, mode)
        ], any_order=True)

        # Verify the writes were made
        fd_mock().write.assert_has_calls([
            mock.call(self.certificate),
            mock.call(self.intermediates),
            mock.call(self.private_key),
            mock.call(self.private_key_passphrase)
        ], any_order=True)

        return cert_id 
Example #29
Source File: tarfile.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, name, mode):
        mode = {
            "r": os.O_RDONLY,
            "w": os.O_WRONLY | os.O_CREAT | os.O_TRUNC,
        }[mode]
        if hasattr(os, "O_BINARY"):
            mode |= os.O_BINARY
        self.fd = os.open(name, mode, 0o666) 
Example #30
Source File: test_posix.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_osexlock(self):
        fd = os.open(test_support.TESTFN,
                     os.O_WRONLY|os.O_EXLOCK|os.O_CREAT)
        self.assertRaises(OSError, os.open, test_support.TESTFN,
                          os.O_WRONLY|os.O_EXLOCK|os.O_NONBLOCK)
        os.close(fd)

        if hasattr(posix, "O_SHLOCK"):
            fd = os.open(test_support.TESTFN,
                         os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
            self.assertRaises(OSError, os.open, test_support.TESTFN,
                              os.O_WRONLY|os.O_EXLOCK|os.O_NONBLOCK)
            os.close(fd)