def test_write(tmppath): """Test write().""" # With a new file. xfile = XRootDFile(mkurl(join(tmppath, 'data/nuts')), 'w+') assert xfile.size == 0 conts = xfile.read() assert not conts nconts = 'Write.' xfile.write(nconts) assert xfile.tell() == len(nconts) assert not xfile.closed xfile.seek(0) assert xfile.size == len(nconts) assert xfile.read() == nconts xfile.close() # Verify persistence after closing. xfile = XRootDFile(mkurl(join(tmppath, 'data/nuts')), 'r+') assert xfile.size == len(nconts) assert xfile.read() == nconts # Seek(x>0) followed by a write nc2 = 'hello' cntr = len(nconts)//2 xfile.seek(cntr) xfile.write(nc2) assert xfile.tell() == len(nc2) + cntr xfile.seek(0) assert xfile.read() == nconts[:cntr] + nc2 xfile.close() # Seek(x>0) followed by a write of len < size-x fd = get_tsta_file(tmppath) fp, fc = fd['full_path'], fd['contents'] xfile = XRootDFile(mkurl(fp), 'r+') assert xfile.read() == fc xfile.seek(2) nc = 'yo' xfile.write(nc) assert xfile.tell() == len(nc) + 2 assert xfile.read() == fc[2+len(nc):] # run w/ flushing == true xfile.write('', True) # Mock an error, yayy! fake_status = { "status": 3, "code": 0, "ok": False, "errno": errno.EREMOTE, "error": True, "message": '[FATAL] Remote I/O Error', "fatal": True, "shellcode": 51 } xfile._file.write = Mock(return_value=(XRootDStatus(fake_status), None)) pytest.raises(IOError, xfile.write, '')
def read(self, offset=0, size=0, timeout=0, callback=None): """Read a data chunk from a given offset. :param offset: offset from the beginning of the file :type offset: integer :param size: number of bytes to be read :type size: integer :returns: tuple containing :mod:`XRootD.client.responses.XRootDStatus` object and the data that was read """ if callback: callback = CallbackWrapper(callback, None) return XRootDStatus( self.__file.read(offset, size, timeout, callback)) status, response = self.__file.read(offset, size, timeout) return XRootDStatus(status), response
def deeplocate(self, path, flags, timeout=0, callback=None): """Locate a file, recursively locate all disk servers. :param path: path to the file to be located :type path: string :param flags: An `ORed` combination of :mod:`XRootD.client.flags.OpenFlags` :returns: tuple containing :mod:`XRootD.client.responses.XRootDStatus` object and :mod:`XRootD.client.responses.LocationInfo` object """ if callback: callback = CallbackWrapper(callback, LocationInfo) return XRootDStatus( self.__fs.deeplocate(path, flags, timeout, callback)) status, response = self.__fs.deeplocate(path, flags, timeout) if response: response = LocationInfo(response) return XRootDStatus(status), response
def truncate(self, path, size, timeout=0, callback=None): """Truncate a file. :param path: path to the file to be truncated :type path: string :param size: file size :type size: integer :returns: tuple containing :mod:`XRootD.client.responses.XRootDStatus` object and None """ if callback: callback = CallbackWrapper(callback, None) return XRootDStatus( self.__fs.truncate(path, size, timeout, callback)) status, response = self.__fs.truncate(path, size, timeout) return XRootDStatus(status), None
def write(self, buffer, offset=0, size=0, timeout=0, callback=None): """Write a data chunk at a given offset. :param buffer: data to be written :param offset: offset from the beginning of the file :type offset: integer :param size: number of bytes to be written :type size: integer :returns: tuple containing :mod:`XRootD.client.responses.XRootDStatus` object and None """ if callback: callback = CallbackWrapper(callback, None) return XRootDStatus(self.__file.write(buffer, offset, size, timeout, callback)) status, response = self.__file.write(buffer, offset, size, timeout) return XRootDStatus(status), None
def __call__(self, status, response, *argv): self.status = XRootDStatus(status) self.response = response if self.responsetype: self.response = self.responsetype(response) if argv: self.hostlist = HostList(argv[0]) else: self.hostlist = HostList([]) self.callback(self.status, self.response, self.hostlist)
def prepare(self, files, flags, priority=0, timeout=0, callback=None): """Prepare one or more files for access. :param files: list of files to be prepared :type files: list :param flags: An `ORed` combination of :mod:`XRootD.client.flags.PrepareFlags` :param priority: priority of the request 0 (lowest) - 3 (highest) :type priority: integer :returns: tuple containing :mod:`XRootD.client.responses.XRootDStatus` object and None """ if callback: callback = CallbackWrapper(callback, None) return XRootDStatus( self.__fs.prepare(files, flags, priority, timeout, callback)) status, response = self.__fs.prepare(files, flags, priority, timeout) return XRootDStatus(status), response
def open(self, url, flags=0, mode=0, timeout=0, callback=None): """Open the file pointed to by the given URL. :param url: url of the file to be opened :type url: string :param flags: An `ORed` combination of :mod:`XRootD.client.flags.OpenFlags` where the default is `OpenFlags.NONE` :param mode: access mode for new files, an `ORed` combination of :mod:`XRootD.client.flags.AccessMode` where the default is `AccessMode.NONE` :returns: tuple containing :mod:`XRootD.client.responses.XRootDStatus` object and None """ if callback: callback = CallbackWrapper(callback, None) return XRootDStatus(self.__file.open(url, flags, mode, timeout, callback)) status, response = self.__file.open(url, flags, mode, timeout) return XRootDStatus(status), None
def vector_read(self, chunks, timeout=0, callback=None): """Read scattered data chunks in one operation. :param chunks: list of the chunks to be read. The default maximum chunk size is 2097136 bytes and the default maximum number of chunks per request is 1024. The server may be queried using :func:`XRootD.client.FileSystem.query` for the actual settings. :type chunks: list of 2-tuples of the form (offset, size) :returns: tuple containing :mod:`XRootD.client.responses.XRootDStatus` object and :mod:`XRootD.client.responses.VectorReadInfo` object """ if callback: callback = CallbackWrapper(callback, VectorReadInfo) return XRootDStatus(self.__file.vector_read(chunks, timeout, callback)) status, response = self.__file.vector_read(chunks, timeout) if response: response = VectorReadInfo(response) return XRootDStatus(status), response
def query(self, querycode, arg, timeout=0, callback=None): """Obtain server information. :param querycode: the query code as specified in :mod:`XRootD.client.flags.QueryCode` :param arg: query argument :type arg: string :returns: the query response or None if there was an error :rtype: string .. note:: For more information about XRootD query codes and arguments, see `the relevant section in the protocol reference <http://xrootd.slac.stanford.edu/doc/prod/XRdv299.htm#_Toc337053385>`_. """ if callback: callback = CallbackWrapper(callback, None) return XRootDStatus(self.__fs.query(querycode, arg, timeout, callback)) status, response = self.__fs.query(querycode, arg, timeout) return XRootDStatus(status), response
def test_checksum(tmppath): """Test checksum method.""" fs = XRootDPyFS(mkurl(tmppath)) # Local xrootd server does not support checksum operation pytest.raises(UnsupportedError, fs.xrd_checksum, "data/testa.txt") # Let's fake a success response fake_status = { "status": 0, "code": 0, "ok": True, "errno": 0, "error": False, "message": '[SUCCESS] ', "fatal": False, "shellcode": 0 } fs.xrd_client.query = Mock( return_value=(XRootDStatus(fake_status), b'adler32 3836a69a\x00')) algo, val = fs.xrd_checksum("data/testa.txt") assert algo == 'adler32' and val == "3836a69a" # Fake a bad response (e.g. on directory) fake_status = { "status": 1, "code": 400, "ok": False, "errno": 3011, "error": True, "message": '[ERROR] Server responded with an error: [3011] no such ' 'file or directory\n', "fatal": False, "shellcode": 54 } fs.xrd_client.query = Mock( return_value=(XRootDStatus(fake_status), None)) pytest.raises(FSError, fs.xrd_checksum, "data/")
def close(self, timeout=0, callback=None): """Close the file. :returns: tuple containing :mod:`XRootD.client.responses.XRootDStatus` object and None As of Python 2.5, you can avoid having to call this method explicitly if you use the :keyword:`with` statement. For example, the following code will automatically close *f* when the :keyword:`with` block is exited:: from __future__ import with_statement # This isn't required in Python 2.6 with client.File() as f: f.open("root://someserver//somefile") for line in f: print line, """ if callback: callback = CallbackWrapper(callback, None) return XRootDStatus(self.__file.close(timeout, callback)) status, response = self.__file.close(timeout) return XRootDStatus(status), None
def mkdir(self, path, flags=0, mode=0, timeout=0, callback=None): """Create a directory. :param path: path to the directory to create :type path: string :param flags: An `ORed` combination of :mod:`XRootD.client.flags.MkDirFlags` where the default is `MkDirFlags.NONE` :param mode: the initial file access mode, an `ORed` combination of :mod:`XRootD.client.flags.AccessMode` where the default is `rwxr-x---` :returns: tuple containing :mod:`XRootD.client.responses.XRootDStatus` object and None """ if mode == 0: mode = AccessMode.UR | AccessMode.UW | AccessMode.UX | \ AccessMode.GR | AccessMode.GX if callback: callback = CallbackWrapper(callback, None) return XRootDStatus(self.__fs.mkdir(path, flags, mode, timeout, callback)) status, response = self.__fs.mkdir(path, flags, mode, timeout) return XRootDStatus(status), None
def dirlist(self, path, flags=0, timeout=0, callback=None): """List entries of a directory. :param path: path to the directory to list :type path: string :param flags: An `ORed` combination of :mod:`XRootD.client.flags.DirListFlags` where the default is `DirListFlags.NONE` :returns: tuple containing :mod:`XRootD.client.responses.XRootDStatus` object and :mod:`XRootD.client.responses.DirectoryList` object .. warning:: Currently, passing `DirListFlags.STAT` with an asynchronous call to :mod:`XRootD.client.FileSystem.dirlist()` does not work, due to an xrootd client limitation. So you'll get ``None`` instead of the ``StatInfo`` instance. See `the GitHub issue <https://github.com/xrootd/xrootd/issues/2>`_ for more details. """ if callback: callback = CallbackWrapper(callback, DirectoryList) return XRootDStatus(self.__fs.dirlist(path, flags, timeout, callback)) status, response = self.__fs.dirlist(path, flags, timeout) if response: response = DirectoryList(response) return XRootDStatus(status), response
def test_query_error(tmppath): """Test unknown error from query.""" fs = XRootDPyFS(mkurl(tmppath)) fake_status = { "status": 3, "code": 101, "ok": False, "errno": 0, "error": True, "message": '[FATAL] Invalid address', "fatal": True, "shellcode": 51 } fs.xrd_client.query = Mock(return_value=(XRootDStatus(fake_status), None)) pytest.raises(FSError, fs._query, 3, "data/testa.txt")
def test_remove_dir_mock1(tmppath): """Test removedir.""" fs = XRootDPyFS(mkurl(tmppath)) status = XRootDStatus({ "status": 3, "code": 101, "ok": False, "errno": 0, "error": True, "message": '[FATAL] Invalid address', "fatal": True, "shellcode": 51 }) fs.xrd_client.rm = Mock(return_value=(status, None)) pytest.raises(ResourceError, fs.removedir, "data/bfolder/", force=True)
def test_ping(tmppath): """Test ping method.""" fs = XRootDPyFS(mkurl(tmppath)) assert fs.xrd_ping() fake_status = { "status": 3, "code": 101, "ok": False, "errno": 0, "error": True, "message": '[FATAL] Invalid address', "fatal": True, "shellcode": 51 } fs.xrd_client.ping = Mock(return_value=(XRootDStatus(fake_status), None)) pytest.raises(RemoteConnectionError, fs.xrd_ping)
def test_close_error(tmppath): """Test error on close().""" xfile = XRootDPyFile(mkurl(get_tsta_file(tmppath)['full_path'])) # Mock error response on close. fake_status = { "status": 1, "code": 3, "ok": False, "errno": 0, "error": True, "message": '[ERROR] Invalid operation', "fatal": False, "shellcode": 50 } xfile._file.close = Mock(return_value=(XRootDStatus(fake_status), None)) # Ensure error is raised. pytest.raises(IOError, xfile.close)
def test_size_len(tmppath): """Tests for the size and len property.""" fd = get_tsta_file(tmppath) full_path, fc = fd['full_path'], fd['contents'] xfile = XRootDPyFile(mkurl(full_path)) assert xfile.size == len(fc) assert len(xfile) == len(fc) # Length of empty file xfile = XRootDPyFile(mkurl(join(tmppath, fd['dir'], 'whut')), 'w+') assert xfile.size == len('') assert len(xfile) == len('') # Length of multiline file fd = get_mltl_file(tmppath) fpp, fc = fd['full_path'], fd['contents'] xfile = XRootDPyFile(mkurl(fpp)) assert xfile.size == len(fc) assert len(xfile) == len(fc) # Mock the error fake_status = { "status": 3, "code": 0, "ok": False, "errno": errno.EREMOTE, "error": True, "message": '[FATAL] Remote I/O Error', "fatal": True, "shellcode": 51 } xfile.close() xfile = XRootDPyFile(mkurl(full_path)) xfile._file.stat = Mock(return_value=(XRootDStatus(fake_status), None)) try: xfile.size assert False except IOError: assert True try: len(xfile) assert False except IOError: assert True
def copy(self, source, target, force=False): """Copy a file. .. note:: This method is less configurable than using :mod:`XRootD.client.CopyProcess` - it is designed to be as simple as possible by using sensible defaults for the underlying copy job. If you need more configurability, or want to make multiple copy jobs run at once in parallel, use :mod:`XRootD.client.CopyProcess`. :param source: Source file path :type source: string :param target: Destination file path :type target: string :param force: overwrite target if it exists :type force: boolean :returns: tuple containing :mod:`XRootD.client.responses.XRootDStatus` object and None """ result = self.__fs.copy(source=source, target=target, force=force)[0] return XRootDStatus(result), None
def end(self, jobId, results): if results.has_key('status'): results['status'] = XRootDStatus(results['status']) if self.handler: self.handler.end(jobId, results)
def end(self, jobId, results): if 'status' in results: results['status'] = XRootDStatus(results['status']) if self.handler: self.handler.end(jobId, results)
def prepare(self): """Prepare the copy jobs. **Must be called before** ``run()``.""" status = self.__process.prepare() return XRootDStatus(status)