From 1fdf804c7acaa84db13b3695d26b3992dffe76ea Mon Sep 17 00:00:00 2001 From: Brian Pugh Date: Sat, 16 Dec 2023 09:41:49 -0800 Subject: [PATCH] apply black linting to whole project. --- .gitattributes | 2 +- .github/dependabot.yml | 2 +- .pre-commit-config.yaml | 46 ++++++++++++ MANIFEST.in | 2 +- ci/build-wheels.sh | 2 +- ci/download_release_files.py | 25 ++++--- docs/api/index.rst | 3 - docs/cli.rst | 2 +- docs/doc8.ini | 2 +- docs/requirements.txt | 2 +- mypy.ini | 2 +- requirements.txt | 2 +- src/littlefs/__init__.py | 64 ++++++----------- src/littlefs/__main__.py | 15 ++-- src/littlefs/context.py | 68 +++++++++--------- src/littlefs/errors.py | 9 +-- src/littlefs/lfs.pyi | 1 - src/littlefs/lfs.pyx | 1 - test/lfs/conftest.py | 14 ++-- test/lfs/test_dir_functions.py | 24 +++---- test/lfs/test_file_functions.py | 62 ++++++++--------- test/lfs/test_fs_functions.py | 14 ++-- test/test_attr.py | 12 ++-- test/test_block_count.py | 36 +++++----- test/test_directories.py | 67 +++++++++--------- test/test_files.py | 119 ++++++++++++++++---------------- test/test_multiversion.py | 34 ++++----- test/test_remove_rename.py | 76 ++++++++++---------- test/test_version.py | 1 + test/test_walk.py | 47 ++++++------- 30 files changed, 390 insertions(+), 366 deletions(-) create mode 100644 .pre-commit-config.yaml diff --git a/.gitattributes b/.gitattributes index 2a50684..fd33580 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1,2 @@ -*.rst text eol=lf \ No newline at end of file +*.rst text eol=lf diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 0bfa336..1ea9f7a 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -3,4 +3,4 @@ updates: - package-ecosystem: "github-actions" directory: "/" schedule: - interval: "weekly" \ No newline at end of file + interval: "weekly" diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..29541e4 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,46 @@ +repos: + - repo: https://github.com/psf/black + rev: 23.12.0 + hooks: + - id: black + args: + - "--line-length=120" + - "--target-version=py38" + - "--target-version=py39" + - "--target-version=py310" + - "--target-version=py311" + - "--target-version=py312" + types: [python] + + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.5.0 + hooks: + - id: check-added-large-files + - id: check-ast + - id: check-builtin-literals + - id: check-case-conflict + - id: check-docstring-first + - id: check-shebang-scripts-are-executable + - id: check-merge-conflict + - id: check-json + - id: check-toml + - id: check-xml + - id: check-yaml + - id: debug-statements + - id: destroyed-symlinks + - id: detect-private-key + - id: end-of-file-fixer + exclude: ^LICENSE|\.(html|csv|txt|svg|py)$ + - id: pretty-format-json + args: ["--autofix", "--no-ensure-ascii", "--no-sort-keys"] + - id: requirements-txt-fixer + - id: trailing-whitespace + args: [--markdown-linebreak-ext=md] + exclude: \.(html|svg)$ + + - repo: https://github.com/codespell-project/codespell + rev: v2.2.6 + additional_dependencies: + - tomli + hooks: + - id: codespell diff --git a/MANIFEST.in b/MANIFEST.in index c2344ed..1e5bf97 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -2,4 +2,4 @@ graft src graft littlefs include README.rst global-exclude src *.so __pycache__/* -global-exclude *.py[cod] \ No newline at end of file +global-exclude *.py[cod] diff --git a/ci/build-wheels.sh b/ci/build-wheels.sh index bd21b39..6190fdb 100755 --- a/ci/build-wheels.sh +++ b/ci/build-wheels.sh @@ -31,4 +31,4 @@ for PYBIN in /opt/python/*/bin/; do fi "${PYBIN}/pip" install littlefs-python --no-index -f /io/wheels "${PYBIN}/py.test" /io/test -done \ No newline at end of file +done diff --git a/ci/download_release_files.py b/ci/download_release_files.py index 4eccbe9..aaf9299 100644 --- a/ci/download_release_files.py +++ b/ci/download_release_files.py @@ -2,28 +2,27 @@ import os HERE = os.path.dirname(__file__) -DIST_DIR = os.path.abspath(os.path.join(HERE, '..', 'dist')) -REPO = 'jrast/littlefs-python' +DIST_DIR = os.path.abspath(os.path.join(HERE, "..", "dist")) +REPO = "jrast/littlefs-python" if not os.path.exists(DIST_DIR): os.mkdir(DIST_DIR) -resp = requests.get('https://api.github.com/repos/%s/releases/latest' % REPO) +resp = requests.get("https://api.github.com/repos/%s/releases/latest" % REPO) if resp.status_code != 200: - raise RuntimeError('Github API call failed!') + raise RuntimeError("Github API call failed!") data = resp.json() -print('Release Tag:', data['tag_name']) +print("Release Tag:", data["tag_name"]) -print('Assets:') -num_assets = len(data['assets']) -for nr, e in enumerate(data['assets'], 1): - print('(%2d/%2d) Downloading %s' % (nr, num_assets, e['name'])) - r = requests.get(e['browser_download_url'], allow_redirects=True) +print("Assets:") +num_assets = len(data["assets"]) +for nr, e in enumerate(data["assets"], 1): + print("(%2d/%2d) Downloading %s" % (nr, num_assets, e["name"])) + r = requests.get(e["browser_download_url"], allow_redirects=True) if r.status_code != 200: - raise RuntimeError('Downloading %s failed!' % e['name']) - with open(os.path.join(DIST_DIR, e['name']), 'wb') as fh: + raise RuntimeError("Downloading %s failed!" % e["name"]) + with open(os.path.join(DIST_DIR, e["name"]), "wb") as fh: fh.write(r.content) - diff --git a/docs/api/index.rst b/docs/api/index.rst index 4cb1ed1..4a3c670 100644 --- a/docs/api/index.rst +++ b/docs/api/index.rst @@ -32,6 +32,3 @@ littlefs.lfs module .. automodule:: littlefs.lfs :members: :undoc-members: - - - diff --git a/docs/cli.rst b/docs/cli.rst index 627fb33..09d9470 100644 --- a/docs/cli.rst +++ b/docs/cli.rst @@ -3,7 +3,7 @@ Command Line Interface ====================== -.. argparse:: +.. argparse:: :module: littlefs.__main__ :func: get_parser :prog: littlefs-python diff --git a/docs/doc8.ini b/docs/doc8.ini index d9c0ce9..101ec30 100644 --- a/docs/doc8.ini +++ b/docs/doc8.ini @@ -1,3 +1,3 @@ [doc8] -max-line-length=99 \ No newline at end of file +max-line-length=99 diff --git a/docs/requirements.txt b/docs/requirements.txt index f079e71..29842e2 100644 --- a/docs/requirements.txt +++ b/docs/requirements.txt @@ -1,2 +1,2 @@ sphinx~=7.2 -sphinx-argparse~=0.4.0 \ No newline at end of file +sphinx-argparse~=0.4.0 diff --git a/mypy.ini b/mypy.ini index 7d6b3e8..32e726a 100644 --- a/mypy.ini +++ b/mypy.ini @@ -2,4 +2,4 @@ check_untyped_defs = True [mypy-pytest.*] -ignore_missing_imports = True \ No newline at end of file +ignore_missing_imports = True diff --git a/requirements.txt b/requirements.txt index e206208..920fb71 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,2 +1,2 @@ +pytest>=4.0.0 tox>=3.14.0 -pytest>=4.0.0 \ No newline at end of file diff --git a/src/littlefs/__init__.py b/src/littlefs/__init__.py index 48f1e08..2b71f29 100644 --- a/src/littlefs/__init__.py +++ b/src/littlefs/__init__.py @@ -53,10 +53,11 @@ if TYPE_CHECKING: from .lfs import LFSStat + class LittleFS: """Littlefs file system""" - def __init__(self, context:Optional['UserContext']=None, mount=True, **kwargs) -> None: + def __init__(self, context: Optional["UserContext"] = None, mount=True, **kwargs) -> None: self.cfg = lfs.LFSConfig(context=context, **kwargs) self.fs = lfs.LFSFilesystem() @@ -72,7 +73,7 @@ def block_count(self) -> int: return self.fs.block_count @property - def context(self) -> 'UserContext': + def context(self) -> "UserContext": """User context of the file system""" return self.cfg.user_context @@ -102,18 +103,12 @@ def fs_grow(self, block_count: int) -> int: return lfs.fs_grow(self.fs, block_count) - def fs_stat(self) -> 'LFSFSStat': + def fs_stat(self) -> "LFSFSStat": """Get the status of the filesystem""" return lfs.fs_stat(self.fs) def open( - self, - fname: str, - mode='r', - buffering: int = -1, - encoding: str = None, - errors: str = None, - newline: str = None + self, fname: str, mode="r", buffering: int = -1, encoding: str = None, errors: str = None, newline: str = None ) -> IO: """Open a file. @@ -174,25 +169,17 @@ def open( exclusive_modes = (creating, reading, writing, appending) if sum(int(m) for m in exclusive_modes) > 1: - raise ValueError( - "must have exactly one of create/read/write/append mode" - ) + raise ValueError("must have exactly one of create/read/write/append mode") if binary: if encoding is not None: - raise ValueError( - "binary mode doesn't take an encoding argument" - ) + raise ValueError("binary mode doesn't take an encoding argument") if errors is not None: - raise ValueError( - "binary mode doesn't take an errors argument" - ) + raise ValueError("binary mode doesn't take an errors argument") if newline is not None: - raise ValueError( - "binary mode doesn't take a newline argument" - ) + raise ValueError("binary mode doesn't take a newline argument") if buffering == 1: msg = ( @@ -244,13 +231,7 @@ def open( if binary: return buffered - wrapped = io.TextIOWrapper( - buffered, - encoding, - errors, - newline, - line_buffering - ) + wrapped = io.TextIOWrapper(buffered, encoding, errors, newline, line_buffering) return wrapped @@ -266,7 +247,7 @@ def removeattr(self, path: str, typ: Union[str, bytes, int]) -> None: typ = _typ_to_uint8(typ) lfs.removeattr(self.fs, path, typ) - def listdir(self, path='.') -> List[str]: + def listdir(self, path=".") -> List[str]: """List directory content List the content of a directory. This function uses :meth:`scandir` @@ -290,10 +271,10 @@ def mkdir(self, path: str) -> int: def makedirs(self, name: str, exist_ok=False): """Recursive directory creation function.""" - parts = [p for p in name.split('/') if p] - current_name = '' + parts = [p for p in name.split("/") if p] + current_name = "" for nr, part in enumerate(parts): - current_name += '/%s' % part + current_name += "/%s" % part try: self.mkdir(current_name) except FileExistsError as e: @@ -341,13 +322,13 @@ def removedirs(self, name): function tries to recursively remove all parent directories which are also empty. """ - parts = name.split('/') + parts = name.split("/") while parts: try: - name = '/'.join(parts) + name = "/".join(parts) if not name: break - self.remove('/'.join(parts)) + self.remove("/".join(parts)) except errors.LittleFSError as e: if e.code == LittleFSError.Error.LFS_ERR_NOTEMPTY: break @@ -365,17 +346,17 @@ def rmdir(self, path: str) -> int: """ return self.remove(path) - def scandir(self, path='.') -> Iterator['LFSStat']: + def scandir(self, path=".") -> Iterator["LFSStat"]: """List directory content""" dh = lfs.dir_open(self.fs, path) info = lfs.dir_read(self.fs, dh) while info: - if info.name not in ['.', '..']: + if info.name not in [".", ".."]: yield info info = lfs.dir_read(self.fs, dh) lfs.dir_close(self.fs, dh) - def stat(self, path: str) -> 'LFSStat': + def stat(self, path: str) -> "LFSStat": """Get the status of a file or directory""" return lfs.stat(self.fs, path) @@ -408,7 +389,7 @@ def walk(self, top: str) -> Iterator[Tuple[str, List[str], List[str]]]: yield top, dirs, files for dirname in dirs: - newtop = '/'.join((top, dirname)).replace('//', '/') + newtop = "/".join((top, dirname)).replace("//", "/") yield from self.walk(newtop) @@ -487,13 +468,14 @@ def flush(self): super().flush() lfs.file_sync(self.fs, self.fh) + def _typ_to_uint8(typ): try: out = ord(typ) except TypeError: out = int(typ) - if not(0 <= out <= 255): + if not (0 <= out <= 255): raise ValueError(f"type must be in range [0, 255]") return out diff --git a/src/littlefs/__main__.py b/src/littlefs/__main__.py index 9d8b711..2be5a45 100644 --- a/src/littlefs/__main__.py +++ b/src/littlefs/__main__.py @@ -19,6 +19,7 @@ def _fs_from_args(args: argparse.Namespace) -> LittleFS: name_max=args.name_max, ) + def size_parser(size_str): """Parse filesystem / block size in different formats""" size_str = str(size_str).lower() @@ -154,22 +155,16 @@ def get_parser(): ), # formatter_class=argparse.RawTextHelpFormatter, ) - parser.add_argument('--version', action='version', version=__version__) + parser.add_argument("--version", action="version", version=__version__) common_parser = argparse.ArgumentParser(add_help=False) common_parser.add_argument("-v", "--verbose", action="count", default=0) - common_parser.add_argument( - "--block-size", type=size_parser, required=True, help="LittleFS block size" - ) - common_parser.add_argument( - "--name-max", type=size_parser, default=255, help="LittleFS max file path length." - ) + common_parser.add_argument("--block-size", type=size_parser, required=True, help="LittleFS block size") + common_parser.add_argument("--name-max", type=size_parser, default=255, help="LittleFS max file path length.") group = common_parser.add_mutually_exclusive_group(required=True) group.add_argument("--block-count", type=int, help="LittleFS block count") group.add_argument("--fs-size", type=size_parser, help="LittleFS filesystem size") - common_parser.add_argument( - "--image", type=pathlib.Path, required=True, help="LittleFS filesystem image" - ) + common_parser.add_argument("--image", type=pathlib.Path, required=True, help="LittleFS filesystem image") subparsers = parser.add_subparsers(required=True, title="Available Commands", dest="command") diff --git a/src/littlefs/context.py b/src/littlefs/context.py index 22374b2..d697e77 100644 --- a/src/littlefs/context.py +++ b/src/littlefs/context.py @@ -1,17 +1,18 @@ import logging import typing -import ctypes +import ctypes if typing.TYPE_CHECKING: from .lfs import LFSConfig + class UserContext: """Basic User Context Implementation""" def __init__(self, buffsize: int) -> None: self.buffer = bytearray([0xFF] * buffsize) - def read(self, cfg: 'LFSConfig', block: int, off: int, size: int) -> bytearray: + def read(self, cfg: "LFSConfig", block: int, off: int, size: int) -> bytearray: """read data Parameters @@ -25,12 +26,12 @@ def read(self, cfg: 'LFSConfig', block: int, off: int, size: int) -> bytearray: size : int Number of bytes to read. """ - logging.getLogger(__name__).debug('LFS Read : Block: %d, Offset: %d, Size=%d' % (block, off, size)) + logging.getLogger(__name__).debug("LFS Read : Block: %d, Offset: %d, Size=%d" % (block, off, size)) start = block * cfg.block_size + off end = start + size return self.buffer[start:end] - def prog(self, cfg: 'LFSConfig', block: int, off: int, data: bytes) -> int: + def prog(self, cfg: "LFSConfig", block: int, off: int, data: bytes) -> int: """program data Parameters @@ -44,13 +45,13 @@ def prog(self, cfg: 'LFSConfig', block: int, off: int, data: bytes) -> int: data : bytes Data to write """ - logging.getLogger(__name__).debug('LFS Prog : Block: %d, Offset: %d, Data=%r' % (block, off, data)) + logging.getLogger(__name__).debug("LFS Prog : Block: %d, Offset: %d, Data=%r" % (block, off, data)) start = block * cfg.block_size + off end = start + len(data) self.buffer[start:end] = data return 0 - def erase(self, cfg: 'LFSConfig', block: int) -> int: + def erase(self, cfg: "LFSConfig", block: int) -> int: """Erase a block Parameters @@ -60,13 +61,13 @@ def erase(self, cfg: 'LFSConfig', block: int) -> int: block : int Block number to read """ - logging.getLogger(__name__).debug('LFS Erase: Block: %d' % block) + logging.getLogger(__name__).debug("LFS Erase: Block: %d" % block) start = block * cfg.block_size end = start + cfg.block_size self.buffer[start:end] = [0xFF] * cfg.block_size return 0 - def sync(self, cfg: 'LFSConfig') -> int: + def sync(self, cfg: "LFSConfig") -> int: """Sync cached data Parameters @@ -77,26 +78,29 @@ def sync(self, cfg: 'LFSConfig') -> int: return 0 - - -try: - import win32file +try: + import win32file except ImportError: win32file = None + class UserContextWinDisk(UserContext): """Windows disk/file context""" - def __init__(self, disk_path:str) -> None: - self.device = None # + def __init__(self, disk_path: str) -> None: + self.device = None # # if the user does not have the pywin if win32file == None: - raise ImportError("Unable to import 'win32file'. This module is required for Windows-specific functionality. Please ensure you are running on a Windows platform or install 'pywin32' using: 'pip install pywin32'.") - self.device = win32file.CreateFile(disk_path, win32file.GENERIC_READ, win32file.FILE_SHARE_READ, None, win32file.OPEN_EXISTING, 0, None) + raise ImportError( + "Unable to import 'win32file'. This module is required for Windows-specific functionality. Please ensure you are running on a Windows platform or install 'pywin32' using: 'pip install pywin32'." + ) + self.device = win32file.CreateFile( + disk_path, win32file.GENERIC_READ, win32file.FILE_SHARE_READ, None, win32file.OPEN_EXISTING, 0, None + ) if self.device == win32file.INVALID_HANDLE_VALUE: raise IOError("Could not open disk %s" % disk_path) - def read(self, cfg: 'LFSConfig', block: int, off: int, size: int) -> bytearray: + def read(self, cfg: "LFSConfig", block: int, off: int, size: int) -> bytearray: """read data Parameters @@ -110,17 +114,17 @@ def read(self, cfg: 'LFSConfig', block: int, off: int, size: int) -> bytearray: size : int Number of bytes to read. """ - logging.getLogger(__name__).debug('LFS Read : Block: %d, Offset: %d, Size=%d' % (block, off, size)) + logging.getLogger(__name__).debug("LFS Read : Block: %d, Offset: %d, Size=%d" % (block, off, size)) start = block * cfg.block_size + off - + win32file.SetFilePointer(self.device, start, win32file.FILE_BEGIN) buffer = ctypes.create_string_buffer(size) win32file.ReadFile(self.device, buffer) # store the data in the buffer and close the buffer data = buffer.raw return data - - def prog(self, cfg: 'LFSConfig', block: int, off: int, data: bytes) -> int: + + def prog(self, cfg: "LFSConfig", block: int, off: int, data: bytes) -> int: """program data Parameters @@ -134,14 +138,14 @@ def prog(self, cfg: 'LFSConfig', block: int, off: int, data: bytes) -> int: data : bytes Data to write """ - logging.getLogger(__name__).debug('LFS Prog : Block: %d, Offset: %d, Data=%r' % (block, off, data)) + logging.getLogger(__name__).debug("LFS Prog : Block: %d, Offset: %d, Data=%r" % (block, off, data)) start = block * cfg.block_size + off - + win32file.SetFilePointer(self.device, start, win32file.FILE_BEGIN) win32file.WriteFile(self.device, data) return 0 - - def erase(self, cfg: 'LFSConfig', block: int) -> int: + + def erase(self, cfg: "LFSConfig", block: int) -> int: """Erase a block Parameters @@ -151,17 +155,17 @@ def erase(self, cfg: 'LFSConfig', block: int) -> int: block : int Block number to read """ - logging.getLogger(__name__).debug('LFS Erase: Block: %d' % block) + logging.getLogger(__name__).debug("LFS Erase: Block: %d" % block) start = block * cfg.block_size - + win32file.SetFilePointer(self.device, start, win32file.FILE_BEGIN) win32file.WriteFile(self.device, [0xFF] * cfg.block_size) return 0 - - def sync(self, cfg: 'LFSConfig') -> int: + + def sync(self, cfg: "LFSConfig") -> int: win32file.FlushFileBuffers(self.device) return 0 - + def __del__(self): - if self.device != None : - win32file.CloseHandle(self.device) \ No newline at end of file + if self.device != None: + win32file.CloseHandle(self.device) diff --git a/src/littlefs/errors.py b/src/littlefs/errors.py index a93db4e..66c70e9 100644 --- a/src/littlefs/errors.py +++ b/src/littlefs/errors.py @@ -28,13 +28,10 @@ def name(self) -> str: try: return self.Error(self.code).name except ValueError: - return 'ERR_UNKNOWN' + return "ERR_UNKNOWN" def __repr__(self) -> str: - return '<%s(%d)>' % ( - self.__class__.__name__, - self.code - ) + return "<%s(%d)>" % (self.__class__.__name__, self.code) def __str__(self) -> str: - return 'LittleFSError %d: %s' % (self.code, self.name) + return "LittleFSError %d: %s" % (self.code, self.name) diff --git a/src/littlefs/lfs.pyi b/src/littlefs/lfs.pyi index bb30e24..b731c3d 100644 --- a/src/littlefs/lfs.pyi +++ b/src/littlefs/lfs.pyi @@ -118,4 +118,3 @@ def dir_close(fs: LFSFilesystem, dh: LFSDirectory) -> int: ... def dir_read(fs: LFSFilesystem, dh: LFSDirectory) -> LFSStat: ... def dir_tell(fs: LFSFilesystem, dh: LFSDirectory) -> int: ... def dir_rewind(fs: LFSFilesystem, dh: LFSDirectory) -> int: ... - diff --git a/src/littlefs/lfs.pyx b/src/littlefs/lfs.pyx index bb1d367..c47e91f 100644 --- a/src/littlefs/lfs.pyx +++ b/src/littlefs/lfs.pyx @@ -483,4 +483,3 @@ def dir_tell(LFSFilesystem fs, LFSDirectory dh): def dir_rewind(LFSFilesystem fs, LFSDirectory dh): return _raise_on_error(lfs_dir_rewind(&fs._impl, &dh._impl)) - diff --git a/test/lfs/conftest.py b/test/lfs/conftest.py index 986b947..9d6df12 100644 --- a/test/lfs/conftest.py +++ b/test/lfs/conftest.py @@ -1,26 +1,30 @@ import pytest from littlefs import lfs -@pytest.fixture(scope='function') + +@pytest.fixture(scope="function") def fs(): """Littlefs filesystem fixture""" fs = lfs.LFSFilesystem() yield fs -@pytest.fixture(scope='function') + +@pytest.fixture(scope="function") def cfg(): """Littlefs configuration fixture""" cfg = lfs.LFSConfig(block_size=128, block_count=4) yield cfg -@pytest.fixture(scope='function') + +@pytest.fixture(scope="function") def formated_fs(fs, cfg): """fixutre for a formatted filesystem""" lfs.format(fs, cfg) yield fs -@pytest.fixture(scope='function') + +@pytest.fixture(scope="function") def mounted_fs(formated_fs, cfg): """fixture for a formatted and mounted filesystem""" lfs.mount(formated_fs, cfg) - yield formated_fs \ No newline at end of file + yield formated_fs diff --git a/test/lfs/test_dir_functions.py b/test/lfs/test_dir_functions.py index 07ae169..7a53e0b 100644 --- a/test/lfs/test_dir_functions.py +++ b/test/lfs/test_dir_functions.py @@ -2,40 +2,40 @@ from littlefs import lfs -@pytest.fixture(scope='function') +@pytest.fixture(scope="function") def testfs(mounted_fs): - lfs.mkdir(mounted_fs, 'testdir') + lfs.mkdir(mounted_fs, "testdir") yield mounted_fs def test_mkdir(mounted_fs): - assert lfs.mkdir(mounted_fs, 'directory') == 0 + assert lfs.mkdir(mounted_fs, "directory") == 0 def test_dir_open(testfs): - dh = lfs.dir_open(testfs, 'testdir') + dh = lfs.dir_open(testfs, "testdir") assert dh != None def test_dir_close(testfs): - dh = lfs.dir_open(testfs, 'testdir') + dh = lfs.dir_open(testfs, "testdir") lfs.dir_close(testfs, dh) def test_dir_read(testfs): - dh = lfs.dir_open(testfs, '') + dh = lfs.dir_open(testfs, "") info = lfs.dir_read(testfs, dh) - assert info.name == '.' + assert info.name == "." info = lfs.dir_read(testfs, dh) - assert info.name == '..' + assert info.name == ".." info = lfs.dir_read(testfs, dh) - assert info.name == 'testdir' + assert info.name == "testdir" def test_dir_read_overflow(testfs): - dh = lfs.dir_open(testfs, '') + dh = lfs.dir_open(testfs, "") # There are three directories: ., .., testdir for _ in range(3): @@ -48,8 +48,8 @@ def test_dir_read_overflow(testfs): def test_dir_rewind(testfs): - dirs = ['.', '..', 'testdir'] - dh = lfs.dir_open(testfs, '') + dirs = [".", "..", "testdir"] + dh = lfs.dir_open(testfs, "") for name in dirs: info = lfs.dir_read(testfs, dh) diff --git a/test/lfs/test_file_functions.py b/test/lfs/test_file_functions.py index 4c5d920..8da9540 100644 --- a/test/lfs/test_file_functions.py +++ b/test/lfs/test_file_functions.py @@ -4,38 +4,38 @@ def test_file_open(mounted_fs): - fh = lfs.file_open(mounted_fs, 'test.txt', 'w') + fh = lfs.file_open(mounted_fs, "test.txt", "w") def test_file_open_wb(mounted_fs): - fh = lfs.file_open(mounted_fs, 'test.txt', 'wb') + fh = lfs.file_open(mounted_fs, "test.txt", "wb") def test_file_open_a(mounted_fs): - fh = lfs.file_open(mounted_fs, 'test.txt', 'w') - lfs.file_write(mounted_fs, fh, b'0123456789') + fh = lfs.file_open(mounted_fs, "test.txt", "w") + lfs.file_write(mounted_fs, fh, b"0123456789") lfs.file_close(mounted_fs, fh) - fh = lfs.file_open(mounted_fs, 'test.txt', 'a') - lfs.file_write(mounted_fs, fh, b'0123456789') + fh = lfs.file_open(mounted_fs, "test.txt", "a") + lfs.file_write(mounted_fs, fh, b"0123456789") lfs.file_close(mounted_fs, fh) - info = lfs.stat(mounted_fs, 'test.txt') + info = lfs.stat(mounted_fs, "test.txt") assert info.size == 20 def test_file_open_flags(mounted_fs): flags = lfs.LFSFileFlag.wronly | lfs.LFSFileFlag.creat - fh = lfs.file_open(mounted_fs, 'test.txt', flags) + fh = lfs.file_open(mounted_fs, "test.txt", flags) def test_file_open_exist(mounted_fs): - fh = lfs.file_open(mounted_fs, 'test.txt', 'wb') - lfs.file_write(mounted_fs, fh, b'0123456789') + fh = lfs.file_open(mounted_fs, "test.txt", "wb") + lfs.file_write(mounted_fs, fh, b"0123456789") lfs.file_close(mounted_fs, fh) with pytest.raises(LittleFSError) as excinfo: - fh = lfs.file_open(mounted_fs, 'test.txt', 'x') + fh = lfs.file_open(mounted_fs, "test.txt", "x") assert excinfo.value.code == LittleFSError.Error.LFS_ERR_EXIST @@ -43,57 +43,57 @@ def test_file_open_exist(mounted_fs): def test_file_open_noent(mounted_fs): with pytest.raises(LittleFSError) as excinfo: flags = lfs.LFSFileFlag.rdonly - fh = lfs.file_open(mounted_fs, 'test.txt', flags) + fh = lfs.file_open(mounted_fs, "test.txt", flags) assert excinfo.value.code == LittleFSError.Error.LFS_ERR_NOENT def test_file_open_isdir(mounted_fs): - lfs.mkdir(mounted_fs, 'testdir') + lfs.mkdir(mounted_fs, "testdir") with pytest.raises(LittleFSError) as excinfo: - fh = lfs.file_open(mounted_fs, 'testdir', "r") + fh = lfs.file_open(mounted_fs, "testdir", "r") assert excinfo.value.code == LittleFSError.Error.LFS_ERR_ISDIR def test_file_close(mounted_fs): - fh = lfs.file_open(mounted_fs, 'test.txt', 'w') + fh = lfs.file_open(mounted_fs, "test.txt", "w") lfs.file_close(mounted_fs, fh) def test_file_sync(mounted_fs): - fh = lfs.file_open(mounted_fs, 'test.txt', 'w') + fh = lfs.file_open(mounted_fs, "test.txt", "w") lfs.file_sync(mounted_fs, fh) def test_file_read(mounted_fs): - fh = lfs.file_open(mounted_fs, 'test.txt', 'w') - lfs.file_write(mounted_fs, fh, b'0123456789') + fh = lfs.file_open(mounted_fs, "test.txt", "w") + lfs.file_write(mounted_fs, fh, b"0123456789") lfs.file_close(mounted_fs, fh) - fh = lfs.file_open(mounted_fs, 'test.txt', 'r') + fh = lfs.file_open(mounted_fs, "test.txt", "r") data = lfs.file_read(mounted_fs, fh, 10) - assert data == b'0123456789' + assert data == b"0123456789" def test_file_read_rb(mounted_fs): - fh = lfs.file_open(mounted_fs, 'test.txt', 'w') - lfs.file_write(mounted_fs, fh, b'0123456789') + fh = lfs.file_open(mounted_fs, "test.txt", "w") + lfs.file_write(mounted_fs, fh, b"0123456789") lfs.file_close(mounted_fs, fh) - fh = lfs.file_open(mounted_fs, 'test.txt', 'rb') + fh = lfs.file_open(mounted_fs, "test.txt", "rb") data = lfs.file_read(mounted_fs, fh, 10) - assert data == b'0123456789' + assert data == b"0123456789" def test_file_write(mounted_fs): - fh = lfs.file_open(mounted_fs, 'test.txt', 'w') - lfs.file_write(mounted_fs, fh, b'0123456789') + fh = lfs.file_open(mounted_fs, "test.txt", "w") + lfs.file_write(mounted_fs, fh, b"0123456789") def test_file_seek(mounted_fs): - fh = lfs.file_open(mounted_fs, 'test.txt', 'w') + fh = lfs.file_open(mounted_fs, "test.txt", "w") # Seek whenece: # 0: Absolute # 1: Relative to Current Position @@ -103,20 +103,20 @@ def test_file_seek(mounted_fs): def test_file_truncate(mounted_fs): - fh = lfs.file_open(mounted_fs, 'test.txt', 'w') + fh = lfs.file_open(mounted_fs, "test.txt", "w") assert lfs.file_truncate(mounted_fs, fh, 10) == 0 def test_file_tell(mounted_fs): - fh = lfs.file_open(mounted_fs, 'test.txt', 'w') + fh = lfs.file_open(mounted_fs, "test.txt", "w") assert lfs.file_tell(mounted_fs, fh) == 0 def test_file_rewind(mounted_fs): - fh = lfs.file_open(mounted_fs, 'test.txt', 'w') + fh = lfs.file_open(mounted_fs, "test.txt", "w") assert lfs.file_rewind(mounted_fs, fh) == 0 def test_file_size(mounted_fs): - fh = lfs.file_open(mounted_fs, 'test.txt', 'w') + fh = lfs.file_open(mounted_fs, "test.txt", "w") assert lfs.file_size(mounted_fs, fh) == 0 diff --git a/test/lfs/test_fs_functions.py b/test/lfs/test_fs_functions.py index f5c1da6..9db18b9 100644 --- a/test/lfs/test_fs_functions.py +++ b/test/lfs/test_fs_functions.py @@ -31,21 +31,21 @@ def test_unmount(mounted_fs): def test_stat_root_directory(mounted_fs): """Test if stat works""" - stat = lfs.stat(mounted_fs, '/') - assert stat.type == 2, 'Expected a directory type' - assert stat.name == '/' + stat = lfs.stat(mounted_fs, "/") + assert stat.type == 2, "Expected a directory type" + assert stat.name == "/" def test_stat_file(mounted_fs): - fh = lfs.file_open(mounted_fs, 'test.txt', 'w') - lfs.file_write(mounted_fs, fh, b'0123456789') + fh = lfs.file_open(mounted_fs, "test.txt", "w") + lfs.file_write(mounted_fs, fh, b"0123456789") lfs.file_close(mounted_fs, fh) - stat = lfs.stat(mounted_fs, 'test.txt') + stat = lfs.stat(mounted_fs, "test.txt") assert stat.size == 10 assert stat.type == 1 - assert stat.name == 'test.txt' + assert stat.name == "test.txt" def test_fs_stat(mounted_fs): diff --git a/test/test_attr.py b/test/test_attr.py index 5aa0914..29f6125 100644 --- a/test/test_attr.py +++ b/test/test_attr.py @@ -2,11 +2,11 @@ from littlefs import LittleFS, LittleFSError -@pytest.fixture(scope='function') +@pytest.fixture(scope="function") def fs(): fs = LittleFS(block_size=128, block_count=64) - with fs.open('/file.txt', 'w') as fh: - fh.write('Sample Text') + with fs.open("/file.txt", "w") as fh: + fh.write("Sample Text") yield fs @@ -15,12 +15,12 @@ def test_attr(fs): fs.setattr("/file.txt", "f", b"foo") fs.setattr("/file.txt", "b", b"bar") - assert(b"foo" == fs.getattr("/file.txt", "f")) - assert(b"bar" == fs.getattr("/file.txt", "b")) + assert b"foo" == fs.getattr("/file.txt", "f") + assert b"bar" == fs.getattr("/file.txt", "b") fs.removeattr("/file.txt", "f") with pytest.raises(LittleFSError): fs.getattr("/file.txt", "f") # Make sure "b" wasn't impacted - assert(b"bar" == fs.getattr("/file.txt", "b")) + assert b"bar" == fs.getattr("/file.txt", "b") diff --git a/test/test_block_count.py b/test/test_block_count.py index e0c8881..73d2c2c 100644 --- a/test/test_block_count.py +++ b/test/test_block_count.py @@ -9,16 +9,18 @@ def test_block_count_autodetect(): context = UserContext(block_size * block_count) # Create the filesystem with 57 blocks - fs = LittleFS(context=context, - block_size=block_size, - block_count=block_count, - ) + fs = LittleFS( + context=context, + block_size=block_size, + block_count=block_count, + ) assert fs.block_count == 57 - fs = LittleFS(context=context, - block_size=block_size, - block_count=0, # infer from superblock - ) + fs = LittleFS( + context=context, + block_size=block_size, + block_count=0, # infer from superblock + ) assert fs.block_count == 57 @@ -35,16 +37,18 @@ def test_fs_stat_block_count_autodetect(): context = UserContext(block_size * block_count) # Create the filesystem with 57 blocks - fs = LittleFS(context=context, - block_size=block_size, - block_count=block_count, - ) + fs = LittleFS( + context=context, + block_size=block_size, + block_count=block_count, + ) assert fs.block_count == 57 - fs = LittleFS(context=context, - block_size=block_size, - block_count=0, # infer from superblock - ) + fs = LittleFS( + context=context, + block_size=block_size, + block_count=0, # infer from superblock + ) # Note: filesystem has to be mounted for fs_stat to work. info = fs.fs_stat() diff --git a/test/test_directories.py b/test/test_directories.py index 890ed21..4010fc1 100644 --- a/test/test_directories.py +++ b/test/test_directories.py @@ -2,67 +2,66 @@ from littlefs import LittleFS -@pytest.fixture(scope='function') +@pytest.fixture(scope="function") def fs(): fs = LittleFS(block_size=128, block_count=64) yield fs def test_listdir(fs): - dirs = fs.listdir('/') + dirs = fs.listdir("/") assert dirs == [] - dirs = fs.listdir('.') + dirs = fs.listdir(".") assert dirs == [] - fs.mkdir('test') - assert fs.listdir('/') == ['test'] + fs.mkdir("test") + assert fs.listdir("/") == ["test"] - fs.mkdir('test/sub') - assert fs.listdir('/') == ['test'] - assert fs.listdir('/test') == ['sub'] + fs.mkdir("test/sub") + assert fs.listdir("/") == ["test"] + assert fs.listdir("/test") == ["sub"] def test_mkdir(fs): - fs.mkdir('/test') - assert 'test' in fs.listdir('/') + fs.mkdir("/test") + assert "test" in fs.listdir("/") - fs.mkdir('./test1') - assert fs.listdir('/') == ['test1', 'test'] + fs.mkdir("./test1") + assert fs.listdir("/") == ["test1", "test"] def test_mkdir_if_dir_exists(fs): - fs.mkdir('test') + fs.mkdir("test") with pytest.raises(FileExistsError) as excinfo: - fs.mkdir('test') - assert '[LittleFSError -17]' in str(excinfo.value) + fs.mkdir("test") + assert "[LittleFSError -17]" in str(excinfo.value) def test_makedirs(fs): # Simple invocation. Here the filesystem contains no folders yet. - fs.makedirs('/dir/sub/subsub') - assert fs.listdir('/') == ['dir'] - assert fs.listdir('/dir') == ['sub'] - assert fs.listdir('/dir/sub') == ['subsub'] + fs.makedirs("/dir/sub/subsub") + assert fs.listdir("/") == ["dir"] + assert fs.listdir("/dir") == ["sub"] + assert fs.listdir("/dir/sub") == ["subsub"] # Create the same folder again. Do not rise if the directory exists. - fs.makedirs('/dir/sub/subsub', exist_ok=True) - assert fs.listdir('/') == ['dir'] - assert fs.listdir('/dir') == ['sub'] - assert fs.listdir('/dir/sub') == ['subsub'] + fs.makedirs("/dir/sub/subsub", exist_ok=True) + assert fs.listdir("/") == ["dir"] + assert fs.listdir("/dir") == ["sub"] + assert fs.listdir("/dir/sub") == ["subsub"] # Create again, but raise if the directory exits with pytest.raises(FileExistsError) as excinfo: - fs.makedirs('/dir/sub/subsub', exist_ok=False) - assert '[LittleFSError -17]' in str(excinfo.value) - assert '/dir/sub/subsub' in str(excinfo.value) - assert fs.listdir('/') == ['dir'] - assert fs.listdir('/dir') == ['sub'] - assert fs.listdir('/dir/sub') == ['subsub'] + fs.makedirs("/dir/sub/subsub", exist_ok=False) + assert "[LittleFSError -17]" in str(excinfo.value) + assert "/dir/sub/subsub" in str(excinfo.value) + assert fs.listdir("/") == ["dir"] + assert fs.listdir("/dir") == ["sub"] + assert fs.listdir("/dir/sub") == ["subsub"] # Create another directory on the third level - fs.makedirs('/dir/sub/abc') - assert fs.listdir('/') == ['dir'] - assert fs.listdir('/dir') == ['sub'] - assert fs.listdir('/dir/sub') == ['abc', 'subsub'] - + fs.makedirs("/dir/sub/abc") + assert fs.listdir("/") == ["dir"] + assert fs.listdir("/dir") == ["sub"] + assert fs.listdir("/dir/sub") == ["abc", "subsub"] diff --git a/test/test_files.py b/test/test_files.py index fb39a6d..9869d6d 100644 --- a/test/test_files.py +++ b/test/test_files.py @@ -2,16 +2,16 @@ from littlefs import LittleFS, FileHandle -@pytest.fixture(scope='function') +@pytest.fixture(scope="function") def fs(): fs = LittleFS(block_size=128, block_count=64) - fs.mkdir('mydir') + fs.mkdir("mydir") - with fs.open('test.txt', 'w') as f: - f.write('1234567890') + with fs.open("test.txt", "w") as f: + f.write("1234567890") - with fs.open('test.bin', 'wb') as f: - contents = bytes.fromhex('11 22 33 44 aa bb cc dd ee ff') + with fs.open("test.bin", "wb") as f: + contents = bytes.fromhex("11 22 33 44 aa bb cc dd ee ff") f.write(contents) yield fs @@ -19,104 +19,102 @@ def fs(): def test_open_notfound(fs): with pytest.raises(FileNotFoundError): - with fs.open('test2.txt') as f: + with fs.open("test2.txt") as f: pass def test_open_isdir(fs): with pytest.raises(IsADirectoryError): - with fs.open('mydir') as f: + with fs.open("mydir") as f: pass def test_open_exists(fs): with pytest.raises(FileExistsError): - with fs.open('test.txt', 'x') as f: + with fs.open("test.txt", "x") as f: pass + def test_open_invalid_mode(fs): with pytest.raises(ValueError) as excinfo: - with fs.open('test.txt', 'c') as fh: + with fs.open("test.txt", "c") as fh: pass - + assert str(excinfo.value) == "invalid mode: 'c'" + def test_open_binary_and_text(fs): with pytest.raises(ValueError) as excinfo: - with fs.open('test.txt', 'bt') as fh: + with fs.open("test.txt", "bt") as fh: pass assert str(excinfo.value) == "can't have text and binary mode at once" def test_bin_read(fs): - with fs.open('test.txt', 'rb') as f: + with fs.open("test.txt", "rb") as f: data = f.read() - assert data == b'1234567890' + assert data == b"1234567890" def test_text_read(fs): - with fs.open('test.txt', 'rt') as f: + with fs.open("test.txt", "rt") as f: data = f.read() - assert data == '1234567890' + assert data == "1234567890" def test_bin_append(fs): - with fs.open('test.txt', 'ab') as f: - f.write(b'1234567890') + with fs.open("test.txt", "ab") as f: + f.write(b"1234567890") - info = fs.stat('test.txt') + info = fs.stat("test.txt") assert info.size == 20 def test_text_encoding(fs): - txt_data = ( - 'abcdefghijklmnopqrstuvwxyz' - 'αβγδεζηθικλμνξοπρστυφχψω' - ) - bin_data = txt_data.encode('utf8') + txt_data = "abcdefghijklmnopqrstuvwxyz" "αβγδεζηθικλμνξοπρστυφχψω" + bin_data = txt_data.encode("utf8") - with fs.open("test2.txt", "w", encoding='utf8') as f: + with fs.open("test2.txt", "w", encoding="utf8") as f: f.write(txt_data) - info = fs.stat('test2.txt') + info = fs.stat("test2.txt") assert info.size == len(bin_data) - with fs.open('test2.txt', 'rb') as f: + with fs.open("test2.txt", "rb") as f: data = f.read() assert data == bin_data - with fs.open('test2.txt', 'r', encoding='utf8') as f: + with fs.open("test2.txt", "r", encoding="utf8") as f: data = f.read() assert data == txt_data offset = 30 - file_offset = len(txt_data[:offset].encode('utf8')) + file_offset = len(txt_data[:offset].encode("utf8")) - with fs.open('test2.txt', 'r', encoding='utf8') as f: + with fs.open("test2.txt", "r", encoding="utf8") as f: f.seek(file_offset) data = f.read(4) - assert data == txt_data[offset:offset+4] + assert data == txt_data[offset : offset + 4] def test_text_lines(fs): fname = "test2.txt" lipsum = ( - 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, \n' - 'sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\n' - 'Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris \n' - 'nisi ut aliquip ex ea commodo consequat.' + "Lorem ipsum dolor sit amet, consectetur adipiscing elit, \n" + "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\n" + "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris \n" + "nisi ut aliquip ex ea commodo consequat." ) - - with fs.open(fname, 'w') as f: + with fs.open(fname, "w") as f: f.write(lipsum) num_lines = 0 - with fs.open(fname, 'r') as f: + with fs.open(fname, "r") as f: for _ in f: num_lines += 1 @@ -124,32 +122,32 @@ def test_text_lines(fs): def test_bin_read_update(fs): - with fs.open('test.bin', 'r+b') as f: + with fs.open("test.bin", "r+b") as f: f.seek(2) a = f.read(2) b = f.read(2) - assert a == bytes.fromhex('33 44') - assert b == bytes.fromhex('aa bb') + assert a == bytes.fromhex("33 44") + assert b == bytes.fromhex("aa bb") assert f.tell() == 6 f.seek(2) f.write(b) f.write(a) - expected = bytes.fromhex('11 22 aa bb 33 44 cc dd ee ff') + expected = bytes.fromhex("11 22 aa bb 33 44 cc dd ee ff") - with fs.open('test.bin', 'rb') as f: + with fs.open("test.bin", "rb") as f: data = f.read() assert data == expected def test_bin_write_update(fs): - contents = bytes.fromhex('11 aa 22 bb 33 cc 44 dd') + contents = bytes.fromhex("11 aa 22 bb 33 cc 44 dd") - with fs.open('test.bin', 'w+b') as f: + with fs.open("test.bin", "w+b") as f: data = f.read() - assert data == b'' + assert data == b"" f.write(contents) f.seek(4) @@ -158,13 +156,13 @@ def test_bin_write_update(fs): def test_bin_append_update(fs): - fname = 'test2.bin' - contents = bytes.fromhex('11 aa 22 bb 33 cc 44 dd') + fname = "test2.bin" + contents = bytes.fromhex("11 aa 22 bb 33 cc 44 dd") - with fs.open(fname, 'wb') as f: + with fs.open(fname, "wb") as f: f.write(contents[0:6]) - with fs.open(fname, 'a+b') as f: + with fs.open(fname, "a+b") as f: f.write(contents[6:]) f.seek(0) @@ -173,7 +171,7 @@ def test_bin_append_update(fs): def test_text_read_update(fs): - with fs.open('test.txt', 'r+') as f: + with fs.open("test.txt", "r+") as f: f.seek(2) a = f.read(2) b = f.read(2) @@ -188,7 +186,7 @@ def test_text_read_update(fs): expected = "1256347890" - with fs.open('test.txt', 'r') as f: + with fs.open("test.txt", "r") as f: data = f.read() assert data == expected @@ -196,7 +194,7 @@ def test_text_read_update(fs): def test_text_write_update(fs): contents = "1a2b3c4d" - with fs.open('test.txt', 'w+') as f: + with fs.open("test.txt", "w+") as f: data = f.read() assert data == "" @@ -207,24 +205,25 @@ def test_text_write_update(fs): def test_text_append_update(fs): - fname = 'test2.txt' + fname = "test2.txt" contents = "1a2b3c4d" - with fs.open(fname, 'w') as f: + with fs.open(fname, "w") as f: f.write(contents[0:6]) - with fs.open(fname, 'a+') as f: + with fs.open(fname, "a+") as f: f.write(contents[6:]) f.seek(0) data = f.read() assert data == contents + def test_text_truncate(fs: LittleFS): - with fs.open('trunc.txt', 'w') as f: - f.write('Some Content') + with fs.open("trunc.txt", "w") as f: + f.write("Some Content") - with fs.open('trunc.txt', 'r+') as f: + with fs.open("trunc.txt", "r+") as f: f.truncate() - assert fs.open('trunc.txt', 'r').read() == '' + assert fs.open("trunc.txt", "r").read() == "" diff --git a/test/test_multiversion.py b/test/test_multiversion.py index c580494..4579206 100644 --- a/test/test_multiversion.py +++ b/test/test_multiversion.py @@ -4,41 +4,44 @@ def create_image(version): fs = LittleFS(block_size=128, block_count=64, disk_version=version) - fs.mkdir('testdir') - with fs.open('file.txt', 'w') as f: - f.write('Sample Content') - + fs.mkdir("testdir") + with fs.open("file.txt", "w") as f: + f.write("Sample Content") + return fs.context.buffer -@pytest.fixture(scope='function') +@pytest.fixture(scope="function") def fs20(): fs = LittleFS(block_size=128, block_count=64, disk_version=0x00020000) - fs.mkdir('mydir') + fs.mkdir("mydir") - with fs.open('test.txt', 'w') as f: - f.write('1234567890') + with fs.open("test.txt", "w") as f: + f.write("1234567890") yield fs -@pytest.fixture(scope='function') + +@pytest.fixture(scope="function") def fs21(): fs = LittleFS(block_size=128, block_count=64, disk_version=0x00020001) - fs.mkdir('mydir') + fs.mkdir("mydir") - with fs.open('test.txt', 'w') as f: - f.write('1234567890') + with fs.open("test.txt", "w") as f: + f.write("1234567890") yield fs + def test_lfs20(fs20): assert fs20.fs_stat().disk_version == 0x00020000 + def test_lfs21(fs21): assert fs21.fs_stat().disk_version == 0x00020001 -@pytest.mark.parametrize('version', [0x00020000, 0x00020001], ids=['FS2.0', 'FS2.1']) +@pytest.mark.parametrize("version", [0x00020000, 0x00020001], ids=["FS2.0", "FS2.1"]) def test_load_images(version): fs = LittleFS(block_size=128, block_count=64, disk_version=0x00020001) fs.context.buffer = create_image(version) @@ -47,9 +50,8 @@ def test_load_images(version): assert stat.disk_version == version - def test_load_incompatible_image(): fs = LittleFS(block_size=128, block_count=64, disk_version=0x00020000) fs.context.buffer = create_image(0x00020001) - with pytest.raises(LittleFSError, match='-22: LFS_ERR_INVAL'): - assert fs.mount() + with pytest.raises(LittleFSError, match="-22: LFS_ERR_INVAL"): + assert fs.mount() diff --git a/test/test_remove_rename.py b/test/test_remove_rename.py index eab8f46..3525e11 100644 --- a/test/test_remove_rename.py +++ b/test/test_remove_rename.py @@ -3,53 +3,53 @@ from littlefs import errors -@pytest.fixture(scope='function') +@pytest.fixture(scope="function") def fs(): fs = LittleFS(block_size=128, block_count=64) - fs.mkdir('/dir') - fs.mkdir('/dir/emptyA') - fs.mkdir('/dir/emptyB') - fs.mkdir('/dir/sub') - with fs.open('/dir/sub/file.txt', 'w') as fh: - fh.write('Sample Text') - with fs.open('/dir/file.txt', 'w') as fh: - fh.write('Sample Text') + fs.mkdir("/dir") + fs.mkdir("/dir/emptyA") + fs.mkdir("/dir/emptyB") + fs.mkdir("/dir/sub") + with fs.open("/dir/sub/file.txt", "w") as fh: + fh.write("Sample Text") + with fs.open("/dir/file.txt", "w") as fh: + fh.write("Sample Text") yield fs def test_remove(fs): # Remove empty directory, without leading slash - fs.remove('/dir/emptyA') + fs.remove("/dir/emptyA") # Remove empty directory, with leading slash - fs.remove('/dir/emptyB/') + fs.remove("/dir/emptyB/") # Remove a file - fs.remove('/dir/file.txt') + fs.remove("/dir/file.txt") # Remove a folder which is not empty with pytest.raises(errors.LittleFSError) as excinfo: - fs.remove('/dir') - assert 'LittleFSError' in str(excinfo.value) + fs.remove("/dir") + assert "LittleFSError" in str(excinfo.value) assert excinfo.value.code == -39 # Remove a file which does not exist with pytest.raises(FileNotFoundError) as excinfo: - fs.remove('/dir/fileB.txt') - assert 'LittleFSError -2' in str(excinfo.value) - assert '/dir/fileB.txt' in str(excinfo.value) + fs.remove("/dir/fileB.txt") + assert "LittleFSError -2" in str(excinfo.value) + assert "/dir/fileB.txt" in str(excinfo.value) # Remove a directory which does not exist (without leading slash) with pytest.raises(FileNotFoundError) as excinfo: - fs.remove('/dir/directroy') - assert 'LittleFSError -2' in str(excinfo.value) - assert '/dir/directroy' in str(excinfo.value) + fs.remove("/dir/thisdirdoesnotexist") + assert "LittleFSError -2" in str(excinfo.value) + assert "/dir/thisdirdoesnotexist" in str(excinfo.value) # Remove a directory which does not exist (with leading slash) with pytest.raises(FileNotFoundError) as excinfo: - fs.remove('/dir/directory/') - assert 'LittleFSError -2' in str(excinfo.value) - assert '/dir/directory/' in str(excinfo.value) + fs.remove("/dir/directory/") + assert "LittleFSError -2" in str(excinfo.value) + assert "/dir/directory/" in str(excinfo.value) def test_remove_recursive(fs): @@ -60,26 +60,26 @@ def test_remove_recursive(fs): def test_removedirs(fs): - fs.removedirs('/dir/sub/file.txt') - assert set(fs.listdir('/dir')) == {'emptyA', 'emptyB', 'file.txt'} - fs.removedirs('/dir/emptyA') - fs.removedirs('/dir/emptyB') - assert set(fs.listdir('/dir')) == {'file.txt'} - fs.removedirs('/dir/file.txt') - assert fs.listdir('/') == [ ] + fs.removedirs("/dir/sub/file.txt") + assert set(fs.listdir("/dir")) == {"emptyA", "emptyB", "file.txt"} + fs.removedirs("/dir/emptyA") + fs.removedirs("/dir/emptyB") + assert set(fs.listdir("/dir")) == {"file.txt"} + fs.removedirs("/dir/file.txt") + assert fs.listdir("/") == [] def test_rename(fs: LittleFS): # File rename - fs.rename('/dir/file.txt', '/dir/file_renamed.txt') - files_in_dir = fs.listdir('/dir') + fs.rename("/dir/file.txt", "/dir/file_renamed.txt") + files_in_dir = fs.listdir("/dir") - assert 'file.txt' not in files_in_dir - assert 'file_renamed.txt' in files_in_dir + assert "file.txt" not in files_in_dir + assert "file_renamed.txt" in files_in_dir # Directory Rename - fs.rename('/dir/sub', '/dir/sub_renamed') - files_in_dir = fs.listdir('/dir') + fs.rename("/dir/sub", "/dir/sub_renamed") + files_in_dir = fs.listdir("/dir") - assert 'sub' not in files_in_dir - assert 'sub_renamed' in files_in_dir + assert "sub" not in files_in_dir + assert "sub_renamed" in files_in_dir diff --git a/test/test_version.py b/test/test_version.py index 5b26c56..53b2f85 100644 --- a/test/test_version.py +++ b/test/test_version.py @@ -1,5 +1,6 @@ import littlefs + def test_version(): """Test if the versions of littlefs can be imported""" assert littlefs.__LFS_VERSION__ == (2, 8) diff --git a/test/test_walk.py b/test/test_walk.py index cc00ea1..517a1e2 100644 --- a/test/test_walk.py +++ b/test/test_walk.py @@ -2,45 +2,42 @@ from littlefs import LittleFS -@pytest.fixture(scope='function') +@pytest.fixture(scope="function") def fs(): fs = LittleFS(block_size=128, block_count=64) - fs.mkdir('/dir') - fs.mkdir('/dir/emptyA') - fs.mkdir('/dir/emptyB') - fs.mkdir('/dir/sub') - with fs.open('/dir/sub/file.txt', 'w') as fh: - fh.write('Sample Text') - with fs.open('/dir/file.txt', 'w') as fh: - fh.write('Sample Text') + fs.mkdir("/dir") + fs.mkdir("/dir/emptyA") + fs.mkdir("/dir/emptyB") + fs.mkdir("/dir/sub") + with fs.open("/dir/sub/file.txt", "w") as fh: + fh.write("Sample Text") + with fs.open("/dir/file.txt", "w") as fh: + fh.write("Sample Text") yield fs def test_walk(fs): data = [] - for root, dirs, files in fs.walk('/'): + for root, dirs, files in fs.walk("/"): data.append((root, dirs, files)) assert data == [ - ('/', ['dir'], []), - ('/dir', ['emptyA', 'emptyB', 'sub'], ['file.txt']), - ('/dir/emptyA', [], []), - ('/dir/emptyB', [], []), - ('/dir/sub', [], ['file.txt']) + ("/", ["dir"], []), + ("/dir", ["emptyA", "emptyB", "sub"], ["file.txt"]), + ("/dir/emptyA", [], []), + ("/dir/emptyB", [], []), + ("/dir/sub", [], ["file.txt"]), ] def test_walk_size(fs): sizes = [] - for root, dirs, files in fs.walk('/'): - sizes.append(( - root, - sum(fs.stat('/'.join((root, name))).size for name in files) - )) + for root, dirs, files in fs.walk("/"): + sizes.append((root, sum(fs.stat("/".join((root, name))).size for name in files))) assert sizes == [ - ('/', 0), - ('/dir', 11), - ('/dir/emptyA', 0), - ('/dir/emptyB', 0), - ('/dir/sub', 11), + ("/", 0), + ("/dir", 11), + ("/dir/emptyA", 0), + ("/dir/emptyB", 0), + ("/dir/sub", 11), ]