PK!4 Everyone is permitted to copy and distribute verbatim or modified copies of this license document, and changing it is allowed as long as the name is changed. DO WHAT THE FUCK YOU WANT TO BUT IT'S NOT MY FAULT PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. You just DO WHAT THE FUCK YOU WANT TO. 1. Do not hold the author(s), creator(s), developer(s) or distributor(s) liable for anything that happens or goes wrong with your use of the work. PK!simple_test_process/__init__.pyPK!q==simple_test_process/__main__.pyfrom .parseArgs import parseArgs from .runProcess import runProcess import sys def printErr(msg): print(msg, file=sys.stderr) kwargs = parseArgs(*sys.argv[1:]).__dict__ result = runProcess(**kwargs) if result.stdout: print(result.stdout) if result.stderr: printErr(result.stderr) exit(result.code) PK!X"#simple_test_process/fns/__init__.pyfrom .all_ import all_ from .any_ import any_ from .applyOneTo import applyOneTo from .discardFirst import discardFirst from .discardWhen import discardWhen from .endsWith import endsWith from .forEach import forEach from .getAttributeKeys import getAttributeKeys from .getListOfCollectionKeys import getListOfCollectionKeys from .getListOfCollectionValues import getListOfCollectionValues from .iif import iif from .invokeAttr import invokeAttr from .isEmpty import isEmpty from .isLaden import isLaden from .joinWith import joinWith from .keepWhen import keepWhen from .map_ import map_ from .passThrough import passThrough from .prependStr import prependStr from .raise_ import raise_ from .split import split from .toWrittenList import toWrittenList __all__ = [ "all_", "any_", "applyOneTo", "discardFirst", "discardWhen", "endsWith", "forEach", "getAttributeKeys", "getListOfCollectionKeys", "getListOfCollectionValues", "iif", "invokeAttr", "isEmpty", "isLaden", "joinWith", "keepWhen", "map_", "passThrough", "prependStr", "raise_", "split", "toWrittenList", ] PK!]simple_test_process/fns/all_.py# ------- # # Imports # # ------- # from types import SimpleNamespace from .internal.makeGenericCallFn import makeGenericCallFn from .internal.getTypedResult import getTypedResult from .decorators.argIsCallable import argIsCallable # ---- # # Main # # ---- # @argIsCallable def all_(predicate): fnName = all.__name__ callPredicate = makeGenericCallFn(predicate, 3, fnName) def all_inner(collection): typedAll = getTypedResult(collection, typeToAll, fnName) return typedAll(callPredicate, collection) return all_inner # ------- # # Helpers # # ------- # def all_list(callPredicate, aList): for idx, el in enumerate(aList): if not callPredicate(el, idx, aList): return False return True def all_simpleNamespace(callPredicate, aSimpleNamespace): for key, val in aSimpleNamespace.__dict__.items(): if not callPredicate(val, key, aSimpleNamespace): return False return True typeToAll = {list: all_list, SimpleNamespace: all_simpleNamespace} PK!v_simple_test_process/fns/any_.py# ------- # # Imports # # ------- # from .internal.makeGenericCallFn import makeGenericCallFn from .internal.getTypedResult import getTypedResult from .decorators.argIsCallable import argIsCallable # ---- # # Main # # ---- # @argIsCallable def any_(predicate): fnName = any.__name__ callPredicate = makeGenericCallFn(predicate, 3, fnName) def any_inner(collection): typedAny = getTypedResult(collection, typeToAny, fnName) return typedAny(callPredicate, collection) return any_inner # ------- # # Helpers # # ------- # def any_list(callPredicate, aList): for idx, el in enumerate(aList): if callPredicate(el, idx, aList): return True return False typeToAny = {list: any_list} PK!G7`%simple_test_process/fns/applyOneTo.pyfrom .decorators.argIsCallable import argIsCallable @argIsCallable def applyOneTo(callable): def applyOneTo_inner(arg): return callable(arg) return applyOneTo_inner PK!.simple_test_process/fns/decorators/__init__.pyPK![`)gEE3simple_test_process/fns/decorators/argIsCallable.pyfrom inspect import signature import wrapt @wrapt.decorator def argIsCallable(fn, _instance, args, kwargs): if not callable(args[0]): argName = list(signature(fn).parameters)[0] fnName = fn.__name__ raise ValueError(f"{fnName} requires {argName} to be callable") return fn(*args, **kwargs) PK!waII0simple_test_process/fns/decorators/argIsClass.pyfrom inspect import isclass, signature import wrapt @wrapt.decorator def argIsClass(fn, _instance, args, kwargs): if not isclass(args[0]): argName = list(signature(fn).parameters)[0] fnName = fn.__name__ raise ValueError(f"{fnName} requires {argName} to be a class") return fn(*args, **kwargs) PK!dZT3simple_test_process/fns/decorators/argIsInstance.pyfrom inspect import signature from ..internal.raise_ import raise_ import wrapt def argIsInstance(aType, fnName=None): @wrapt.decorator def wrapper(fn, _instance, args, kwargs): nonlocal fnName if not isinstance(args[0], aType): argName = list(signature(fn).parameters)[0] fnName = fnName or fn.__name__ typePassed = type(args[0]) typeName = aType.__name__ raise_( ValueError, f""" {fnName} requires {argName} to be an instance of {typeName} type passed: {typePassed.__name__} """, ) return fn(*args, **kwargs) return wrapper PK!5simple_test_process/fns/decorators/argIsListOfType.pyfrom ordered_set import OrderedSet import wrapt from ..internal.discardWhen import discardWhen from ..internal.get import get from ..internal.getArgName import getArgName from ..internal.isLaden import isLaden from ..internal.isType import isType from ..internal.joinWith import joinWith from ..internal.map_ import map_ from ..internal.passThrough import passThrough from ..internal.raise_ import raise_ from ..internal.sort import sort from ..internal.toType import toType def argIsListOfType(aType): @wrapt.decorator def wrapper(fn, _instance, args, kwargs): typePassed = type(args[0]) fnName = fn.__name__ typeName = aType.__name__ if typePassed is not list: argName = getArgName(fn) raise_( ValueError, f"""\ {fnName} requires {argName} to have the type list type passed: {typePassed.__name__} """, ) invalidTypes = discardWhen(isType(aType))(args[0]) if isLaden(invalidTypes): argName = getArgName(fn) invalidTypeNames = passThrough( invalidTypes, [ map_(toType), OrderedSet, list, map_(get("__name__")), sort, joinWith(", "), ], ) raise_( ValueError, f"""\ {fnName} requires {argName} to be a list of {typeName} invalid types passed: {invalidTypeNames} """, ) return fn(*args, **kwargs) return wrapper PK!E/simple_test_process/fns/decorators/argIsType.pyfrom inspect import signature from ..internal.raise_ import raise_ import wrapt def argIsType(aType): @wrapt.decorator def wrapper(fn, _instance, args, kwargs): typePassed = type(args[0]) if typePassed is not aType: argName = list(signature(fn).parameters)[0] fnName = fn.__name__ typeName = aType.__name__ raise_( ValueError, f""" {fnName} requires {argName} to have the type {typeName} type passed: {typePassed.__name__} """, ) return fn(*args, **kwargs) return wrapper PK!ǥ&&'simple_test_process/fns/discardFirst.py# ------- # # Imports # # ------- # from .internal.getTypedResult import getTypedResult # ---- # # Main # # ---- # def discardFirst(n): fnName = discardFirst.__name__ def discardFirst_inner(collection): discardFn = getTypedResult(collection, typeToDiscardFirst, fnName) return discardFn(n, collection) return discardFirst_inner # ------- # # Helpers # # ------- # def discardFirst_viaSlice(n, sliceAble): return sliceAble[n:] typeToDiscardFirst = {list: discardFirst_viaSlice, str: discardFirst_viaSlice} PK!| ;;&simple_test_process/fns/discardWhen.pyfrom .internal.discardWhen import discardWhen # noqa f401 PK!t8#simple_test_process/fns/endsWith.pyfrom .decorators.argIsType import argIsType @argIsType(str) def endsWith(prefix): @argIsType(str) def endsWith_inner(fullStr): return fullStr.endswith(prefix) return endsWith_inner PK!`c??"simple_test_process/fns/forEach.py# ------- # # Imports # # ------- # from types import SimpleNamespace from .internal.makeGenericCallFn import makeGenericCallFn from .internal.getTypedResult import getTypedResult from .decorators.argIsCallable import argIsCallable # ---- # # Main # # ---- # @argIsCallable def forEach(fn): fnName = forEach.__name__ callFn = makeGenericCallFn(fn, 3, fnName) def forEach_inner(collection): typedForEach = getTypedResult(collection, typeToForEach, fnName) return typedForEach(callFn, collection) return forEach_inner # ------- # # Helpers # # ------- # def forEach_dict(callFn, aDict): for key, val in aDict.items(): callFn(val, key, aDict) return aDict def forEach_list(callFn, aList): for idx, el in enumerate(aList): callFn(el, idx, aList) return aList def forEach_simpleNamespace(callFn, aSimpleNamespace): forEach_dict(callFn, aSimpleNamespace.__dict__) return aSimpleNamespace typeToForEach = { dict: forEach_dict, list: forEach_list, SimpleNamespace: forEach_simpleNamespace, } PK!FF+simple_test_process/fns/getAttributeKeys.pydef getAttributeKeys(something): return something.__dict__.keys() PK!$2simple_test_process/fns/getListOfCollectionKeys.py# ------- # # Imports # # ------- # from types import SimpleNamespace from .internal.getTypedResult import getTypedResult # ---- # # Main # # ---- # def getListOfCollectionKeys(collection): fnName = getListOfCollectionKeys.__name__ typedKeys = getTypedResult(collection, typeToKeys, fnName) return typedKeys(collection) # ------- # # Helpers # # ------- # def getListOfCollectionKeys_dict(aDict): return list(aDict.keys()) def getListOfCollectionKeys_simpleNamespace(aSimpleNamespace): return list(aSimpleNamespace.__dict__.keys()) typeToKeys = { dict: getListOfCollectionKeys_dict, SimpleNamespace: getListOfCollectionKeys_simpleNamespace, } PK!ȇ#4simple_test_process/fns/getListOfCollectionValues.py# ------- # # Imports # # ------- # from types import SimpleNamespace from .internal.getTypedResult import getTypedResult # ---- # # Main # # ---- # def getListOfCollectionValues(collection): fnName = getListOfCollectionValues.__name__ typedValues = getTypedResult(collection, typeToValues, fnName) return typedValues(collection) # ------- # # Helpers # # ------- # def getListOfCollectionValues_dict(aDict): return list(aDict.values()) def getListOfCollectionValues_simpleNamespace(aSimpleNamespace): return list(aSimpleNamespace.__dict__.values()) typeToValues = { dict: getListOfCollectionValues_dict, SimpleNamespace: getListOfCollectionValues_simpleNamespace, } PK!R++simple_test_process/fns/iif.pyfrom .internal.iif import iif # noqa f401 PK!B u/simple_test_process/fns/internal/NotCallable.pyfrom types import SimpleNamespace from .mAssignToSelf import mAssignToSelf from .raise_ import raise_ import os class NotCallable(SimpleNamespace): def __init__(self, fnName, **typeToFn): self._fnName = fnName self._typeToFn = typeToFn mAssignToSelf(typeToFn, self) def __call__(self, *args, **kwargs): availableKeys = list(self._typeToFn.keys()) fnName = self._fnName raise_( TypeError, f""" The utility '{fnName}' is not callable because it needs to know what to return in the case of an empty list. example usage: {fnName}.{availableKeys[0]}([...]) available keys: {os.linesep.join(availableKeys)} """, ) PK!,simple_test_process/fns/internal/__init__.pyPK!F/simple_test_process/fns/internal/discardWhen.py# ------- # # Imports # # ------- # from .getTypedResult import getTypedResult from .makeGenericCallFn import makeGenericCallFn from ..decorators.argIsCallable import argIsCallable # ---- # # Main # # ---- # @argIsCallable def discardWhen(predicate): fnName = discardWhen.__name__ shouldDiscard = makeGenericCallFn(predicate, 3, fnName) def discardWhen_inner(collection): typedDiscardWhen = getTypedResult(collection, typeToDiscardWhen, fnName) return typedDiscardWhen(shouldDiscard, collection) return discardWhen_inner # ------- # # Helpers # # ------- # def discardWhen_list(shouldDiscard, aList): result = [] for idx, el in enumerate(aList): if not shouldDiscard(el, idx, aList): result.append(el) return result def discardWhen_dict(shouldDiscard, aDict): result = {} for key, val in aDict.items(): if shouldDiscard(val, key, aDict): result[key] = val return result typeToDiscardWhen = {list: discardWhen_list, dict: discardWhen_dict} PK!ss'simple_test_process/fns/internal/get.pydef get(attrName): def get_inner(something): return getattr(something, attrName) return get_inner PK!)jj.simple_test_process/fns/internal/getArgName.pyfrom inspect import signature def getArgName(fn, idx=0): return list(signature(fn).parameters)[idx] PK!X2simple_test_process/fns/internal/getFnSignature.pyfrom inspect import signature from .raise_ import raise_ def getFnSignature(fn, callerName): try: return signature(fn) except Exception as e: raise_( ValueError, f"""\ '{callerName}' is unable to get the signature of the passed callable callable passed: {fn.__name__} one reason this could occur is the callable is written in c (e.g. the builtin 'str' callable). """, fromException=e, ) PK!k:simple_test_process/fns/internal/getNumPositionalParams.py# ------- # # Imports # # ------- # from inspect import Parameter from math import inf from .getFnSignature import getFnSignature from .iif import iif # ---- # # Init # # ---- # _nonVarPositionalParamKinds = { Parameter.POSITIONAL_ONLY, Parameter.POSITIONAL_OR_KEYWORD, } # ---- # # Main # # ---- # # # Returns a tuple # numRequired: number of required positional params # numAllowed: number of allowed positional params # def getNumPositionalParams(fn, callerName): sig = getFnSignature(fn, callerName) numAllowed = iif(_hasVarPositionalParam(sig), inf, 0) numRequired = 0 for p in sig.parameters.values(): if p.kind in _nonVarPositionalParamKinds: numAllowed += 1 if p.default is Parameter.empty: numRequired += 1 return (numRequired, numAllowed) # ------- # # Helpers # # ------- # def _hasVarPositionalParam(sig): for p in sig.parameters.values(): if p.kind is Parameter.VAR_POSITIONAL: return True PK!w<2simple_test_process/fns/internal/getTypedResult.py# # README # - I'm not sure what to call this. Its purpose is to centralize the type # validation, minimizing copy/paste. # # ------- # # Imports # # ------- # from .raise_ import raise_ from .get import get # ---- # # Init # # ---- # getName = get("__name__") # # we need a unique object here to ensure the 'typeToSomething' doesn't lead us # to a 'None' value # nothing = object() # ---- # # Main # # ---- # def getTypedResult(value, typeToSomething, fnName): valueType = type(value) result = typeToSomething.get(valueType, nothing) if _isSomething(result): return result supportedTypes = ", ".join(map(getName, typeToSomething.keys())) raise_( ValueError, f"""\ {fnName} doesn't support the type '{valueType.__name__}' supported types: {supportedTypes} """, ) # ------- # # Helpers # # ------- # def _isSomething(x): return x is not nothing PK!;||'simple_test_process/fns/internal/iif.pydef iif(condition, whenTruthy, whenFalsey): if condition: return whenTruthy else: return whenFalsey PK!ws{33+simple_test_process/fns/internal/isLaden.pydef isLaden(aList): return len(aList) is not 0 PK!Ȋ4simple_test_process/fns/internal/isOnlyWhitespace.pyimport re onlyWhitespaceRe = re.compile(r"\s*$") def isOnlyWhitespace(aString): return onlyWhitespaceRe.match(aString) is not None PK!f*simple_test_process/fns/internal/isType.pyfrom inspect import isclass def isType(aType): if not isclass(aType): raise ValueError("isType requires argument 'aType' to pass isclass") def isType_inner(something): return type(something) is aType return isType_inner PK!v_R*++,simple_test_process/fns/internal/joinWith.py# ------- # # Imports # # ------- # from ordered_set import OrderedSet from .getTypedResult import getTypedResult # ---- # # Main # # ---- # def joinWith(separator): def joinWith_inner(collection): typedJoinWith = getTypedResult(collection, typeToJoinWith, "joinWith") return typedJoinWith(separator, collection) return joinWith_inner # ------- # # Helpers # # ------- # def joinWith_iterable(separator, aList): return separator.join(aList) typeToJoinWith = {list: joinWith_iterable, OrderedSet: joinWith_iterable} PK!K1simple_test_process/fns/internal/mAssignToSelf.py# # assigns dict key-values onto self as attributes # return secondaryObj # ** mutates secondaryObj # def mAssignToSelf(aDict, aSelf): for k, v in aDict.items(): setattr(aSelf, k, v) return aSelf PK!K.simple_test_process/fns/internal/makeCallFn.py# ------- # # Imports # # ------- # from math import inf from .returnFirstArgument import returnFirstArgument as identity from .getNumPositionalParams import getNumPositionalParams # ---- # # Main # # ---- # def makeCallFn(fn, callerName, *, modifyResult=identity): (_, allowed) = getNumPositionalParams(fn, callerName) if allowed is inf: return lambda *args, **kwargs: modifyResult(fn(*args, **kwargs)) else: return lambda *args, **kwargs: modifyResult( fn(*args[:allowed], **kwargs) ) PK!T-5simple_test_process/fns/internal/makeGenericCallFn.py# ------- # # Imports # # ------- # from math import inf from .getNumPositionalParams import getNumPositionalParams from .raise_ import raise_ # ---- # # Main # # ---- # def makeGenericCallFn(fn, maxParams, callerName): required, allowed = getNumPositionalParams(fn, callerName) if allowed is inf: allowed = maxParams if required > maxParams: raise_( ValueError, f""" {callerName} can only take functions with up to {maxParams} positional params. The function '{fn.__name__}' requires {required} """, ) return lambda *args, **kwargs: fn(*args[:allowed], **kwargs) PK!mC(simple_test_process/fns/internal/map_.py# ------- # # Imports # # ------- # from types import SimpleNamespace from .makeGenericCallFn import makeGenericCallFn from .getTypedResult import getTypedResult from ..decorators.argIsCallable import argIsCallable # ---- # # Main # # ---- # @argIsCallable def map_(mapperFn): fnName = map_.__name__ callMapperFn = makeGenericCallFn(mapperFn, 3, fnName) def map_inner(collection): typedMap = getTypedResult(collection, typeToMap, fnName) return typedMap(callMapperFn, collection) return map_inner # ------- # # Helpers # # ------- # def map_list(callMapperFn, aList): result = [] for idx, el in enumerate(aList): result.append(callMapperFn(el, idx, aList)) return result def map_simpleNamespace(callMapperFn, aSimpleNamespace): result = SimpleNamespace() for key, val in aSimpleNamespace.__dict__.items(): setattr(result, key, callMapperFn(val, key, aSimpleNamespace)) return result typeToMap = {list: map_list, SimpleNamespace: map_simpleNamespace} PK!yy/simple_test_process/fns/internal/passThrough.pyfrom .reduce import reduce def passThrough(arg, fnList): return reduce(lambda result, fn: fn(result), arg)(fnList) PK!W*simple_test_process/fns/internal/raise_.pyfrom tedent import tedent from .isOnlyWhitespace import isOnlyWhitespace import os def raise_(errorClass, message, *, fromException=None): allLines = message.split(os.linesep) if isOnlyWhitespace(allLines[0]) and isOnlyWhitespace(allLines[-1]): message = tedent(message) err = errorClass(message) if fromException is None: raise err else: raise err from fromException PK!Et*simple_test_process/fns/internal/reduce.py# ------- # # Imports # # ------- # from .makeGenericCallFn import makeGenericCallFn from .getTypedResult import getTypedResult from ..decorators.argIsCallable import argIsCallable # ---- # # Main # # ---- # @argIsCallable def reduce(fn, initial): reducerFn = makeGenericCallFn(fn, 4, "reduce") def reduce_inner(collection): typedReduce = getTypedResult(collection, typeToReduce, "reduce") return typedReduce(reducerFn, initial, collection) return reduce_inner # ------- # # Helpers # # ------- # def reduce_list(reducerFn, initial, aList): result = initial for idx, el in enumerate(aList): result = reducerFn(result, el, idx, aList) return result typeToReduce = {list: reduce_list} PK!pjj7simple_test_process/fns/internal/returnFirstArgument.pyfrom .iif import iif def returnFirstArgument(*args, **kwargs): return iif(len(args), args[0], None) PK!\xx3simple_test_process/fns/internal/sanitizeAscDesc.pyfrom .raise_ import raise_ ascDescSet = {"asc", "desc"} def sanitizeAscDesc(ascOrDesc): sanitized = ascOrDesc.lower() if sanitized not in ascDescSet: raise_( ValueError, f""" ascOrDesc must be either 'asc' or 'desc' (case insensitive) value given: {ascOrDesc} """, ) return sanitized PK!0oo(simple_test_process/fns/internal/sort.py# ------- # # Imports # # ------- # from .getTypedResult import getTypedResult # ---- # # Main # # ---- # def sort(collection): typedSort = getTypedResult(collection, typeToSort, "sort") return typedSort(collection) # ------- # # Helpers # # ------- # def sort_viaSorted(something): return sorted(something) typeToSort = {list: sort_viaSorted} PK!V;22*simple_test_process/fns/internal/toType.pydef toType(something): return type(something) PK!%tt%simple_test_process/fns/invokeAttr.pydef invokeAttr(key): def invokeAttr_inner(obj): return getattr(obj, key)() return invokeAttr_inner PK!¢["simple_test_process/fns/isEmpty.pyfrom types import SimpleNamespace # TODO: make 'isEmpty' generic like the other utils def isEmpty(lenAble): if isinstance(lenAble, SimpleNamespace): return len(lenAble.__dict__) is 0 else: return len(lenAble) is 0 PK!X33"simple_test_process/fns/isLaden.pyfrom .internal.isLaden import isLaden # noqa f401 PK!955#simple_test_process/fns/joinWith.pyfrom .internal.joinWith import joinWith # noqa f401 PK!*xNOO#simple_test_process/fns/keepWhen.py# ------- # # Imports # # ------- # from types import SimpleNamespace from .internal.makeGenericCallFn import makeGenericCallFn from .internal.getTypedResult import getTypedResult from .decorators.argIsCallable import argIsCallable # ---- # # Main # # ---- # @argIsCallable def keepWhen(predicate): fnName = keepWhen.__name__ shouldKeep = makeGenericCallFn(predicate, 3, fnName) def keepWhen_inner(collection): typedKeepWhen = getTypedResult(collection, typeToKeepWhen, fnName) return typedKeepWhen(shouldKeep, collection) return keepWhen_inner # ------- # # Helpers # # ------- # def keepWhen_list(shouldKeep, aList): result = [] for idx, el in enumerate(aList): if shouldKeep(el, idx, aList): result.append(el) return result def keepWhen_dict(shouldKeep, aDict): result = {} for key, val in aDict.items(): if shouldKeep(val, key, aDict): result[key] = val return result def keepWhen_simpleNamespace(shouldKeep, aSimpleNamespace): result = SimpleNamespace() for key, val in aSimpleNamespace.__dict__.items(): if shouldKeep(val, key, aSimpleNamespace): setattr(result, key, val) return result typeToKeepWhen = { list: keepWhen_list, dict: keepWhen_dict, SimpleNamespace: keepWhen_simpleNamespace, } PK!}--simple_test_process/fns/map_.pyfrom .internal.map_ import map_ # noqa f401 PK!F;;&simple_test_process/fns/passThrough.pyfrom .internal.passThrough import passThrough # noqa f401 PK!76E  %simple_test_process/fns/prependStr.pyfrom .decorators.argIsInstance import argIsInstance @argIsInstance(str) def prependStr(prependThis): fnName = prependStr.__name__ @argIsInstance(str, fnName) def prependStr_inner(toThis): return prependThis + toThis return prependStr_inner PK!(11!simple_test_process/fns/raise_.pyfrom .internal.raise_ import raise_ # noqa f401 PK!:ʼtt simple_test_process/fns/split.pydef split(separator): def split_inner(aString): return aString.split(separator) return split_inner PK!i(simple_test_process/fns/toWrittenList.pyfrom .internal.joinWith import joinWith def toWrittenList(aList): andSeparated = aList[-2:] commaSeparated = aList[:-2] commaSeparated.append(joinWith(" and ")(andSeparated)) return joinWith(", ")(commaSeparated) PK!Ό +simple_test_process/onlyKeepGreppedTests.py# ------- # # Imports # # ------- # import re from .fns import all_, any_, forEach, isEmpty as areEmpty, keepWhen, map_ # ---- # # Main # # ---- # # # This method mutates state # def onlyKeepGreppedTests(state, grepArgs): if all_(areEmpty)(grepArgs): return state grepArgs = map_(allToRegexes)(grepArgs) markGreppedTests(state, grepArgs.grepTests) markGreppedSuites(state, grepArgs.grepSuites) markGreppedTestsAndSuites(state, grepArgs.grep) trimNonMarkedTestsAndSuites(state) removeAllMarks(state) return state # ------- # # Helpers # # ------- # def mark(testOrSuite): testOrSuite._keep = True if testOrSuite.parentSuite: mark(testOrSuite.parentSuite) def allToRegexes(grepStrings): return map_(lambda aString: re.compile(aString))(grepStrings) def regexMatches(someString): def regexMatches_inner(aRegex): return bool(aRegex.search(someString)) return regexMatches_inner def markTestIfLabelMatches(regexes): def markTestIfLabelMatches_inner(testOrSuite): if any_(regexMatches(testOrSuite.label))(regexes): mark(testOrSuite) return markTestIfLabelMatches_inner def markGreppedTests(stateOrSuite, grepTests): forEach(markTestIfLabelMatches(grepTests))(stateOrSuite.tests) forEach(lambda suite: markGreppedTests(suite, grepTests))( stateOrSuite.suites ) def markAllTestsIfLabelMatches(regexes): def markAllTestsIfLabelMatches_inner(suite): if any_(regexMatches(suite.label))(regexes): forEach(mark)(suite.tests) return markAllTestsIfLabelMatches_inner def markGreppedSuites(stateOrSuite, grepSuites): forEach(markAllTestsIfLabelMatches(grepSuites))(stateOrSuite.suites) forEach(lambda suite: markGreppedSuites(suite, grepSuites))( stateOrSuite.suites ) def markGreppedTestsAndSuites(stateOrSuite, grep): forEach(markTestIfLabelMatches(grep))(stateOrSuite.tests) forEach(markAllTestsIfLabelMatches(grep))(stateOrSuite.suites) forEach(lambda suite: markGreppedTestsAndSuites(suite, grep))( stateOrSuite.suites ) def isMarked(testOrSuite): return getattr(testOrSuite, "_keep", False) def trimNonMarkedTestsAndSuites(stateOrSuite): stateOrSuite.tests = keepWhen(isMarked)(stateOrSuite.tests) stateOrSuite.suites = keepWhen(isMarked)(stateOrSuite.suites) forEach(trimNonMarkedTestsAndSuites)(stateOrSuite.suites) def removeMark(testOrSuite): delattr(testOrSuite, "_keep") def removeAllMarks(stateOrSuite): forEach(removeMark)(stateOrSuite.tests) forEach(removeMark)(stateOrSuite.suites) forEach(removeAllMarks)(stateOrSuite.suites) PK!&__ simple_test_process/parseArgs.py# ------- # # Imports # # ------- # from case_conversion import camelcase from copy import deepcopy from types import SimpleNamespace as o import case_conversion from .fns import ( getListOfCollectionKeys, map_, passThrough, prependStr, raise_, toWrittenList, ) # ---- # # Init # # ---- # # # case_conversion.dashcase takes more than a single argument so `map_` will pass # it the index and original array which may screw things up # def dashcase(aString): return case_conversion.dashcase(aString) _grepArgs = o(grep=[], grepSuites=[], grepTests=[]) _grepArgsKeys = passThrough( _grepArgs, [getListOfCollectionKeys, map_(dashcase), map_(prependStr("--"))] ) _availableGrepArgsKeys = toWrittenList(_grepArgsKeys) # ---- # # Main # # ---- # # # We can assume the argument order # 0 projectDir # 1 reporter # 2 silent # 3?+ grep | grepSuites | grepTests # # # and we can also assume # - projectDir exists on the file system # - reporter is a non-relative module name # - silent is a string boolean # - grepArgs may or may not exist. Validation is only for debugging purposes # as calling code should be reliable. # # def parseArgs(*args): return o( projectDir=args[0], reporter=args[1], silent=args[2], grepArgs=parseGrepArgs(args[3:]), ) # ------- # # Helpers # # ------- # def parseGrepArgs(grepArgs): result = deepcopy(_grepArgs) i = 0 grepArgsLen = len(grepArgs) while i < grepArgsLen: arg = grepArgs[i] if arg not in _grepArgsKeys: raise_( ValueError, f""" key '{arg}' is invalid available grep keys: {_availableGrepArgsKeys} """, ) grepKey = arg i += 1 if i == grepArgsLen: raise_( ValueError, f""" a value must be given to '{grepKey}' """, ) grepVals = getattr(result, camelcase(grepKey)) grepVals.append(grepArgs[i]) i += 1 return result PK!{b"simple_test_process/runAllTests.py# ------- # # Imports # # ------- # from traceback import format_exc from .fns import forEach # ---- # # Main # # ---- # def runAllTests(stateOrSuite): forEach(runTest)(stateOrSuite.tests) forEach(runAllTests)(stateOrSuite.suites) # ------- # # Helpers # # ------- # def runTest(aTest): try: aTest.fn() aTest.succeeded = True except Exception as e: aTest.succeeded = False aTest.rootState.succeeded = False propagateFailure(aTest.parentSuite) aTest.formattedException = format_exc() aTest.error = e def propagateFailure(aSuite): if aSuite is None: return if aSuite.succeeded: aSuite.succeeded = False propagateFailure(aSuite.parentSuite) PK!kc !simple_test_process/runProcess.py# ------- # # Imports # # ------- # from os import path from tedent import tedent from traceback import format_exc from types import SimpleNamespace as o from .fns import forEach, iif, isEmpty, joinWith, map_, passThrough, prependStr from .onlyKeepGreppedTests import onlyKeepGreppedTests from .runAllTests import runAllTests from .state import initState from .utils import gatherTests, importTests, twoLineSeps from .validateAndGetReportFn import validateAndGetReportFn import os import toml # ---- # # Main # # ---- # def runProcess(*, projectDir, reporter, silent, grepArgs): try: silent = silent == "True" cliResult = o(stderr=None, stdout=None, code=None) if not silent: validationResult = validateAndGetReportFn( reporter, silent, cliResult ) if validationResult.hasError: return validationResult.cliResult report = validationResult.report pyprojectTomlPath = path.join(projectDir, "pyproject.toml") reportOpts = None if path.isfile(pyprojectTomlPath): allProjectSettings = toml.load(pyprojectTomlPath) result = getValueAtPath(allProjectSettings, ["tool", reporter]) if result.hasValue: reportOpts = result.value state = initState() importTests(projectDir) forEach(gatherTests)(state.suites) onlyKeepGreppedTests(state, grepArgs) runAllTests(state) if not state.testsFound: if not silent: cliResult.stderr = tedent( f""" No tests were found in any python files under the project's tests directory: '{path.join(projectDir, 'tests')}' Remember you define tests by decorating a function with @test("test label") """ ) cliResult.code = 2 return cliResult if isEmpty(state.tests) and isEmpty(state.suites): # grepArgs must contain something if this code is reached if not silent: cliResult.stderr = ( "Your grep options failed to match any suites or tests" ) cliResult.code = 2 return cliResult if not silent: if reportOpts is None: report(state) else: report(state, reportOpts) cliResult.code = iif(state.succeeded, 0, 1) return cliResult except Exception: if not silent: cliResult.stderr = ( os.linesep + "An error occurred during simple_test_process" + twoLineSeps + format_exc() ) cliResult.code = 2 return cliResult # ------- # # Helpers # # ------- # def toFormattedGrepArgs(greppedStrings, grepKey): return ( grepKey + ":" + os.linesep + passThrough( greppedStrings, [map_(prependStr(" ")), joinWith(os.linesep)] ) ) def getValueAtPath(aDict, pathToValue): result = o(hasValue=None, value=None) val = aDict for segment in pathToValue: if segment not in val: result.hasValue = False return result val = val[segment] result.hasValue = True result.value = val return result PK!simple_test_process/state.pyfrom copy import deepcopy from types import SimpleNamespace as o _initialState = o( tests=[], suites=[], currentSuite=None, testsFound=False, succeeded=True ) state = deepcopy(_initialState) def _getState(): return state def initState(): global state state = deepcopy(_initialState) return state def addSuite(label, fn): currentSuite = state.currentSuite newSuite = o( label=label, fn=fn, tests=[], suites=[], parentSuite=currentSuite, rootState=state, succeeded=True, ) if currentSuite is None: state.suites.append(newSuite) else: currentSuite.suites.append(newSuite) return state def addTest(label, fn): global state currentSuite = state.currentSuite test = o(label=label, fn=fn, parentSuite=currentSuite, rootState=state) if currentSuite is None: state.tests.append(test) else: currentSuite.tests.append(test) state.testsFound = True return state PK!Kauusimple_test_process/suite.pyfrom .state import addSuite def suite(label): def wrapper(fn): addSuite(label, fn) return wrapper PK!bANrrsimple_test_process/test.pyfrom .state import addTest def test(label): def wrapper(fn): addTest(label, fn) return wrapper PK!N\VVsimple_test_process/utils.py# ------- # # Imports # # ------- # from glob import glob from os import path from .suite import suite from .test import test import importlib.util import os from .fns import ( discardFirst, discardWhen, endsWith, forEach, joinWith, map_, passThrough, split, ) # ---- # # Main # # ---- # twoLineSeps = os.linesep + os.linesep # # I'm choosing to gather all the tests prior to running any because I feel that # will be a simpler design. # def gatherTests(aSuite): oldCurrentSuite = aSuite.rootState.currentSuite aSuite.rootState.currentSuite = aSuite aSuite.fn() forEach(gatherTests)(aSuite.suites) aSuite.rootState.currentSuite = oldCurrentSuite # # I can't find a clean way to do this so I'm rolling my own. The python # import system is inherently hacky anyway :( # def importTests(projectDir): testsDir = path.join(projectDir, "tests") globStr = path.join(testsDir, "**/*.py") passThrough( globStr, [ recursiveGlob, discardWhen(endsWith("__init__.py")), map_(discardFirst(len(projectDir + "/"))), map_(toModulePath), forEach(importModule), ], ) def importModule(modulePath): try: spec = importlib.util.find_spec(modulePath) testModule = importlib.util.module_from_spec(spec) testModule.test = test testModule.suite = suite spec.loader.exec_module(testModule) except Exception as e: raise Exception(f"Error occurred while importing '{modulePath}'") from e def recursiveGlob(globStr): return glob(globStr, recursive=True) def toModulePath(filePathFromTestsDir): return passThrough( filePathFromTestsDir, [removeExtension, split(os.sep), joinWith(".")] ) def removeExtension(filePath): return os.path.splitext(filePath)[0] PK!,,-simple_test_process/validateAndGetReportFn.py# ------- # # Imports # # ------- # from traceback import format_exc from types import SimpleNamespace as o from .utils import twoLineSeps import importlib import os # ---- # # Main # # ---- # def validateAndGetReportFn(reporter, silent, cliResult): validationResult = o(report=None, cliResult=cliResult, hasError=False) try: reporterModule = importlib.import_module(reporter) except: if not silent: err = "An error occurred while importing the reporter" cliResult.stderr = os.linesep + err + twoLineSeps + format_exc() cliResult.code = 2 validationResult.hasError = True return validationResult if hasattr(reporterModule, "report") and callable(reporterModule.report): validationResult.report = reporterModule.report else: if not silent: cliResult.stderr = ( os.linesep + "the reporter must expose a callable 'report'" ) cliResult.code = 2 validationResult.hasError = True return validationResult PK!HڽTU)simple_test_process-0.2.0.dist-info/WHEEL A н#Z;/"d&F[xzw@Zpy3Fv]\fi4WZ^EgM_-]#0(q7PK!H8,simple_test_process-0.2.0.dist-info/METADATAo0W#H@MeK7>ϥ؄<%r>ϝ$(R7I{WXBY i })_X)Dz_*v\rp>A'o!t΢#[,p(j8hj󭬽z vձvF8z2>Vpj\bViSA};`EYGLU$l"ǪZco~m`&sP.ֿM/t jpU{?jxu~w2Ndwe;ؤ*n0-#$CY%Ɠ#\Ht+ǃqɲU0aWykPFGmTa'cS;T,,1n3v:E1 o㑆<:!>Vs?<:M6z =Z4A&#L'^7,\.Ú*9'PK!HMV _*simple_test_process-0.2.0.dist-info/RECORDXI\oE/d7f2 &2y}7Ƶ.2[?d Ţ& )[4.#qEy#QCtu0]t - ѭ)A4sV BHͪ!SxWY/@hf_Zq q u@97`; >{_"j9Ļ+s/sG*J)X 0Aú~Ž ;= s|ЏW9`&ev* 9׸{5=kS>^5S wcj70{V@8tbLyάF砤aUw$~MS q'R srN5&~rG`db;޻ 6mFn+ H{סZ[e5_(m+ rI)MroUFm_I!pƻϞVcz1_CLXVFcڹnB pqxgɔ3-;C=|3'kӑǾ1=(s!(3Ic-&XlF*%[!Zsu7&:iYFӲ2Q{yc|.&Glaj8N u7 Sʕ,V5IwJdTU~L_Z(Ǟۥ/"{A(6e@cV}0X^GsQvovL6ҡ _- o)? SaN=V>rvpQ7g/2|8VoỈU"hrp=ӦcB ex-a(u)?yg'~Ώ.Z^R,6G$x s-l^xx`YxP)O<9C\3nA"V8xqjNMd^NMvbr9;y7&mj`(>DWTsb,9&T}wkextܠ98g&_)?FbT>d-\ ;3Ēς (%a .ZcϯPMp'ͱhQwYCxԶ^x"Š/nƩbqۗ3 0~ءHE\''D-RIE< a0TEո%:<C ; nl`?Mҝ1 :l? ;_M35@̎o֎U_bHڪc+ TZޝGYAݕO$ ^#7J"mdi `_W)K=`uImY۾`s[ \tQB穡/NP|lK Dզ7TӇŐ$%yA,*2Z<5MTLb;;yß4~Q+)4Ȣ,d.z0e ^CQ}ܧmLMھ:eK; =;,Si_2t7pp3eXHm=qa"fLPHk觚ՌGtz WQJYUK`β.? 6T38_F!c #qGA94U{%ycK23ҏQ$t ovBq\];7\1M-_|SAlq}Aц$O`|o9z!=!cC~=n8-\b\2"˜Fh(7>qs qgm{6ϋJ4yжeM#6*Mr"MyE̽rֱka1 /}fA6~8_@=gAcyהP@D ^~nlO˱NNE`]C eujvVJƫ+VK7$֢hfY&7˾j%v(+g⑓H )zTV"*G AȸYy`}衫W WٔF:1}A--Qo9 e^_c~wc#vg ܇.Y)m@]&SӲޡ] uzO S{5 vO:2 (Hrq[:? }d#3<8| _k#cq0\ ] V-||e3/C)Ya]pBss)ޫPP(#o|mT9ПA#)5ʼDUñ Ͷq3c8:57ӽ%4u{Ix1[K$"].@ ;1LZÜWI6Yr kt"Lc4#-O}(F%N{7ixXԯuj$pE3)1&\_hsEa]$[M6Lm@#Ԏ DyQiIJ[>~7 -#Tۋ1̤߽'Aa58̗^LS\BӤp}VfK?u?O .-TM5poAɔBcw 0E^7PK!4