Skip to content

Commit

Permalink
Fix style complaints and get coverage back to 100.
Browse files Browse the repository at this point in the history
  • Loading branch information
thebjorn committed Apr 7, 2017
1 parent 574cdcb commit f85b617
Show file tree
Hide file tree
Showing 4 changed files with 109 additions and 53 deletions.
22 changes: 13 additions & 9 deletions dkfileutils/path.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,10 @@ def curdir(cls):

def touch(self, mode=0o666, exist_ok=True):
"""Create this file with the given access mode, if it doesn't exist.
(based on https://github.com/python/cpython/blob/master/Lib/pathlib.py)
Based on:
https://github.com/python/cpython/blob/master/Lib/pathlib.py)
"""
if exist_ok:
# First try to bump modification time
Expand Down Expand Up @@ -252,7 +255,7 @@ def split(self, sep=None, maxsplit=-1):
return os.path.split(self)

def parts(self):
res = re.split(r"\\|/", self)
res = re.split(r"[\\/]", self)
if res and os.path.splitdrive(res[0]) == (res[0], ''):
res[0] += os.path.sep
return res
Expand Down Expand Up @@ -309,16 +312,16 @@ def cd(self):
def chmod(self, *args, **kw):
return os.chmod(self, *args, **kw)

@doc(os.listdir)
def listdir(self):
return [Path(p) for p in os.listdir(self)]

def list(self, filterfn=lambda x: True):
"""Return all direct descendands of directory `self` for which
`filterfn` returns True.
"""
return [self / p for p in self.listdir() if filterfn(self / p)]

@doc(os.listdir)
def listdir(self):
return [Path(p) for p in os.listdir(self)]

def subdirs(self):
"""Return all direct sub-directories.
"""
Expand All @@ -334,7 +337,7 @@ def lstat(self):
return os.lstat(self)

@doc(os.makedirs)
def makedirs(self, path=None, mode=0777):
def makedirs(self, path=None, mode=0o777):
pth = os.path.join(self, path) if path else self
try:
os.makedirs(pth, mode)
Expand All @@ -343,7 +346,7 @@ def makedirs(self, path=None, mode=0777):
return Path(pth)

@doc(os.mkdir)
def mkdir(self, path, mode=0777):
def mkdir(self, path, mode=0o777):
pth = os.path.join(self, path)
os.mkdir(pth, mode)
return Path(pth)
Expand All @@ -353,7 +356,8 @@ def remove(self):
return os.remove(self)

def rm(self, fname=None):
"Remove a file, don't raise exception if file does not exist."
"""Remove a file, don't raise exception if file does not exist.
"""
if fname is not None:
return (self / fname).rm()
try:
Expand Down
41 changes: 18 additions & 23 deletions dkfileutils/which.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,16 +32,11 @@ def is_executable(fname):
return os.stat(fname)[ST_MODE] & (S_IXUSR | S_IXGRP | S_IXOTH)


def _noprint(*_args, **_kwargs):
"""Don't print.
"""
pass


def _listdir(pth):
def _listdir(pth, extensions):
"""Non-raising listdir."""
try:
return os.listdir(pth)
return [fname for fname in os.listdir(pth)
if os.path.splitext(fname)[1] in extensions]
except OSError: # pragma: nocover
pass

Expand All @@ -53,35 +48,35 @@ def _normalize(pth):
def which(filename, interactive=False, verbose=False):
"""Yield all executable files on path that matches `filename`.
"""
exe = os.environ.get('PATHEXT', ['.cmd', '.bat', '.exe', '.com'])
writeln = print if verbose else _noprint
exe = [e.lower() for e in os.environ.get('PATHEXT', '').split(';')]
if sys.platform != 'win32': # pragma: nocover
exe.append('')

name, ext = os.path.splitext(filename)
if ext and (ext in exe): # pragma: nocover
exe = []
has_extension = bool(ext)
if has_extension and ext.lower() not in exe:
raise ValueError("which can only search for executable files")

def match(filenames):
"""Returns the sorted subset of ``filenames`` that matches ``filename``.
"""
res = set()
for fname in filenames:
if fname == filename: # pragma: nocover
res.add(fname)
res.add(fname) # exact match
continue

fn_name, fn_ext = os.path.splitext(fname)
if name == fn_name:
for suffix in exe: # pragma: nocover
# if name + suffix == fname:
if name + fn_ext == fname:
res.add(fname)

fname_name, fname_ext = os.path.splitext(fname)
if fname_name == name and fname_ext.lower() in exe:
res.add(fname)
return sorted(res)

returnset = set()
found = False
for pth in get_path_directories():
writeln('checking pth..')
if verbose: # pragma: nocover
print('checking pth..')

fnames = _listdir(pth)
fnames = _listdir(pth, exe)
if not fnames:
continue

Expand Down
93 changes: 72 additions & 21 deletions tests/test_path.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
import glob
from __future__ import print_function
import os
import stat

Expand Down Expand Up @@ -28,6 +28,39 @@ def test_open():
assert (path.Path(root) / 'b').open().read() == 'hello'


def test_read():
files = """
b: hello
"""
with create_files(files) as root:
assert (path.Path(root) / 'b').read() == 'hello'


def test_write():
files = """
b: hello
"""
with create_files(files) as root:
r = path.Path(root)
bfile = r / 'b'
bfile.write('goodbye')
assert bfile.read() == 'goodbye'
cfile = r / 'c'
cfile.write('world')
assert cfile.read() == 'world'


def test_append():
files = """
b: hello
"""
with create_files(files) as root:
r = path.Path(root)
bfile = r / 'b'
bfile.append(' world')
assert bfile.read() == 'hello world'


def test_iter():
files = """
- .dotfile
Expand Down Expand Up @@ -67,7 +100,7 @@ def test_rmtree():
"""
with create_files(files) as _root:
root = path.Path(_root)
print "FILES:", root.contents()
print("FILES:", root.contents())
# print "LISTALL:", root.listall()
(root / 'a').rmtree('b')
assert root.contents() == [path.Path('e') / 'f.txt']
Expand Down Expand Up @@ -107,17 +140,17 @@ def test_touch_existing():
with create_files(files) as _root:
after = time.time()
assert before < after
print 'before/after', before, after, after-before
print('before/after', before, after, after - before)
root = path.Path(_root)
print "FILES:", root.contents()
print("FILES:", root.contents())
assert 'a' in root
a = root / 'a'
a_before_touch = a.getmtime()
# assert before <= a_before_touch <= after
a.touch()
after_touch = time.time()
a_after_touch = a.getmtime()
print "LOCALS:", locals()
print("LOCALS:", locals())
assert a_before_touch <= a_after_touch
# assert a_after_touch > after
# assert a_after_touch <= after_touch
Expand Down Expand Up @@ -148,6 +181,7 @@ def test_touch_new():
assert b.exists()
assert 'b' in root


def test_parents():
files = """
a:
Expand All @@ -159,8 +193,8 @@ def test_parents():
root = path.Path(_root)
d = root / 'a' / 'b' / 'c' / 'd.txt'
assert d.open().read() == "hello world"
print "PARTS:", d.parts()
print "PARENTS:", d.parents
print("PARTS:", d.parts())
print("PARENTS:", d.parents)
assert d.parents == [
root / 'a' / 'b' / 'c',
root / 'a' / 'b',
Expand Down Expand Up @@ -219,8 +253,9 @@ def test_renames():
with create_files(files) as _root:
root = path.Path(_root)
(root / 'foo').renames('bar')
newfiles = [f.relpath(root).replace('\\', '/') for f in root.glob('**/*')]
print newfiles
newfiles = [f.relpath(root).replace('\\', '/')
for f in root.glob('**/*')]
print(newfiles)
assert 'bar/a/b' in newfiles
assert 'bar/a/c' in newfiles
assert 'bar/e/f/g' in newfiles
Expand All @@ -234,8 +269,8 @@ def test_utime():
with create_files(files) as _root:
root = path.Path(_root)
t = time.time()
stat = root.utime()
assert abs(stat.st_atime - t) < 1
_stat = root.utime()
assert abs(_stat.st_atime - t) < 1


def test_chmod():
Expand All @@ -244,7 +279,7 @@ def test_chmod():
"""
with create_files(files) as _root:
root = path.Path(_root)
(root / 'a').chmod(00400) # only read for only current user
(root / 'a').chmod(0o0400) # only read for only current user
# (root / 'a').chmod(stat.S_IREAD)
if sys.platform == 'win32':
# doesn't appear to be any way for a user to create a file that he
Expand Down Expand Up @@ -275,6 +310,26 @@ def test_unlink():
assert [p.relpath(root) for p in root] == []


def test_rm():
files = """
- a
- b
"""
with create_files(files) as _root:
root = path.Path(_root)
assert {p.relpath(root) for p in root} == {'a', 'b'}

b = root / 'b'
b.rm()
assert [p.relpath(root) for p in root] == ['a']

root.rm('a')
assert [p.relpath(root) for p in root] == []

root.rm('c') # shouldn't raise
assert [p.relpath(root) for p in root] == []


def test_glob():
files = """
- a.py
Expand Down Expand Up @@ -330,7 +385,7 @@ def test_files():
"""
with create_files(files) as _root:
root = path.Path(_root)
print "LISTDIR:", os.listdir('.')
print("LISTDIR:", os.listdir('.'))
assert {d.relpath(root) for d in root.files()} == {
'a.py', 'd', 'f'
}
Expand Down Expand Up @@ -370,9 +425,9 @@ def test_commonprefix():
- f
"""
with create_files(files) as _root:
root = path.Path(_root)
assert root.commonprefix(root) == root
assert root.commonprefix(root/'a.py', root/'d', root/'b'/'a.txt') == root
r = path.Path(_root)
assert r.commonprefix(r) == r
assert r.commonprefix(r/'a.py', r/'d', r/'b'/'a.txt') == r


def test_abspath():
Expand All @@ -391,10 +446,6 @@ def test_basename():
assert os.path.basename('empty') == path.Path('empty').basename()


# def test_commonprefix():
# assert os.path.commonprefix('empty', 'empty') == path.Path('empty').commonprefix('empty')


def test_dirname():
assert os.path.dirname('empty') == path.Path('empty').dirname()

Expand Down Expand Up @@ -543,7 +594,7 @@ def test_cd_contextmanager():
- b
"""
with create_files(files) as _root:
root = path.Path(_root)
# root = path.Path(_root)
assert 'a' in os.listdir('.')
with cd('a'):
assert 'b' in os.listdir('.')
Expand Down
6 changes: 6 additions & 0 deletions tests/test_which.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# -*- coding: utf-8 -*-
import pytest

from dkfileutils import which

Expand All @@ -14,3 +15,8 @@ def test_get_executable():

def test_missing_executable():
assert not which.get_executable('chewbaccascousin')


def test_incorrect_extension():
with pytest.raises(ValueError):
which.get_executable('foo.bar')

0 comments on commit f85b617

Please sign in to comment.