From 764479d9d170f7b87100d5811d64fae9d6cdd7f6 Mon Sep 17 00:00:00 2001 From: Tim Vergenz Date: Fri, 26 Apr 2024 19:18:17 -0400 Subject: [PATCH] refactor: convert camelCase to snake_case Purposes: 1. To match typical modern Python coding styles (recommended by PEP 8) 2. To prepare for argparse usage, which uses snake_case for default dests Via https://ast-grep.github.io/, with rule: ``` id: _ language: python rule: pattern: $ID kind: identifier all: - regex: '^[^A-Z]' # not PascalCase - regex: '[a-z][A-Z]' # has camelCase transition not: any: # backcompat (part of cog module API) - regex: ^sOut$ - inside: kind: attribute has: field: object regex: \.cogmodule$ # unittest methods - regex: ^assert - regex: ^setUp$ - regex: ^tearDown$ - regex: ^addCleanup$ transform: ID_SNAKE: convert: source: $ID toCase: snakeCase UNDERSCORE: replace: source: $ID replace: '^(_)?.*' by: '$1' fix: $UNDERSCORE$ID_SNAKE ``` plus manual review of all changes --- cogapp/cogapp.py | 460 +++++++++++----------- cogapp/makefiles.py | 12 +- cogapp/test_cogapp.py | 786 +++++++++++++++++++------------------- cogapp/test_makefiles.py | 56 +-- cogapp/test_whiteutils.py | 132 +++---- cogapp/utils.py | 2 +- cogapp/whiteutils.py | 22 +- docs/running.rst | 2 +- 8 files changed, 736 insertions(+), 736 deletions(-) diff --git a/cogapp/cogapp.py b/cogapp/cogapp.py index 798439d..b463f87 100644 --- a/cogapp/cogapp.py +++ b/cogapp/cogapp.py @@ -12,7 +12,7 @@ import traceback import types -from .whiteutils import commonPrefix, reindentBlock, whitePrefix +from .whiteutils import common_prefix, reindent_block, white_prefix from .utils import NumberedFileReader, Redirectable, change_dir, md5 __version__ = "3.4.1" @@ -114,29 +114,29 @@ def __init__(self, options=None): self.lines = [] self.options = options or CogOptions() - def parseMarker(self, line): + def parse_marker(self, line): self.markers.append(line) - def parseLine(self, line): + def parse_line(self, line): self.lines.append(line.strip("\n")) - def getCode(self): + def get_code(self): """Extract the executable Python code from the generator.""" # If the markers and lines all have the same prefix # (end-of-line comment chars, for example), # then remove it from all the lines. - prefIn = commonPrefix(self.markers + self.lines) - if prefIn: - self.markers = [line.replace(prefIn, "", 1) for line in self.markers] - self.lines = [line.replace(prefIn, "", 1) for line in self.lines] + pref_in = common_prefix(self.markers + self.lines) + if pref_in: + self.markers = [line.replace(pref_in, "", 1) for line in self.markers] + self.lines = [line.replace(pref_in, "", 1) for line in self.lines] - return reindentBlock(self.lines, "") + return reindent_block(self.lines, "") def evaluate(self, cog, globals, fname): # figure out the right whitespace prefix for the output - prefOut = whitePrefix(self.markers) + pref_out = white_prefix(self.markers) - intext = self.getCode() + intext = self.get_code() if not intext: return "" @@ -152,7 +152,7 @@ def evaluate(self, cog, globals, fname): cog.cogmodule.error = self.error real_stdout = sys.stdout - if self.options.printOutput: + if self.options.print_output: sys.stdout = captured_stdout = io.StringIO() self.outstring = "" @@ -170,7 +170,7 @@ def evaluate(self, cog, globals, fname): finally: sys.stdout = real_stdout - if self.options.printOutput: + if self.options.print_output: self.outstring = captured_stdout.getvalue() # We need to make sure that the last line in the output @@ -179,7 +179,7 @@ def evaluate(self, cog, globals, fname): if self.outstring and self.outstring[-1] != "\n": self.outstring += "\n" - return reindentBlock(self.outstring, prefOut) + return reindent_block(self.outstring, pref_out) def msg(self, s): self.prout("Message: " + s) @@ -194,7 +194,7 @@ def out(self, sOut="", dedent=False, trimblanklines=False): del lines[-1] sOut = "\n".join(lines) + "\n" if dedent: - sOut = reindentBlock(sOut) + sOut = reindent_block(sOut) self.outstring += sOut def outl(self, sOut="", **kw): @@ -219,26 +219,26 @@ class CogOptions: def __init__(self): # Defaults for argument values. self.args = [] - self.includePath = [] + self.include_path = [] self.defines = {} - self.showVersion = False - self.makeWritableCmd = None + self.show_version = False + self.make_writable_cmd = None self.replace = False - self.noGenerate = False - self.outputName = None - self.warnEmpty = False - self.hashOutput = False - self.deleteCode = False - self.eofCanBeEnd = False + self.no_generate = False + self.output_name = None + self.warn_empty = False + self.hash_output = False + self.delete_code = False + self.eof_can_be_end = False self.suffix = None self.newlines = False - self.beginSpec = "[[[cog" - self.endSpec = "]]]" - self.endOutput = "[[[end]]]" + self.begin_spec = "[[[cog" + self.end_spec = "]]]" + self.end_output = "[[[end]]]" self.encoding = "utf-8" self.verbosity = 2 self.prologue = "" - self.printOutput = False + self.print_output = False self.check = False def __eq__(self, other): @@ -249,12 +249,12 @@ def clone(self): """Make a clone of these options, for further refinement.""" return copy.deepcopy(self) - def addToIncludePath(self, dirs): + def add_to_include_path(self, dirs): """Add directories to the include path.""" dirs = dirs.split(os.pathsep) - self.includePath.extend(dirs) + self.include_path.extend(dirs) - def parseArgs(self, argv): + def parse_args(self, argv): # Parse the command line arguments. try: opts, self.args = getopt.getopt( @@ -272,22 +272,22 @@ def parseArgs(self, argv): # Handle the command line arguments. for o, a in opts: if o == "-c": - self.hashOutput = True + self.hash_output = True elif o == "-d": - self.deleteCode = True + self.delete_code = True elif o == "-D": if a.count("=") < 1: raise CogUsageError("-D takes a name=value argument") name, value = a.split("=", 1) self.defines[name] = value elif o == "-e": - self.warnEmpty = True + self.warn_empty = True elif o == "-I": - self.addToIncludePath(os.path.abspath(a)) + self.add_to_include_path(os.path.abspath(a)) elif o == "-n": self.encoding = a elif o == "-o": - self.outputName = a + self.output_name = a elif o == "-r": self.replace = True elif o == "-s": @@ -295,17 +295,17 @@ def parseArgs(self, argv): elif o == "-p": self.prologue = a elif o == "-P": - self.printOutput = True + self.print_output = True elif o == "-U": self.newlines = True elif o == "-v": - self.showVersion = True + self.show_version = True elif o == "-w": - self.makeWritableCmd = a + self.make_writable_cmd = a elif o == "-x": - self.noGenerate = True + self.no_generate = True elif o == "-z": - self.eofCanBeEnd = True + self.eof_can_be_end = True elif o == "--check": self.check = True elif o == "--markers": @@ -319,7 +319,7 @@ def parseArgs(self, argv): def _parse_markers(self, val): try: - self.beginSpec, self.endSpec, self.endOutput = val.split(" ") + self.begin_spec, self.end_spec, self.end_output = val.split(" ") except ValueError: raise CogUsageError( f"--markers requires 3 values separated by spaces, could not parse {val!r}" @@ -327,12 +327,12 @@ def _parse_markers(self, val): def validate(self): """Does nothing if everything is OK, raises CogError's if it's not.""" - if self.replace and self.deleteCode: + if self.replace and self.delete_code: raise CogUsageError( "Can't use -d with -r (or you would delete all your source!)" ) - if self.replace and self.outputName: + if self.replace and self.output_name: raise CogUsageError("Can't use -o with -r (they are opposites)") @@ -342,31 +342,31 @@ class Cog(Redirectable): def __init__(self): super().__init__() self.options = CogOptions() - self._fixEndOutputPatterns() + self._fix_end_output_patterns() self.cogmodulename = "cog" - self.createCogModule() - self.checkFailed = False + self.create_cog_module() + self.check_failed = False - def _fixEndOutputPatterns(self): - end_output = re.escape(self.options.endOutput) - self.reEndOutput = re.compile( + def _fix_end_output_patterns(self): + end_output = re.escape(self.options.end_output) + self.re_end_output = re.compile( end_output + r"(?P *\(checksum: (?P[a-f0-9]+)\))" ) - self.endFormat = self.options.endOutput + " (checksum: %s)" + self.end_format = self.options.end_output + " (checksum: %s)" - def showWarning(self, msg): + def show_warning(self, msg): self.prout(f"Warning: {msg}") - def isBeginSpecLine(self, s): - return self.options.beginSpec in s + def is_begin_spec_line(self, s): + return self.options.begin_spec in s - def isEndSpecLine(self, s): - return self.options.endSpec in s and not self.isEndOutputLine(s) + def is_end_spec_line(self, s): + return self.options.end_spec in s and not self.is_end_output_line(s) - def isEndOutputLine(self, s): - return self.options.endOutput in s + def is_end_output_line(self, s): + return self.options.end_output in s - def createCogModule(self): + def create_cog_module(self): """Make a cog "module" object. Imported Python modules can use "import cog" to get our state. @@ -375,7 +375,7 @@ def createCogModule(self): self.cogmodule = types.SimpleNamespace() self.cogmodule.path = [] - def openOutputFile(self, fname): + def open_output_file(self, fname): """Open an output file, taking all the details into account.""" opts = {} mode = "w" @@ -387,40 +387,40 @@ def openOutputFile(self, fname): os.makedirs(fdir) return open(fname, mode, **opts) - def openInputFile(self, fname): + def open_input_file(self, fname): """Open an input file.""" if fname == "-": return sys.stdin else: return open(fname, encoding=self.options.encoding) - def processFile(self, fileIn, fileOut, fname=None, globals=None): + def process_file(self, file_in, file_out, fname=None, globals=None): """Process an input file object to an output file object. `fileIn` and `fileOut` can be file objects, or file names. """ - fileNameIn = fname or "" - fileNameOut = fname or "" - fileInToClose = fileOutToClose = None + file_name_in = fname or "" + file_name_out = fname or "" + file_in_to_close = file_out_to_close = None # Convert filenames to files. - if isinstance(fileIn, (bytes, str)): + if isinstance(file_in, (bytes, str)): # Open the input file. - fileNameIn = fileIn - fileIn = fileInToClose = self.openInputFile(fileIn) - if isinstance(fileOut, (bytes, str)): + file_name_in = file_in + file_in = file_in_to_close = self.open_input_file(file_in) + if isinstance(file_out, (bytes, str)): # Open the output file. - fileNameOut = fileOut - fileOut = fileOutToClose = self.openOutputFile(fileOut) + file_name_out = file_out + file_out = file_out_to_close = self.open_output_file(file_out) try: - fileIn = NumberedFileReader(fileIn) + file_in = NumberedFileReader(file_in) - sawCog = False + saw_cog = False - self.cogmodule.inFile = fileNameIn - self.cogmodule.outFile = fileNameOut - self.cogmodulename = "cog_" + md5(fileNameOut.encode()).hexdigest() + self.cogmodule.inFile = file_name_in + self.cogmodule.outFile = file_name_out + self.cogmodulename = "cog_" + md5(file_name_out.encode()).hexdigest() sys.modules[self.cogmodulename] = self.cogmodule # if "import cog" explicitly done in code by user, note threading will cause clashes. sys.modules["cog"] = self.cogmodule @@ -433,113 +433,113 @@ def processFile(self, fileIn, fileOut, fname=None, globals=None): globals.update(self.options.defines) # loop over generator chunks - line = fileIn.readline() + line = file_in.readline() while line: # Find the next spec begin - while line and not self.isBeginSpecLine(line): - if self.isEndSpecLine(line): + while line and not self.is_begin_spec_line(line): + if self.is_end_spec_line(line): raise CogError( - f"Unexpected {self.options.endSpec!r}", - file=fileNameIn, - line=fileIn.linenumber(), + f"Unexpected {self.options.end_spec!r}", + file=file_name_in, + line=file_in.linenumber(), ) - if self.isEndOutputLine(line): + if self.is_end_output_line(line): raise CogError( - f"Unexpected {self.options.endOutput!r}", - file=fileNameIn, - line=fileIn.linenumber(), + f"Unexpected {self.options.end_output!r}", + file=file_name_in, + line=file_in.linenumber(), ) - fileOut.write(line) - line = fileIn.readline() + file_out.write(line) + line = file_in.readline() if not line: break - if not self.options.deleteCode: - fileOut.write(line) + if not self.options.delete_code: + file_out.write(line) # l is the begin spec gen = CogGenerator(options=self.options) - gen.setOutput(stdout=self.stdout) - gen.parseMarker(line) - firstLineNum = fileIn.linenumber() - self.cogmodule.firstLineNum = firstLineNum + gen.set_output(stdout=self.stdout) + gen.parse_marker(line) + first_line_num = file_in.linenumber() + self.cogmodule.firstLineNum = first_line_num # If the spec begin is also a spec end, then process the single # line of code inside. - if self.isEndSpecLine(line): - beg = line.find(self.options.beginSpec) - end = line.find(self.options.endSpec) + if self.is_end_spec_line(line): + beg = line.find(self.options.begin_spec) + end = line.find(self.options.end_spec) if beg > end: raise CogError( "Cog code markers inverted", - file=fileNameIn, - line=firstLineNum, + file=file_name_in, + line=first_line_num, ) else: - code = line[beg + len(self.options.beginSpec) : end].strip() - gen.parseLine(code) + code = line[beg + len(self.options.begin_spec) : end].strip() + gen.parse_line(code) else: # Deal with an ordinary code block. - line = fileIn.readline() + line = file_in.readline() # Get all the lines in the spec - while line and not self.isEndSpecLine(line): - if self.isBeginSpecLine(line): + while line and not self.is_end_spec_line(line): + if self.is_begin_spec_line(line): raise CogError( - f"Unexpected {self.options.beginSpec!r}", - file=fileNameIn, - line=fileIn.linenumber(), + f"Unexpected {self.options.begin_spec!r}", + file=file_name_in, + line=file_in.linenumber(), ) - if self.isEndOutputLine(line): + if self.is_end_output_line(line): raise CogError( - f"Unexpected {self.options.endOutput!r}", - file=fileNameIn, - line=fileIn.linenumber(), + f"Unexpected {self.options.end_output!r}", + file=file_name_in, + line=file_in.linenumber(), ) - if not self.options.deleteCode: - fileOut.write(line) - gen.parseLine(line) - line = fileIn.readline() + if not self.options.delete_code: + file_out.write(line) + gen.parse_line(line) + line = file_in.readline() if not line: raise CogError( "Cog block begun but never ended.", - file=fileNameIn, - line=firstLineNum, + file=file_name_in, + line=first_line_num, ) - if not self.options.deleteCode: - fileOut.write(line) - gen.parseMarker(line) + if not self.options.delete_code: + file_out.write(line) + gen.parse_marker(line) - line = fileIn.readline() + line = file_in.readline() # Eat all the lines in the output section. While reading past # them, compute the md5 hash of the old output. previous = [] hasher = md5() - while line and not self.isEndOutputLine(line): - if self.isBeginSpecLine(line): + while line and not self.is_end_output_line(line): + if self.is_begin_spec_line(line): raise CogError( - f"Unexpected {self.options.beginSpec!r}", - file=fileNameIn, - line=fileIn.linenumber(), + f"Unexpected {self.options.begin_spec!r}", + file=file_name_in, + line=file_in.linenumber(), ) - if self.isEndSpecLine(line): + if self.is_end_spec_line(line): raise CogError( - f"Unexpected {self.options.endSpec!r}", - file=fileNameIn, - line=fileIn.linenumber(), + f"Unexpected {self.options.end_spec!r}", + file=file_name_in, + line=file_in.linenumber(), ) previous.append(line) hasher.update(line.encode("utf-8")) - line = fileIn.readline() - curHash = hasher.hexdigest() + line = file_in.readline() + cur_hash = hasher.hexdigest() - if not line and not self.options.eofCanBeEnd: + if not line and not self.options.eof_can_be_end: # We reached end of file before we found the end output line. raise CogError( - f"Missing {self.options.endOutput!r} before end of file.", - file=fileNameIn, - line=fileIn.linenumber(), + f"Missing {self.options.end_output!r} before end of file.", + file=file_name_in, + line=file_in.linenumber(), ) # Make the previous output available to the current code @@ -548,55 +548,55 @@ def processFile(self, fileIn, fileOut, fname=None, globals=None): # Write the output of the spec to be the new output if we're # supposed to generate code. hasher = md5() - if not self.options.noGenerate: - fname = f"" + if not self.options.no_generate: + fname = f"" gen = gen.evaluate(cog=self, globals=globals, fname=fname) - gen = self.suffixLines(gen) + gen = self.suffix_lines(gen) hasher.update(gen.encode("utf-8")) - fileOut.write(gen) - newHash = hasher.hexdigest() + file_out.write(gen) + new_hash = hasher.hexdigest() - sawCog = True + saw_cog = True # Write the ending output line - hashMatch = self.reEndOutput.search(line) - if self.options.hashOutput: - if hashMatch: - oldHash = hashMatch["hash"] - if oldHash != curHash: + hash_match = self.re_end_output.search(line) + if self.options.hash_output: + if hash_match: + old_hash = hash_match["hash"] + if old_hash != cur_hash: raise CogError( "Output has been edited! Delete old checksum to unprotect.", - file=fileNameIn, - line=fileIn.linenumber(), + file=file_name_in, + line=file_in.linenumber(), ) # Create a new end line with the correct hash. - endpieces = line.split(hashMatch.group(0), 1) + endpieces = line.split(hash_match.group(0), 1) else: # There was no old hash, but we want a new hash. - endpieces = line.split(self.options.endOutput, 1) - line = (self.endFormat % newHash).join(endpieces) + endpieces = line.split(self.options.end_output, 1) + line = (self.end_format % new_hash).join(endpieces) else: # We don't want hashes output, so if there was one, get rid of # it. - if hashMatch: - line = line.replace(hashMatch["hashsect"], "", 1) + if hash_match: + line = line.replace(hash_match["hashsect"], "", 1) - if not self.options.deleteCode: - fileOut.write(line) - line = fileIn.readline() + if not self.options.delete_code: + file_out.write(line) + line = file_in.readline() - if not sawCog and self.options.warnEmpty: - self.showWarning(f"no cog code found in {fileNameIn}") + if not saw_cog and self.options.warn_empty: + self.show_warning(f"no cog code found in {file_name_in}") finally: - if fileInToClose: - fileInToClose.close() - if fileOutToClose: - fileOutToClose.close() + if file_in_to_close: + file_in_to_close.close() + if file_out_to_close: + file_out_to_close.close() # A regex for non-empty lines, used by suffixLines. - reNonEmptyLines = re.compile(r"^\s*\S+.*$", re.MULTILINE) + re_non_empty_lines = re.compile(r"^\s*\S+.*$", re.MULTILINE) - def suffixLines(self, text): + def suffix_lines(self, text): """Add suffixes to the lines in text, if our options desire it. `text` is many lines, as a single string. @@ -605,113 +605,113 @@ def suffixLines(self, text): if self.options.suffix: # Find all non-blank lines, and add the suffix to the end. repl = r"\g<0>" + self.options.suffix.replace("\\", "\\\\") - text = self.reNonEmptyLines.sub(repl, text) + text = self.re_non_empty_lines.sub(repl, text) return text - def processString(self, input, fname=None): + def process_string(self, input, fname=None): """Process `input` as the text to cog. Return the cogged output as a string. """ - fileOld = io.StringIO(input) - fileNew = io.StringIO() - self.processFile(fileOld, fileNew, fname=fname) - return fileNew.getvalue() + file_old = io.StringIO(input) + file_new = io.StringIO() + self.process_file(file_old, file_new, fname=fname) + return file_new.getvalue() - def replaceFile(self, oldPath, newText): + def replace_file(self, old_path, new_text): """Replace file oldPath with the contents newText""" - if not os.access(oldPath, os.W_OK): + if not os.access(old_path, os.W_OK): # Need to ensure we can write. - if self.options.makeWritableCmd: + if self.options.make_writable_cmd: # Use an external command to make the file writable. - cmd = self.options.makeWritableCmd.replace("%s", oldPath) + cmd = self.options.make_writable_cmd.replace("%s", old_path) with os.popen(cmd) as cmdout: self.stdout.write(cmdout.read()) - if not os.access(oldPath, os.W_OK): - raise CogError(f"Couldn't make {oldPath} writable") + if not os.access(old_path, os.W_OK): + raise CogError(f"Couldn't make {old_path} writable") else: # Can't write! - raise CogError(f"Can't overwrite {oldPath}") - f = self.openOutputFile(oldPath) - f.write(newText) + raise CogError(f"Can't overwrite {old_path}") + f = self.open_output_file(old_path) + f.write(new_text) f.close() - def saveIncludePath(self): - self.savedInclude = self.options.includePath[:] - self.savedSysPath = sys.path[:] + def save_include_path(self): + self.saved_include = self.options.include_path[:] + self.saved_sys_path = sys.path[:] - def restoreIncludePath(self): - self.options.includePath = self.savedInclude - self.cogmodule.path = self.options.includePath - sys.path = self.savedSysPath + def restore_include_path(self): + self.options.include_path = self.saved_include + self.cogmodule.path = self.options.include_path + sys.path = self.saved_sys_path - def addToIncludePath(self, includePath): - self.cogmodule.path.extend(includePath) - sys.path.extend(includePath) + def add_to_include_path(self, include_path): + self.cogmodule.path.extend(include_path) + sys.path.extend(include_path) - def processOneFile(self, fname): + def process_one_file(self, fname): """Process one filename through cog.""" - self.saveIncludePath() - needNewline = False + self.save_include_path() + need_newline = False try: - self.addToIncludePath(self.options.includePath) + self.add_to_include_path(self.options.include_path) # Since we know where the input file came from, # push its directory onto the include path. - self.addToIncludePath([os.path.dirname(fname)]) + self.add_to_include_path([os.path.dirname(fname)]) # How we process the file depends on where the output is going. - if self.options.outputName: - self.processFile(fname, self.options.outputName, fname) + if self.options.output_name: + self.process_file(fname, self.options.output_name, fname) elif self.options.replace or self.options.check: # We want to replace the cog file with the output, # but only if they differ. verb = "Cogging" if self.options.replace else "Checking" if self.options.verbosity >= 2: self.prout(f"{verb} {fname}", end="") - needNewline = True + need_newline = True try: - fileOldFile = self.openInputFile(fname) - oldText = fileOldFile.read() - fileOldFile.close() - newText = self.processString(oldText, fname=fname) - if oldText != newText: + file_old_file = self.open_input_file(fname) + old_text = file_old_file.read() + file_old_file.close() + new_text = self.process_string(old_text, fname=fname) + if old_text != new_text: if self.options.verbosity >= 1: if self.options.verbosity < 2: self.prout(f"{verb} {fname}", end="") self.prout(" (changed)") - needNewline = False + need_newline = False if self.options.replace: - self.replaceFile(fname, newText) + self.replace_file(fname, new_text) else: assert self.options.check - self.checkFailed = True + self.check_failed = True finally: # The try-finally block is so we can print a partial line # with the name of the file, and print (changed) on the # same line, but also make sure to break the line before # any traceback. - if needNewline: + if need_newline: self.prout("") else: - self.processFile(fname, self.stdout, fname) + self.process_file(fname, self.stdout, fname) finally: - self.restoreIncludePath() + self.restore_include_path() - def processWildcards(self, fname): + def process_wildcards(self, fname): files = glob.glob(fname) if files: - for matchingFile in files: - self.processOneFile(matchingFile) + for matching_file in files: + self.process_one_file(matching_file) else: - self.processOneFile(fname) + self.process_one_file(fname) - def processFileList(self, fileNameList): + def process_file_list(self, file_name_list): """Process the files in a file list.""" - flist = self.openInputFile(fileNameList) + flist = self.open_input_file(file_name_list) lines = flist.readlines() flist.close() for line in lines: @@ -723,32 +723,32 @@ def processFileList(self, fileNameList): lex.escape = "" args = list(lex) if args: - self.processArguments(args) + self.process_arguments(args) - def processArguments(self, args): + def process_arguments(self, args): """Process one command-line.""" saved_options = self.options self.options = self.options.clone() - self.options.parseArgs(args[1:]) + self.options.parse_args(args[1:]) self.options.validate() if args[0][0] == "@": - if self.options.outputName: + if self.options.output_name: raise CogUsageError("Can't use -o with @file") - self.processFileList(args[0][1:]) + self.process_file_list(args[0][1:]) elif args[0][0] == "&": - if self.options.outputName: + if self.options.output_name: raise CogUsageError("Can't use -o with &file") file_list = args[0][1:] with change_dir(os.path.dirname(file_list)): - self.processFileList(os.path.basename(file_list)) + self.process_file_list(os.path.basename(file_list)) else: - self.processWildcards(args[0]) + self.process_wildcards(args[0]) self.options = saved_options - def callableMain(self, argv): + def callable_main(self, argv): """All of command-line cog, but in a callable form. This is used by main. `argv` is the equivalent of sys.argv. @@ -761,28 +761,28 @@ def callableMain(self, argv): self.prerr(usage, end="") return - self.options.parseArgs(argv) + self.options.parse_args(argv) self.options.validate() - self._fixEndOutputPatterns() + self._fix_end_output_patterns() - if self.options.showVersion: + if self.options.show_version: self.prout(f"Cog version {__version__}") return if self.options.args: for a in self.options.args: - self.processArguments([a]) + self.process_arguments([a]) else: raise CogUsageError("No files to process") - if self.checkFailed: + if self.check_failed: raise CogCheckFailed("Check failed") def main(self, argv): """Handle the command-line execution for cog.""" try: - self.callableMain(argv) + self.callable_main(argv) return 0 except CogUsageError as err: self.prerr(err) diff --git a/cogapp/makefiles.py b/cogapp/makefiles.py index 9051e09..2cd3a63 100644 --- a/cogapp/makefiles.py +++ b/cogapp/makefiles.py @@ -2,10 +2,10 @@ import os.path -from .whiteutils import reindentBlock +from .whiteutils import reindent_block -def makeFiles(d, basedir="."): +def make_files(d, basedir="."): """Create files from the dictionary `d` in the directory named by `basedir`.""" for name, contents in d.items(): child = os.path.join(basedir, name) @@ -14,14 +14,14 @@ def makeFiles(d, basedir="."): if isinstance(contents, bytes): mode += "b" with open(child, mode) as f: - f.write(reindentBlock(contents)) + f.write(reindent_block(contents)) else: if not os.path.exists(child): os.mkdir(child) - makeFiles(contents, child) + make_files(contents, child) -def removeFiles(d, basedir="."): +def remove_files(d, basedir="."): """Remove the files created by `makeFiles`. Directories are removed if they are empty. @@ -32,6 +32,6 @@ def removeFiles(d, basedir="."): if isinstance(contents, (bytes, str)): os.remove(child) else: - removeFiles(contents, child) + remove_files(contents, child) if not os.listdir(child): os.rmdir(child) diff --git a/cogapp/test_cogapp.py b/cogapp/test_cogapp.py index 13a7390..ca3162f 100644 --- a/cogapp/test_cogapp.py +++ b/cogapp/test_cogapp.py @@ -15,14 +15,14 @@ from .cogapp import Cog, CogOptions, CogGenerator from .cogapp import CogError, CogUsageError, CogGeneratedError, CogUserException from .cogapp import usage, __version__, main -from .makefiles import makeFiles -from .whiteutils import reindentBlock +from .makefiles import make_files +from .whiteutils import reindent_block class CogTestsInMemory(TestCase): """Test cases for cogapp.Cog()""" - def testNoCog(self): + def test_no_cog(self): strings = [ "", " ", @@ -32,9 +32,9 @@ def testNoCog(self): "Horton\n\tHears A\n\t\tWho", ] for s in strings: - self.assertEqual(Cog().processString(s), s) + self.assertEqual(Cog().process_string(s), s) - def testSimple(self): + def test_simple(self): infile = """\ Some text. //[[[cog @@ -61,9 +61,9 @@ def testSimple(self): epilogue. """ - self.assertEqual(Cog().processString(infile), outfile) + self.assertEqual(Cog().process_string(infile), outfile) - def testEmptyCog(self): + def test_empty_cog(self): # The cog clause can be totally empty. Not sure why you'd want it, # but it works. infile = """\ @@ -74,10 +74,10 @@ def testEmptyCog(self): goodbye """ - infile = reindentBlock(infile) - self.assertEqual(Cog().processString(infile), infile) + infile = reindent_block(infile) + self.assertEqual(Cog().process_string(infile), infile) - def testMultipleCogs(self): + def test_multiple_cogs(self): # One file can have many cog chunks, even abutting each other. infile = """\ //[[[cog @@ -98,10 +98,10 @@ def testMultipleCogs(self): //[[[end]]] """ - infile = reindentBlock(infile) - self.assertEqual(Cog().processString(infile), infile) + infile = reindent_block(infile) + self.assertEqual(Cog().process_string(infile), infile) - def testTrimBlankLines(self): + def test_trim_blank_lines(self): infile = """\ //[[[cog cog.out("This is line one\\n", trimblanklines=True) @@ -116,10 +116,10 @@ def testTrimBlankLines(self): //[[[end]]] """ - infile = reindentBlock(infile) - self.assertEqual(Cog().processString(infile), infile) + infile = reindent_block(infile) + self.assertEqual(Cog().process_string(infile), infile) - def testTrimEmptyBlankLines(self): + def test_trim_empty_blank_lines(self): infile = """\ //[[[cog cog.out("This is line one\\n", trimblanklines=True) @@ -135,10 +135,10 @@ def testTrimEmptyBlankLines(self): //[[[end]]] """ - infile = reindentBlock(infile) - self.assertEqual(Cog().processString(infile), infile) + infile = reindent_block(infile) + self.assertEqual(Cog().process_string(infile), infile) - def testTrimBlankLinesWithLastPartial(self): + def test_trim_blank_lines_with_last_partial(self): infile = """\ //[[[cog cog.out("This is line one\\n", trimblanklines=True) @@ -150,10 +150,10 @@ def testTrimBlankLinesWithLastPartial(self): //[[[end]]] """ - infile = reindentBlock(infile) - self.assertEqual(Cog().processString(infile), infile) + infile = reindent_block(infile) + self.assertEqual(Cog().process_string(infile), infile) - def testCogOutDedent(self): + def test_cog_out_dedent(self): infile = """\ //[[[cog cog.out("This is the first line\\n") @@ -182,10 +182,10 @@ def testCogOutDedent(self): //[[[end]]] """ - infile = reindentBlock(infile) - self.assertEqual(Cog().processString(infile), infile) + infile = reindent_block(infile) + self.assertEqual(Cog().process_string(infile), infile) - def test22EndOfLine(self): + def test22_end_of_line(self): # In Python 2.2, this cog file was not parsing because the # last line is indented but didn't end with a newline. infile = """\ @@ -200,10 +200,10 @@ def test22EndOfLine(self): //[[[end]]] """ - infile = reindentBlock(infile) - self.assertEqual(Cog().processString(infile), infile) + infile = reindent_block(infile) + self.assertEqual(Cog().process_string(infile), infile) - def testIndentedCode(self): + def test_indented_code(self): infile = """\ first line [[[cog @@ -218,10 +218,10 @@ def testIndentedCode(self): last line """ - infile = reindentBlock(infile) - self.assertEqual(Cog().processString(infile), infile) + infile = reindent_block(infile) + self.assertEqual(Cog().process_string(infile), infile) - def testPrefixedCode(self): + def test_prefixed_code(self): infile = """\ --[[[cog --import cog @@ -234,10 +234,10 @@ def testPrefixedCode(self): --[[[end]]] """ - infile = reindentBlock(infile) - self.assertEqual(Cog().processString(infile), infile) + infile = reindent_block(infile) + self.assertEqual(Cog().process_string(infile), infile) - def testPrefixedIndentedCode(self): + def test_prefixed_indented_code(self): infile = """\ prologue --[[[cog @@ -251,10 +251,10 @@ def testPrefixedIndentedCode(self): --[[[end]]] """ - infile = reindentBlock(infile) - self.assertEqual(Cog().processString(infile), infile) + infile = reindent_block(infile) + self.assertEqual(Cog().process_string(infile), infile) - def testBogusPrefixMatch(self): + def test_bogus_prefix_match(self): infile = """\ prologue #[[[cog @@ -269,10 +269,10 @@ def testBogusPrefixMatch(self): #[[[end]]] """ - infile = reindentBlock(infile) - self.assertEqual(Cog().processString(infile), infile) + infile = reindent_block(infile) + self.assertEqual(Cog().process_string(infile), infile) - def testNoFinalNewline(self): + def test_no_final_newline(self): # If the cog'ed output has no final newline, # it shouldn't eat up the cog terminator. infile = """\ @@ -287,10 +287,10 @@ def testNoFinalNewline(self): epilogue """ - infile = reindentBlock(infile) - self.assertEqual(Cog().processString(infile), infile) + infile = reindent_block(infile) + self.assertEqual(Cog().process_string(infile), infile) - def testNoOutputAtAll(self): + def test_no_output_at_all(self): # If there is absolutely no cog output, that's ok. infile = """\ prologue @@ -301,10 +301,10 @@ def testNoOutputAtAll(self): epilogue """ - infile = reindentBlock(infile) - self.assertEqual(Cog().processString(infile), infile) + infile = reindent_block(infile) + self.assertEqual(Cog().process_string(infile), infile) - def testPurelyBlankLine(self): + def test_purely_blank_line(self): # If there is a blank line in the cog code with no whitespace # prefix, that should be OK. @@ -321,10 +321,10 @@ def testPurelyBlankLine(self): epilogue """ - infile = reindentBlock(infile.replace("$", "")) - self.assertEqual(Cog().processString(infile), infile) + infile = reindent_block(infile.replace("$", "")) + self.assertEqual(Cog().process_string(infile), infile) - def testEmptyOutl(self): + def test_empty_outl(self): # Alexander Belchenko suggested the string argument to outl should # be optional. Does it work? @@ -347,10 +347,10 @@ def testEmptyOutl(self): epilogue """ - infile = reindentBlock(infile) - self.assertEqual(Cog().processString(infile), infile) + infile = reindent_block(infile) + self.assertEqual(Cog().process_string(infile), infile) - def testFirstLineNum(self): + def test_first_line_num(self): infile = """\ fooey [[[cog @@ -366,10 +366,10 @@ def testFirstLineNum(self): [[[end]]] """ - infile = reindentBlock(infile) - self.assertEqual(Cog().processString(infile), infile) + infile = reindent_block(infile) + self.assertEqual(Cog().process_string(infile), infile) - def testCompactOneLineCode(self): + def test_compact_one_line_code(self): infile = """\ first line hey: [[[cog cog.outl("hello %d" % (3*3*3*3)) ]]] looky! @@ -386,10 +386,10 @@ def testCompactOneLineCode(self): last line """ - infile = reindentBlock(infile) - self.assertEqual(Cog().processString(infile), reindentBlock(outfile)) + infile = reindent_block(infile) + self.assertEqual(Cog().process_string(infile), reindent_block(outfile)) - def testInsideOutCompact(self): + def test_inside_out_compact(self): infile = """\ first line hey?: ]]] what is this? [[[cog strange! @@ -400,9 +400,9 @@ def testInsideOutCompact(self): with self.assertRaisesRegex( CogError, r"^infile.txt\(2\): Cog code markers inverted$" ): - Cog().processString(reindentBlock(infile), "infile.txt") + Cog().process_string(reindent_block(infile), "infile.txt") - def testSharingGlobals(self): + def test_sharing_globals(self): infile = """\ first line hey: [[[cog s="hey there" ]]] looky! @@ -424,10 +424,10 @@ def testSharingGlobals(self): last line """ - infile = reindentBlock(infile) - self.assertEqual(Cog().processString(infile), reindentBlock(outfile)) + infile = reindent_block(infile) + self.assertEqual(Cog().process_string(infile), reindent_block(outfile)) - def testAssertInCogCode(self): + def test_assert_in_cog_code(self): # Check that we can test assertions in cog code in the test framework. infile = """\ [[[cog @@ -435,11 +435,11 @@ def testAssertInCogCode(self): ]]] [[[end]]] """ - infile = reindentBlock(infile) + infile = reindent_block(infile) with self.assertRaisesRegex(CogUserException, "AssertionError: Oops"): - Cog().processString(infile) + Cog().process_string(infile) - def testCogPrevious(self): + def test_cog_previous(self): # Check that we can access the previous run's output. infile = """\ [[[cog @@ -462,31 +462,31 @@ def testCogPrevious(self): [[[end]]] """ - infile = reindentBlock(infile) - self.assertEqual(Cog().processString(infile), reindentBlock(outfile)) + infile = reindent_block(infile) + self.assertEqual(Cog().process_string(infile), reindent_block(outfile)) class CogOptionsTests(TestCase): """Test the CogOptions class.""" - def testEquality(self): + def test_equality(self): o = CogOptions() p = CogOptions() self.assertEqual(o, p) - o.parseArgs(["-r"]) + o.parse_args(["-r"]) self.assertNotEqual(o, p) - p.parseArgs(["-r"]) + p.parse_args(["-r"]) self.assertEqual(o, p) - def testCloning(self): + def test_cloning(self): o = CogOptions() - o.parseArgs(["-I", "fooey", "-I", "booey", "-s", " /*x*/"]) + o.parse_args(["-I", "fooey", "-I", "booey", "-s", " /*x*/"]) p = o.clone() self.assertEqual(o, p) - p.parseArgs(["-I", "huey", "-D", "foo=quux"]) + p.parse_args(["-I", "huey", "-D", "foo=quux"]) self.assertNotEqual(o, p) q = CogOptions() - q.parseArgs( + q.parse_args( [ "-I", "fooey", @@ -502,53 +502,53 @@ def testCloning(self): ) self.assertEqual(p, q) - def testCombiningFlags(self): + def test_combining_flags(self): # Single-character flags can be combined. o = CogOptions() - o.parseArgs(["-e", "-r", "-z"]) + o.parse_args(["-e", "-r", "-z"]) p = CogOptions() - p.parseArgs(["-erz"]) + p.parse_args(["-erz"]) self.assertEqual(o, p) - def testMarkers(self): + def test_markers(self): o = CogOptions() o._parse_markers("a b c") - self.assertEqual("a", o.beginSpec) - self.assertEqual("b", o.endSpec) - self.assertEqual("c", o.endOutput) + self.assertEqual("a", o.begin_spec) + self.assertEqual("b", o.end_spec) + self.assertEqual("c", o.end_output) - def testMarkersSwitch(self): + def test_markers_switch(self): o = CogOptions() - o.parseArgs(["--markers", "a b c"]) - self.assertEqual("a", o.beginSpec) - self.assertEqual("b", o.endSpec) - self.assertEqual("c", o.endOutput) + o.parse_args(["--markers", "a b c"]) + self.assertEqual("a", o.begin_spec) + self.assertEqual("b", o.end_spec) + self.assertEqual("c", o.end_output) class FileStructureTests(TestCase): """Test that we're properly strict about the structure of files.""" - def isBad(self, infile, msg=None): - infile = reindentBlock(infile) + def is_bad(self, infile, msg=None): + infile = reindent_block(infile) with self.assertRaisesRegex(CogError, "^" + re.escape(msg) + "$"): - Cog().processString(infile, "infile.txt") + Cog().process_string(infile, "infile.txt") - def testBeginNoEnd(self): + def test_begin_no_end(self): infile = """\ Fooey #[[[cog cog.outl('hello') """ - self.isBad(infile, "infile.txt(2): Cog block begun but never ended.") + self.is_bad(infile, "infile.txt(2): Cog block begun but never ended.") - def testNoEoo(self): + def test_no_eoo(self): infile = """\ Fooey #[[[cog cog.outl('hello') #]]] """ - self.isBad(infile, "infile.txt(4): Missing '[[[end]]]' before end of file.") + self.is_bad(infile, "infile.txt(4): Missing '[[[end]]]' before end of file.") infile2 = """\ Fooey @@ -559,13 +559,13 @@ def testNoEoo(self): cog.outl('goodbye') #]]] """ - self.isBad(infile2, "infile.txt(5): Unexpected '[[[cog'") + self.is_bad(infile2, "infile.txt(5): Unexpected '[[[cog'") - def testStartWithEnd(self): + def test_start_with_end(self): infile = """\ #]]] """ - self.isBad(infile, "infile.txt(1): Unexpected ']]]'") + self.is_bad(infile, "infile.txt(1): Unexpected ']]]'") infile2 = """\ #[[[cog @@ -574,13 +574,13 @@ def testStartWithEnd(self): #[[[end]]] #]]] """ - self.isBad(infile2, "infile.txt(5): Unexpected ']]]'") + self.is_bad(infile2, "infile.txt(5): Unexpected ']]]'") - def testStartWithEoo(self): + def test_start_with_eoo(self): infile = """\ #[[[end]]] """ - self.isBad(infile, "infile.txt(1): Unexpected '[[[end]]]'") + self.is_bad(infile, "infile.txt(1): Unexpected '[[[end]]]'") infile2 = """\ #[[[cog @@ -589,15 +589,15 @@ def testStartWithEoo(self): #[[[end]]] #[[[end]]] """ - self.isBad(infile2, "infile.txt(5): Unexpected '[[[end]]]'") + self.is_bad(infile2, "infile.txt(5): Unexpected '[[[end]]]'") - def testNoEnd(self): + def test_no_end(self): infile = """\ #[[[cog cog.outl("hello") #[[[end]]] """ - self.isBad(infile, "infile.txt(3): Unexpected '[[[end]]]'") + self.is_bad(infile, "infile.txt(3): Unexpected '[[[end]]]'") infile2 = """\ #[[[cog @@ -608,9 +608,9 @@ def testNoEnd(self): cog.outl("hello") #[[[end]]] """ - self.isBad(infile2, "infile.txt(7): Unexpected '[[[end]]]'") + self.is_bad(infile2, "infile.txt(7): Unexpected '[[[end]]]'") - def testTwoBegins(self): + def test_two_begins(self): infile = """\ #[[[cog #[[[cog @@ -618,7 +618,7 @@ def testTwoBegins(self): #]]] #[[[end]]] """ - self.isBad(infile, "infile.txt(2): Unexpected '[[[cog'") + self.is_bad(infile, "infile.txt(2): Unexpected '[[[cog'") infile2 = """\ #[[[cog @@ -631,9 +631,9 @@ def testTwoBegins(self): #]]] #[[[end]]] """ - self.isBad(infile2, "infile.txt(6): Unexpected '[[[cog'") + self.is_bad(infile2, "infile.txt(6): Unexpected '[[[cog'") - def testTwoEnds(self): + def test_two_ends(self): infile = """\ #[[[cog cog.outl("hello") @@ -641,7 +641,7 @@ def testTwoEnds(self): #]]] #[[[end]]] """ - self.isBad(infile, "infile.txt(4): Unexpected ']]]'") + self.is_bad(infile, "infile.txt(4): Unexpected ']]]'") infile2 = """\ #[[[cog @@ -654,35 +654,35 @@ def testTwoEnds(self): #]]] #[[[end]]] """ - self.isBad(infile2, "infile.txt(8): Unexpected ']]]'") + self.is_bad(infile2, "infile.txt(8): Unexpected ']]]'") class CogErrorTests(TestCase): """Test cases for cog.error().""" - def testErrorMsg(self): + def test_error_msg(self): infile = """\ [[[cog cog.error("This ain't right!")]]] [[[end]]] """ - infile = reindentBlock(infile) + infile = reindent_block(infile) with self.assertRaisesRegex(CogGeneratedError, "^This ain't right!$"): - Cog().processString(infile) + Cog().process_string(infile) - def testErrorNoMsg(self): + def test_error_no_msg(self): infile = """\ [[[cog cog.error()]]] [[[end]]] """ - infile = reindentBlock(infile) + infile = reindent_block(infile) with self.assertRaisesRegex( CogGeneratedError, "^Error raised by cog generator.$" ): - Cog().processString(infile) + Cog().process_string(infile) - def testNoErrorIfErrorNotCalled(self): + def test_no_error_if_error_not_called(self): infile = """\ --[[[cog --import cog @@ -697,8 +697,8 @@ def testNoErrorIfErrorNotCalled(self): --[[[end]]] """ - infile = reindentBlock(infile) - self.assertEqual(Cog().processString(infile), infile) + infile = reindent_block(infile) + self.assertEqual(Cog().process_string(infile), infile) class CogGeneratorGetCodeTests(TestCase): @@ -708,71 +708,71 @@ def setUp(self): # All tests get a generator to use, and short same-length names for # the functions we're going to use. self.gen = CogGenerator() - self.m = self.gen.parseMarker - self.parseLine = self.gen.parseLine + self.m = self.gen.parse_marker + self.parse_line = self.gen.parse_line - def testEmpty(self): + def test_empty(self): self.m("// [[[cog") self.m("// ]]]") - self.assertEqual(self.gen.getCode(), "") + self.assertEqual(self.gen.get_code(), "") - def testSimple(self): + def test_simple(self): self.m("// [[[cog") - self.parseLine(' print "hello"') - self.parseLine(' print "bye"') + self.parse_line(' print "hello"') + self.parse_line(' print "bye"') self.m("// ]]]") - self.assertEqual(self.gen.getCode(), 'print "hello"\nprint "bye"') + self.assertEqual(self.gen.get_code(), 'print "hello"\nprint "bye"') - def testCompressed1(self): + def test_compressed1(self): # For a while, I supported compressed code blocks, but no longer. self.m('// [[[cog: print """') - self.parseLine("// hello") - self.parseLine("// bye") + self.parse_line("// hello") + self.parse_line("// bye") self.m('// """)]]]') - self.assertEqual(self.gen.getCode(), "hello\nbye") + self.assertEqual(self.gen.get_code(), "hello\nbye") - def testCompressed2(self): + def test_compressed2(self): # For a while, I supported compressed code blocks, but no longer. self.m('// [[[cog: print """') - self.parseLine("hello") - self.parseLine("bye") + self.parse_line("hello") + self.parse_line("bye") self.m('// """)]]]') - self.assertEqual(self.gen.getCode(), "hello\nbye") + self.assertEqual(self.gen.get_code(), "hello\nbye") - def testCompressed3(self): + def test_compressed3(self): # For a while, I supported compressed code blocks, but no longer. self.m("// [[[cog") - self.parseLine('print """hello') - self.parseLine("bye") + self.parse_line('print """hello') + self.parse_line("bye") self.m('// """)]]]') - self.assertEqual(self.gen.getCode(), 'print """hello\nbye') + self.assertEqual(self.gen.get_code(), 'print """hello\nbye') - def testCompressed4(self): + def test_compressed4(self): # For a while, I supported compressed code blocks, but no longer. self.m('// [[[cog: print """') - self.parseLine("hello") - self.parseLine('bye""")') + self.parse_line("hello") + self.parse_line('bye""")') self.m("// ]]]") - self.assertEqual(self.gen.getCode(), 'hello\nbye""")') + self.assertEqual(self.gen.get_code(), 'hello\nbye""")') - def testNoCommonPrefixForMarkers(self): + def test_no_common_prefix_for_markers(self): # It's important to be able to use #if 0 to hide lines from a # C++ compiler. self.m("#if 0 //[[[cog") - self.parseLine("\timport cog, sys") - self.parseLine("") - self.parseLine("\tprint sys.argv") + self.parse_line("\timport cog, sys") + self.parse_line("") + self.parse_line("\tprint sys.argv") self.m("#endif //]]]") - self.assertEqual(self.gen.getCode(), "import cog, sys\n\nprint sys.argv") + self.assertEqual(self.gen.get_code(), "import cog, sys\n\nprint sys.argv") class TestCaseWithTempDir(TestCase): - def newCog(self): + def new_cog(self): """Initialize the cog members for another run.""" # Create a cog engine, and catch its output. self.cog = Cog() self.output = io.StringIO() - self.cog.setOutput(stdout=self.output, stderr=self.output) + self.cog.set_output(stdout=self.output, stderr=self.output) def setUp(self): # Create a temporary directory. @@ -782,17 +782,17 @@ def setUp(self): os.mkdir(self.tempdir) self.olddir = os.getcwd() os.chdir(self.tempdir) - self.newCog() + self.new_cog() def tearDown(self): os.chdir(self.olddir) # Get rid of the temporary directory. shutil.rmtree(self.tempdir) - def assertFilesSame(self, fileName1, fileName2): - with open(os.path.join(self.tempdir, fileName1), "rb") as f1: + def assertFilesSame(self, file_name1, file_name2): + with open(os.path.join(self.tempdir, file_name1), "rb") as f1: text1 = f1.read() - with open(os.path.join(self.tempdir, fileName2), "rb") as f2: + with open(os.path.join(self.tempdir, file_name2), "rb") as f2: text2 = f2.read() self.assertEqual(text1, text2) @@ -804,58 +804,58 @@ def assertFileContent(self, fname, content): class ArgumentHandlingTests(TestCaseWithTempDir): - def testArgumentFailure(self): + def test_argument_failure(self): # Return value 2 means usage problem. self.assertEqual(self.cog.main(["argv0", "-j"]), 2) output = self.output.getvalue() self.assertIn("option -j not recognized", output) with self.assertRaisesRegex(CogUsageError, r"^No files to process$"): - self.cog.callableMain(["argv0"]) + self.cog.callable_main(["argv0"]) with self.assertRaisesRegex(CogUsageError, r"^option -j not recognized$"): - self.cog.callableMain(["argv0", "-j"]) + self.cog.callable_main(["argv0", "-j"]) - def testNoDashOAndAtFile(self): - makeFiles({"cogfiles.txt": "# Please run cog"}) + def test_no_dash_o_and_at_file(self): + make_files({"cogfiles.txt": "# Please run cog"}) with self.assertRaisesRegex(CogUsageError, r"^Can't use -o with @file$"): - self.cog.callableMain(["argv0", "-o", "foo", "@cogfiles.txt"]) + self.cog.callable_main(["argv0", "-o", "foo", "@cogfiles.txt"]) - def testNoDashOAndAmpFile(self): - makeFiles({"cogfiles.txt": "# Please run cog"}) + def test_no_dash_o_and_amp_file(self): + make_files({"cogfiles.txt": "# Please run cog"}) with self.assertRaisesRegex(CogUsageError, r"^Can't use -o with &file$"): - self.cog.callableMain(["argv0", "-o", "foo", "&cogfiles.txt"]) + self.cog.callable_main(["argv0", "-o", "foo", "&cogfiles.txt"]) - def testDashV(self): + def test_dash_v(self): self.assertEqual(self.cog.main(["argv0", "-v"]), 0) output = self.output.getvalue() self.assertEqual("Cog version %s\n" % __version__, output) - def producesHelp(self, args): - self.newCog() + def produces_help(self, args): + self.new_cog() argv = ["argv0"] + args.split() self.assertEqual(self.cog.main(argv), 0) self.assertEqual(usage, self.output.getvalue()) - def testDashH(self): + def test_dash_h(self): # -h or -? anywhere on the command line should just print help. - self.producesHelp("-h") - self.producesHelp("-?") - self.producesHelp("fooey.txt -h") - self.producesHelp("-o -r @fooey.txt -? @booey.txt") + self.produces_help("-h") + self.produces_help("-?") + self.produces_help("fooey.txt -h") + self.produces_help("-o -r @fooey.txt -? @booey.txt") - def testDashOAndDashR(self): + def test_dash_o_and_dash_r(self): d = { "cogfile.txt": """\ # Please run cog """ } - makeFiles(d) + make_files(d) with self.assertRaisesRegex( CogUsageError, r"^Can't use -o with -r \(they are opposites\)$" ): - self.cog.callableMain(["argv0", "-o", "foo", "-r", "cogfile.txt"]) + self.cog.callable_main(["argv0", "-o", "foo", "-r", "cogfile.txt"]) - def testDashZ(self): + def test_dash_z(self): d = { "test.cog": """\ // This is my C++ file. @@ -878,32 +878,32 @@ def testDashZ(self): """, } - makeFiles(d) + make_files(d) with self.assertRaisesRegex( CogError, r"^test.cog\(6\): Missing '\[\[\[end\]\]\]' before end of file.$" ): - self.cog.callableMain(["argv0", "-r", "test.cog"]) - self.newCog() - self.cog.callableMain(["argv0", "-r", "-z", "test.cog"]) + self.cog.callable_main(["argv0", "-r", "test.cog"]) + self.new_cog() + self.cog.callable_main(["argv0", "-r", "-z", "test.cog"]) self.assertFilesSame("test.cog", "test.out") - def testBadDashD(self): + def test_bad_dash_d(self): with self.assertRaisesRegex(CogUsageError, r"^-D takes a name=value argument$"): - self.cog.callableMain(["argv0", "-Dfooey", "cog.txt"]) + self.cog.callable_main(["argv0", "-Dfooey", "cog.txt"]) with self.assertRaisesRegex(CogUsageError, r"^-D takes a name=value argument$"): - self.cog.callableMain(["argv0", "-D", "fooey", "cog.txt"]) + self.cog.callable_main(["argv0", "-D", "fooey", "cog.txt"]) - def testBadMarkers(self): + def test_bad_markers(self): with self.assertRaisesRegex( CogUsageError, r"^--markers requires 3 values separated by spaces, could not parse 'X'$", ): - self.cog.callableMain(["argv0", "--markers=X"]) + self.cog.callable_main(["argv0", "--markers=X"]) with self.assertRaisesRegex( CogUsageError, r"^--markers requires 3 values separated by spaces, could not parse 'A B C D'$", ): - self.cog.callableMain(["argv0", "--markers=A B C D"]) + self.cog.callable_main(["argv0", "--markers=A B C D"]) class TestMain(TestCaseWithTempDir): @@ -954,10 +954,10 @@ def test_error_report_with_prologue(self): def check_error_report(self, *args): """Check that the error report is right.""" - makeFiles(self.files) + make_files(self.files) sys.argv = ["argv0"] + list(args) + ["-r", "test.cog"] main() - expected = reindentBlock("""\ + expected = reindent_block("""\ Traceback (most recent call last): File "test.cog", line 9, in func() @@ -971,10 +971,10 @@ def check_error_report(self, *args): assert expected == sys.stderr.getvalue() def test_error_in_prologue(self): - makeFiles(self.files) + make_files(self.files) sys.argv = ["argv0", "-p", "import mycode; mycode.boom()", "-r", "test.cog"] main() - expected = reindentBlock("""\ + expected = reindent_block("""\ Traceback (most recent call last): File "", line 1, in import mycode; mycode.boom() @@ -987,7 +987,7 @@ def test_error_in_prologue(self): class TestFileHandling(TestCaseWithTempDir): - def testSimple(self): + def test_simple(self): d = { "test.cog": """\ // This is my C++ file. @@ -1012,13 +1012,13 @@ def testSimple(self): """, } - makeFiles(d) - self.cog.callableMain(["argv0", "-r", "test.cog"]) + make_files(d) + self.cog.callable_main(["argv0", "-r", "test.cog"]) self.assertFilesSame("test.cog", "test.out") output = self.output.getvalue() self.assertIn("(changed)", output) - def testPrintOutput(self): + def test_print_output(self): d = { "test.cog": """\ // This is my C++ file. @@ -1043,13 +1043,13 @@ def testPrintOutput(self): """, } - makeFiles(d) - self.cog.callableMain(["argv0", "-rP", "test.cog"]) + make_files(d) + self.cog.callable_main(["argv0", "-rP", "test.cog"]) self.assertFilesSame("test.cog", "test.out") output = self.output.getvalue() self.assertIn("(changed)", output) - def testWildcards(self): + def test_wildcards(self): d = { "test.cog": """\ // This is my C++ file. @@ -1101,15 +1101,15 @@ def testWildcards(self): """, } - makeFiles(d) - self.cog.callableMain(["argv0", "-r", "t*.cog"]) + make_files(d) + self.cog.callable_main(["argv0", "-r", "t*.cog"]) self.assertFilesSame("test.cog", "test.out") self.assertFilesSame("test2.cog", "test.out") self.assertFilesSame("not_this_one.cog", "not_this_one.out") output = self.output.getvalue() self.assertIn("(changed)", output) - def testOutputFile(self): + def test_output_file(self): # -o sets the output file. d = { "test.cog": """\ @@ -1135,11 +1135,11 @@ def testOutputFile(self): """, } - makeFiles(d) - self.cog.callableMain(["argv0", "-o", "in/a/dir/test.cogged", "test.cog"]) + make_files(d) + self.cog.callable_main(["argv0", "-o", "in/a/dir/test.cogged", "test.cog"]) self.assertFilesSame("in/a/dir/test.cogged", "test.out") - def testAtFile(self): + def test_at_file(self): d = { "one.cog": """\ //[[[cog @@ -1175,14 +1175,14 @@ def testAtFile(self): """, } - makeFiles(d) - self.cog.callableMain(["argv0", "-r", "@cogfiles.txt"]) + make_files(d) + self.cog.callable_main(["argv0", "-r", "@cogfiles.txt"]) self.assertFilesSame("one.cog", "one.out") self.assertFilesSame("two.cog", "two.out") output = self.output.getvalue() self.assertIn("(changed)", output) - def testNestedAtFile(self): + def test_nested_at_file(self): d = { "one.cog": """\ //[[[cog @@ -1221,14 +1221,14 @@ def testNestedAtFile(self): """, } - makeFiles(d) - self.cog.callableMain(["argv0", "-r", "@cogfiles.txt"]) + make_files(d) + self.cog.callable_main(["argv0", "-r", "@cogfiles.txt"]) self.assertFilesSame("one.cog", "one.out") self.assertFilesSame("two.cog", "two.out") output = self.output.getvalue() self.assertIn("(changed)", output) - def testAtFileWithArgs(self): + def test_at_file_with_args(self): d = { "both.cog": """\ //[[[cog @@ -1262,12 +1262,12 @@ def testAtFileWithArgs(self): """, } - makeFiles(d) - self.cog.callableMain(["argv0", "@cogfiles.txt"]) + make_files(d) + self.cog.callable_main(["argv0", "@cogfiles.txt"]) self.assertFilesSame("in/a/dir/both.one", "one.out") self.assertFilesSame("in/a/dir/both.two", "two.out") - def testAtFileWithBadArgCombo(self): + def test_at_file_with_bad_arg_combo(self): d = { "both.cog": """\ //[[[cog @@ -1283,14 +1283,14 @@ def testAtFileWithBadArgCombo(self): """, } - makeFiles(d) + make_files(d) with self.assertRaisesRegex( CogUsageError, r"^Can't use -d with -r \(or you would delete all your source!\)$", ): - self.cog.callableMain(["argv0", "-r", "@cogfiles.txt"]) + self.cog.callable_main(["argv0", "-r", "@cogfiles.txt"]) - def testAtFileWithTrickyFilenames(self): + def test_at_file_with_tricky_filenames(self): def fix_backslashes(files_txt): """Make the contents of a files.txt sensitive to the platform.""" if sys.platform != "win32": @@ -1329,13 +1329,13 @@ def fix_backslashes(files_txt): """), } - makeFiles(d) - self.cog.callableMain(["argv0", "-z", "-r", "@cogfiles.txt"]) + make_files(d) + self.cog.callable_main(["argv0", "-z", "-r", "@cogfiles.txt"]) self.assertFilesSame("one 1.cog", "one.out") self.assertFilesSame("subdir/subback.cog", "subback.out") self.assertFilesSame("subdir/subfwd.cog", "subfwd.out") - def testAmpFile(self): + def test_amp_file(self): d = { "code": { "files_to_cog": """\ @@ -1362,9 +1362,9 @@ def testAmpFile(self): } } - makeFiles(d) + make_files(d) print(os.path.abspath("code/test.out")) - self.cog.callableMain(["argv0", "-r", "&code/files_to_cog"]) + self.cog.callable_main(["argv0", "-r", "&code/files_to_cog"]) self.assertFilesSame("code/test.cog", "code/test.out") def run_with_verbosity(self, verbosity): @@ -1388,8 +1388,8 @@ def run_with_verbosity(self, verbosity): """, } - makeFiles(d) - self.cog.callableMain( + make_files(d) + self.cog.callable_main( ["argv0", "-r", "--verbosity=" + verbosity, "@cogfiles.txt"] ) output = self.output.getvalue() @@ -1435,29 +1435,29 @@ class CogTestLineEndings(TestCaseWithTempDir): "", ] - def testOutputNativeEol(self): - makeFiles({"infile": "\n".join(self.lines_in)}) - self.cog.callableMain(["argv0", "-o", "outfile", "infile"]) + def test_output_native_eol(self): + make_files({"infile": "\n".join(self.lines_in)}) + self.cog.callable_main(["argv0", "-o", "outfile", "infile"]) self.assertFileContent("outfile", os.linesep.join(self.lines_out)) - def testOutputLfEol(self): - makeFiles({"infile": "\n".join(self.lines_in)}) - self.cog.callableMain(["argv0", "-U", "-o", "outfile", "infile"]) + def test_output_lf_eol(self): + make_files({"infile": "\n".join(self.lines_in)}) + self.cog.callable_main(["argv0", "-U", "-o", "outfile", "infile"]) self.assertFileContent("outfile", "\n".join(self.lines_out)) - def testReplaceNativeEol(self): - makeFiles({"test.cog": "\n".join(self.lines_in)}) - self.cog.callableMain(["argv0", "-r", "test.cog"]) + def test_replace_native_eol(self): + make_files({"test.cog": "\n".join(self.lines_in)}) + self.cog.callable_main(["argv0", "-r", "test.cog"]) self.assertFileContent("test.cog", os.linesep.join(self.lines_out)) - def testReplaceLfEol(self): - makeFiles({"test.cog": "\n".join(self.lines_in)}) - self.cog.callableMain(["argv0", "-U", "-r", "test.cog"]) + def test_replace_lf_eol(self): + make_files({"test.cog": "\n".join(self.lines_in)}) + self.cog.callable_main(["argv0", "-U", "-r", "test.cog"]) self.assertFileContent("test.cog", "\n".join(self.lines_out)) class CogTestCharacterEncoding(TestCaseWithTempDir): - def testSimple(self): + def test_simple(self): d = { "test.cog": b"""\ // This is my C++ file. @@ -1476,13 +1476,13 @@ def testSimple(self): """.replace(b"\n", os.linesep.encode()), } - makeFiles(d) - self.cog.callableMain(["argv0", "-r", "test.cog"]) + make_files(d) + self.cog.callable_main(["argv0", "-r", "test.cog"]) self.assertFilesSame("test.cog", "test.out") output = self.output.getvalue() self.assertIn("(changed)", output) - def testFileEncodingOption(self): + def test_file_encoding_option(self): d = { "test.cog": b"""\ // \xca\xee\xe4\xe8\xf0\xe2\xea\xe0 Windows @@ -1501,8 +1501,8 @@ def testFileEncodingOption(self): """.replace(b"\n", os.linesep.encode()), } - makeFiles(d) - self.cog.callableMain(["argv0", "-n", "cp1251", "-r", "test.cog"]) + make_files(d) + self.cog.callable_main(["argv0", "-n", "cp1251", "-r", "test.cog"]) self.assertFilesSame("test.cog", "test.out") output = self.output.getvalue() self.assertIn("(changed)", output) @@ -1572,44 +1572,44 @@ class CogIncludeTests(TestCaseWithImports): }, } - def testNeedIncludePath(self): + def test_need_include_path(self): # Try it without the -I, to see that an ImportError happens. - makeFiles(self.dincludes) + make_files(self.dincludes) msg = "(ImportError|ModuleNotFoundError): No module named '?mymodule'?" with self.assertRaisesRegex(CogUserException, msg): - self.cog.callableMain(["argv0", "-r", "test.cog"]) + self.cog.callable_main(["argv0", "-r", "test.cog"]) - def testIncludePath(self): + def test_include_path(self): # Test that -I adds include directories properly. - makeFiles(self.dincludes) - self.cog.callableMain(["argv0", "-r", "-I", "include", "test.cog"]) + make_files(self.dincludes) + self.cog.callable_main(["argv0", "-r", "-I", "include", "test.cog"]) self.assertFilesSame("test.cog", "test.out") - def testTwoIncludePaths(self): + def test_two_include_paths(self): # Test that two -I's add include directories properly. - makeFiles(self.dincludes) - self.cog.callableMain( + make_files(self.dincludes) + self.cog.callable_main( ["argv0", "-r", "-I", "include", "-I", "inc2", "test.cog"] ) self.assertFilesSame("test.cog", "test.out") - def testTwoIncludePaths2(self): + def test_two_include_paths2(self): # Test that two -I's add include directories properly. - makeFiles(self.dincludes) - self.cog.callableMain( + make_files(self.dincludes) + self.cog.callable_main( ["argv0", "-r", "-I", "inc2", "-I", "include", "test.cog"] ) self.assertFilesSame("test.cog", "test2.out") - def testUselessIncludePath(self): + def test_useless_include_path(self): # Test that the search will continue past the first directory. - makeFiles(self.dincludes) - self.cog.callableMain( + make_files(self.dincludes) + self.cog.callable_main( ["argv0", "-r", "-I", "inc3", "-I", "include", "test.cog"] ) self.assertFilesSame("test.cog", "test.out") - def testSysPathIsUnchanged(self): + def test_sys_path_is_unchanged(self): d = { "bad.cog": """\ //[[[cog cog.error("Oh no!") ]]] @@ -1621,42 +1621,42 @@ def testSysPathIsUnchanged(self): """, } - makeFiles(d) + make_files(d) # Is it unchanged just by creating a cog engine? oldsyspath = sys.path[:] - self.newCog() + self.new_cog() self.assertEqual(oldsyspath, sys.path) # Is it unchanged for a successful run? - self.newCog() - self.cog.callableMain(["argv0", "-r", "good.cog"]) + self.new_cog() + self.cog.callable_main(["argv0", "-r", "good.cog"]) self.assertEqual(oldsyspath, sys.path) # Is it unchanged for a successful run with includes? - self.newCog() - self.cog.callableMain(["argv0", "-r", "-I", "xyzzy", "good.cog"]) + self.new_cog() + self.cog.callable_main(["argv0", "-r", "-I", "xyzzy", "good.cog"]) self.assertEqual(oldsyspath, sys.path) # Is it unchanged for a successful run with two includes? - self.newCog() - self.cog.callableMain(["argv0", "-r", "-I", "xyzzy", "-I", "quux", "good.cog"]) + self.new_cog() + self.cog.callable_main(["argv0", "-r", "-I", "xyzzy", "-I", "quux", "good.cog"]) self.assertEqual(oldsyspath, sys.path) # Is it unchanged for a failed run? - self.newCog() + self.new_cog() with self.assertRaisesRegex(CogError, r"^Oh no!$"): - self.cog.callableMain(["argv0", "-r", "bad.cog"]) + self.cog.callable_main(["argv0", "-r", "bad.cog"]) self.assertEqual(oldsyspath, sys.path) # Is it unchanged for a failed run with includes? - self.newCog() + self.new_cog() with self.assertRaisesRegex(CogError, r"^Oh no!$"): - self.cog.callableMain(["argv0", "-r", "-I", "xyzzy", "bad.cog"]) + self.cog.callable_main(["argv0", "-r", "-I", "xyzzy", "bad.cog"]) self.assertEqual(oldsyspath, sys.path) # Is it unchanged for a failed run with two includes? - self.newCog() + self.new_cog() with self.assertRaisesRegex(CogError, r"^Oh no!$"): - self.cog.callableMain( + self.cog.callable_main( ["argv0", "-r", "-I", "xyzzy", "-I", "quux", "bad.cog"] ) self.assertEqual(oldsyspath, sys.path) - def testSubDirectories(self): + def test_sub_directories(self): # Test that relative paths on the command line work, with includes. d = { @@ -1681,15 +1681,15 @@ def testSubDirectories(self): } } - makeFiles(d) + make_files(d) # We should be able to invoke cog without the -I switch, and it will # auto-include the current directory - self.cog.callableMain(["argv0", "-r", "code/test.cog"]) + self.cog.callable_main(["argv0", "-r", "code/test.cog"]) self.assertFilesSame("code/test.cog", "code/test.out") class CogTestsInFiles(TestCaseWithTempDir): - def testWarnIfNoCogCode(self): + def test_warn_if_no_cog_code(self): # Test that the -e switch warns if there is no Cog code. d = { "with.cog": """\ @@ -1705,20 +1705,20 @@ def testWarnIfNoCogCode(self): """, } - makeFiles(d) - self.cog.callableMain(["argv0", "-e", "with.cog"]) + make_files(d) + self.cog.callable_main(["argv0", "-e", "with.cog"]) output = self.output.getvalue() self.assertNotIn("Warning", output) - self.newCog() - self.cog.callableMain(["argv0", "-e", "without.cog"]) + self.new_cog() + self.cog.callable_main(["argv0", "-e", "without.cog"]) output = self.output.getvalue() self.assertIn("Warning: no cog code found in without.cog", output) - self.newCog() - self.cog.callableMain(["argv0", "without.cog"]) + self.new_cog() + self.cog.callable_main(["argv0", "without.cog"]) output = self.output.getvalue() self.assertNotIn("Warning", output) - def testFileNameProps(self): + def test_file_name_props(self): d = { "cog1.txt": """\ //[[[cog @@ -1743,14 +1743,14 @@ def testFileNameProps(self): """, } - makeFiles(d) - self.cog.callableMain(["argv0", "-r", "cog1.txt"]) + make_files(d) + self.cog.callable_main(["argv0", "-r", "cog1.txt"]) self.assertFilesSame("cog1.txt", "cog1.out") - self.newCog() - self.cog.callableMain(["argv0", "-o", "cog1out.txt", "cog1.txt"]) + self.new_cog() + self.cog.callable_main(["argv0", "-o", "cog1out.txt", "cog1.txt"]) self.assertFilesSame("cog1out.txt", "cog1out.out") - def testGlobalsDontCrossFiles(self): + def test_globals_dont_cross_files(self): # Make sure that global values don't get shared between files. d = { "one.cog": """\ @@ -1793,14 +1793,14 @@ def testGlobalsDontCrossFiles(self): """, } - makeFiles(d) - self.cog.callableMain(["argv0", "-r", "@cogfiles.txt"]) + make_files(d) + self.cog.callable_main(["argv0", "-r", "@cogfiles.txt"]) self.assertFilesSame("one.cog", "one.out") self.assertFilesSame("two.cog", "two.out") output = self.output.getvalue() self.assertIn("(changed)", output) - def testRemoveGeneratedOutput(self): + def test_remove_generated_output(self): d = { "cog1.txt": """\ //[[[cog @@ -1827,32 +1827,32 @@ def testRemoveGeneratedOutput(self): """, } - makeFiles(d) + make_files(d) # Remove generated output. - self.cog.callableMain(["argv0", "-r", "-x", "cog1.txt"]) + self.cog.callable_main(["argv0", "-r", "-x", "cog1.txt"]) self.assertFilesSame("cog1.txt", "cog1.out") - self.newCog() + self.new_cog() # Regenerate the generated output. - self.cog.callableMain(["argv0", "-r", "cog1.txt"]) + self.cog.callable_main(["argv0", "-r", "cog1.txt"]) self.assertFilesSame("cog1.txt", "cog1.out2") - self.newCog() + self.new_cog() # Remove the generated output again. - self.cog.callableMain(["argv0", "-r", "-x", "cog1.txt"]) + self.cog.callable_main(["argv0", "-r", "-x", "cog1.txt"]) self.assertFilesSame("cog1.txt", "cog1.out") - def testMsgCall(self): + def test_msg_call(self): infile = """\ #[[[cog cog.msg("Hello there!") #]]] #[[[end]]] """ - infile = reindentBlock(infile) - self.assertEqual(self.cog.processString(infile), infile) + infile = reindent_block(infile) + self.assertEqual(self.cog.process_string(infile), infile) output = self.output.getvalue() self.assertEqual(output, "Message: Hello there!\n") - def testErrorMessageHasNoTraceback(self): + def test_error_message_has_no_traceback(self): # Test that a Cog error is printed to stderr with no traceback. d = { @@ -1869,9 +1869,9 @@ def testErrorMessageHasNoTraceback(self): """, } - makeFiles(d) + make_files(d) stderr = io.StringIO() - self.cog.setOutput(stderr=stderr) + self.cog.set_output(stderr=stderr) self.cog.main(["argv0", "-c", "-r", "cog1.txt"]) self.assertEqual(self.output.getvalue(), "Cogging cog1.txt\n") self.assertEqual( @@ -1879,7 +1879,7 @@ def testErrorMessageHasNoTraceback(self): "cog1.txt(9): Output has been edited! Delete old checksum to unprotect.\n", ) - def testDashD(self): + def test_dash_d(self): d = { "test.cog": """\ --[[[cog cog.outl("Defined fooey as " + fooey) ]]] @@ -1897,32 +1897,32 @@ def testDashD(self): """, } - makeFiles(d) - self.cog.callableMain(["argv0", "-r", "-D", "fooey=kablooey", "test.cog"]) + make_files(d) + self.cog.callable_main(["argv0", "-r", "-D", "fooey=kablooey", "test.cog"]) self.assertFilesSame("test.cog", "test.kablooey") - makeFiles(d) - self.cog.callableMain(["argv0", "-r", "-Dfooey=kablooey", "test.cog"]) + make_files(d) + self.cog.callable_main(["argv0", "-r", "-Dfooey=kablooey", "test.cog"]) self.assertFilesSame("test.cog", "test.kablooey") - makeFiles(d) - self.cog.callableMain(["argv0", "-r", "-Dfooey=e=mc2", "test.cog"]) + make_files(d) + self.cog.callable_main(["argv0", "-r", "-Dfooey=e=mc2", "test.cog"]) self.assertFilesSame("test.cog", "test.einstein") - makeFiles(d) - self.cog.callableMain( + make_files(d) + self.cog.callable_main( ["argv0", "-r", "-Dbar=quux", "-Dfooey=kablooey", "test.cog"] ) self.assertFilesSame("test.cog", "test.kablooey") - makeFiles(d) - self.cog.callableMain( + make_files(d) + self.cog.callable_main( ["argv0", "-r", "-Dfooey=kablooey", "-Dbar=quux", "test.cog"] ) self.assertFilesSame("test.cog", "test.kablooey") - makeFiles(d) - self.cog.callableMain( + make_files(d) + self.cog.callable_main( ["argv0", "-r", "-Dfooey=gooey", "-Dfooey=kablooey", "test.cog"] ) self.assertFilesSame("test.cog", "test.kablooey") - def testOutputToStdout(self): + def test_output_to_stdout(self): d = { "test.cog": """\ --[[[cog cog.outl('Hey there!') ]]] @@ -1930,10 +1930,10 @@ def testOutputToStdout(self): """ } - makeFiles(d) + make_files(d) stderr = io.StringIO() - self.cog.setOutput(stderr=stderr) - self.cog.callableMain(["argv0", "test.cog"]) + self.cog.set_output(stderr=stderr) + self.cog.callable_main(["argv0", "test.cog"]) output = self.output.getvalue() outerr = stderr.getvalue() self.assertEqual( @@ -1941,7 +1941,7 @@ def testOutputToStdout(self): ) self.assertEqual(outerr, "") - def testReadFromStdin(self): + def test_read_from_stdin(self): stdin = io.StringIO("--[[[cog cog.outl('Wow') ]]]\n--[[[end]]]\n") def restore_stdin(old_stdin): @@ -1951,14 +1951,14 @@ def restore_stdin(old_stdin): sys.stdin = stdin stderr = io.StringIO() - self.cog.setOutput(stderr=stderr) - self.cog.callableMain(["argv0", "-"]) + self.cog.set_output(stderr=stderr) + self.cog.callable_main(["argv0", "-"]) output = self.output.getvalue() outerr = stderr.getvalue() self.assertEqual(output, "--[[[cog cog.outl('Wow') ]]]\nWow\n--[[[end]]]\n") self.assertEqual(outerr, "") - def testSuffixOutputLines(self): + def test_suffix_output_lines(self): d = { "test.cog": """\ Hey there. @@ -1980,11 +1980,11 @@ def testSuffixOutputLines(self): """, } - makeFiles(d) - self.cog.callableMain(["argv0", "-r", "-s", " (foo)", "test.cog"]) + make_files(d) + self.cog.callable_main(["argv0", "-r", "-s", " (foo)", "test.cog"]) self.assertFilesSame("test.cog", "test.out") - def testEmptySuffix(self): + def test_empty_suffix(self): d = { "test.cog": """\ ;[[[cog cog.outl('a\\nb\\nc') ]]] @@ -1999,11 +1999,11 @@ def testEmptySuffix(self): """, } - makeFiles(d) - self.cog.callableMain(["argv0", "-r", "-s", "", "test.cog"]) + make_files(d) + self.cog.callable_main(["argv0", "-r", "-s", "", "test.cog"]) self.assertFilesSame("test.cog", "test.out") - def testHellishSuffix(self): + def test_hellish_suffix(self): d = { "test.cog": """\ ;[[[cog cog.outl('a\\n\\nb') ]]] @@ -2016,11 +2016,11 @@ def testHellishSuffix(self): """, } - makeFiles(d) - self.cog.callableMain(["argv0", "-z", "-r", "-s", r" /\n*+([)]><", "test.cog"]) + make_files(d) + self.cog.callable_main(["argv0", "-z", "-r", "-s", r" /\n*+([)]><", "test.cog"]) self.assertFilesSame("test.cog", "test.out") - def testPrologue(self): + def test_prologue(self): d = { "test.cog": """\ Some text. @@ -2037,11 +2037,11 @@ def testPrologue(self): """, } - makeFiles(d) - self.cog.callableMain(["argv0", "-r", "-p", "import math", "test.cog"]) + make_files(d) + self.cog.callable_main(["argv0", "-r", "-p", "import math", "test.cog"]) self.assertFilesSame("test.cog", "test.out") - def testThreads(self): + def test_threads(self): # Test that the implicitly imported cog module is actually different for # different threads. numthreads = 20 @@ -2055,7 +2055,7 @@ def testThreads(self): + "]]]\n" + "[[[end]]]\n" ) - makeFiles(d) + make_files(d) results = [] @@ -2088,7 +2088,7 @@ def run_check(self, args, status=0): def assert_made_files_unchanged(self, d): for name, content in d.items(): - content = reindentBlock(content) + content = reindent_block(content) if os.name == "nt": content = content.replace("\n", "\r\n") self.assertFileContent(name, content) @@ -2099,7 +2099,7 @@ def test_check_no_cog(self): Hello. """, } - makeFiles(d) + make_files(d) self.run_check(["hello.txt"], status=0) self.assertEqual(self.output.getvalue(), "Checking hello.txt\n") self.assert_made_files_unchanged(d) @@ -2114,7 +2114,7 @@ def test_check_good(self): //[[[end]]] """, } - makeFiles(d) + make_files(d) self.run_check(["unchanged.cog"], status=0) self.assertEqual(self.output.getvalue(), "Checking unchanged.cog\n") self.assert_made_files_unchanged(d) @@ -2129,7 +2129,7 @@ def test_check_bad(self): //[[[end]]] """, } - makeFiles(d) + make_files(d) self.run_check(["changed.cog"], status=5) self.assertEqual( self.output.getvalue(), "Checking changed.cog (changed)\nCheck failed\n" @@ -2153,7 +2153,7 @@ def test_check_mixed(self): //[[[end]]] """, } - makeFiles(d) + make_files(d) for verbosity, output in [ ("0", "Check failed\n"), ("1", "Checking changed.cog (changed)\nCheck failed\n"), @@ -2162,7 +2162,7 @@ def test_check_mixed(self): "Checking unchanged.cog\nChecking changed.cog (changed)\nCheck failed\n", ), ]: - self.newCog() + self.new_cog() self.run_check( ["--verbosity=%s" % verbosity, "unchanged.cog", "changed.cog"], status=5 ) @@ -2183,7 +2183,7 @@ def test_check_with_good_checksum(self): //[[[end]]] (checksum: a8540982e5ad6b95c9e9a184b26f4346) """, } - makeFiles(d) + make_files(d) # Have to use -c with --check if there are checksums in the file. self.run_check(["-c", "good.txt"], status=0) self.assertEqual(self.output.getvalue(), "Checking good.txt\n") @@ -2203,7 +2203,7 @@ def test_check_with_bad_checksum(self): //[[[end]]] (checksum: a9999999e5ad6b95c9e9a184b26f4346) """, } - makeFiles(d) + make_files(d) # Have to use -c with --check if there are checksums in the file. self.run_check(["-c", "bad.txt"], status=1) self.assertEqual( @@ -2245,7 +2245,7 @@ class WritabilityTests(TestCaseWithTempDir): def setUp(self): super().setUp() - makeFiles(self.d) + make_files(self.d) self.testcog = os.path.join(self.tempdir, "test.cog") os.chmod(self.testcog, stat.S_IREAD) # Make the file readonly. assert not os.access(self.testcog, os.W_OK) @@ -2254,29 +2254,29 @@ def tearDown(self): os.chmod(self.testcog, stat.S_IWRITE) # Make the file writable again. super().tearDown() - def testReadonlyNoCommand(self): + def test_readonly_no_command(self): with self.assertRaisesRegex(CogError, "^Can't overwrite test.cog$"): - self.cog.callableMain(["argv0", "-r", "test.cog"]) + self.cog.callable_main(["argv0", "-r", "test.cog"]) assert not os.access(self.testcog, os.W_OK) - def testReadonlyWithCommand(self): - self.cog.callableMain(["argv0", "-r", "-w", self.cmd_w_args, "test.cog"]) + def test_readonly_with_command(self): + self.cog.callable_main(["argv0", "-r", "-w", self.cmd_w_args, "test.cog"]) self.assertFilesSame("test.cog", "test.out") assert os.access(self.testcog, os.W_OK) - def testReadonlyWithCommandWithNoSlot(self): - self.cog.callableMain(["argv0", "-r", "-w", self.cmd_w_asterisk, "test.cog"]) + def test_readonly_with_command_with_no_slot(self): + self.cog.callable_main(["argv0", "-r", "-w", self.cmd_w_asterisk, "test.cog"]) self.assertFilesSame("test.cog", "test.out") assert os.access(self.testcog, os.W_OK) - def testReadonlyWithIneffectualCommand(self): + def test_readonly_with_ineffectual_command(self): with self.assertRaisesRegex(CogError, "^Couldn't make test.cog writable$"): - self.cog.callableMain(["argv0", "-r", "-w", "echo %s", "test.cog"]) + self.cog.callable_main(["argv0", "-r", "-w", "echo %s", "test.cog"]) assert not os.access(self.testcog, os.W_OK) class ChecksumTests(TestCaseWithTempDir): - def testCreateChecksumOutput(self): + def test_create_checksum_output(self): d = { "cog1.txt": """\ //[[[cog @@ -2296,11 +2296,11 @@ def testCreateChecksumOutput(self): """, } - makeFiles(d) - self.cog.callableMain(["argv0", "-r", "-c", "cog1.txt"]) + make_files(d) + self.cog.callable_main(["argv0", "-r", "-c", "cog1.txt"]) self.assertFilesSame("cog1.txt", "cog1.out") - def testCheckChecksumOutput(self): + def test_check_checksum_output(self): d = { "cog1.txt": """\ //[[[cog @@ -2324,11 +2324,11 @@ def testCheckChecksumOutput(self): """, } - makeFiles(d) - self.cog.callableMain(["argv0", "-r", "-c", "cog1.txt"]) + make_files(d) + self.cog.callable_main(["argv0", "-r", "-c", "cog1.txt"]) self.assertFilesSame("cog1.txt", "cog1.out") - def testRemoveChecksumOutput(self): + def test_remove_checksum_output(self): d = { "cog1.txt": """\ //[[[cog @@ -2352,11 +2352,11 @@ def testRemoveChecksumOutput(self): """, } - makeFiles(d) - self.cog.callableMain(["argv0", "-r", "cog1.txt"]) + make_files(d) + self.cog.callable_main(["argv0", "-r", "cog1.txt"]) self.assertFilesSame("cog1.txt", "cog1.out") - def testTamperedChecksumOutput(self): + def test_tampered_checksum_output(self): d = { "cog1.txt": """\ //[[[cog @@ -2425,47 +2425,47 @@ def testTamperedChecksumOutput(self): """, } - makeFiles(d) + make_files(d) with self.assertRaisesRegex( CogError, r"^cog1.txt\(9\): Output has been edited! Delete old checksum to unprotect.$", ): - self.cog.callableMain(["argv0", "-c", "cog1.txt"]) + self.cog.callable_main(["argv0", "-c", "cog1.txt"]) with self.assertRaisesRegex( CogError, r"^cog2.txt\(9\): Output has been edited! Delete old checksum to unprotect.$", ): - self.cog.callableMain(["argv0", "-c", "cog2.txt"]) + self.cog.callable_main(["argv0", "-c", "cog2.txt"]) with self.assertRaisesRegex( CogError, r"^cog3.txt\(10\): Output has been edited! Delete old checksum to unprotect.$", ): - self.cog.callableMain(["argv0", "-c", "cog3.txt"]) + self.cog.callable_main(["argv0", "-c", "cog3.txt"]) with self.assertRaisesRegex( CogError, r"^cog4.txt\(9\): Output has been edited! Delete old checksum to unprotect.$", ): - self.cog.callableMain(["argv0", "-c", "cog4.txt"]) + self.cog.callable_main(["argv0", "-c", "cog4.txt"]) with self.assertRaisesRegex( CogError, r"^cog5.txt\(10\): Output has been edited! Delete old checksum to unprotect.$", ): - self.cog.callableMain(["argv0", "-c", "cog5.txt"]) + self.cog.callable_main(["argv0", "-c", "cog5.txt"]) with self.assertRaisesRegex( CogError, r"^cog6.txt\(6\): Output has been edited! Delete old checksum to unprotect.$", ): - self.cog.callableMain(["argv0", "-c", "cog6.txt"]) + self.cog.callable_main(["argv0", "-c", "cog6.txt"]) - def testArgvIsntModified(self): + def test_argv_isnt_modified(self): argv = ["argv0", "-v"] orig_argv = argv[:] - self.cog.callableMain(argv) + self.cog.callable_main(argv) self.assertEqual(argv, orig_argv) class CustomMarkerTests(TestCaseWithTempDir): - def testCustomerMarkers(self): + def test_customer_markers(self): d = { "test.cog": """\ //{{ @@ -2482,11 +2482,11 @@ def testCustomerMarkers(self): """, } - makeFiles(d) - self.cog.callableMain(["argv0", "-r", "--markers={{ }} {{end}}", "test.cog"]) + make_files(d) + self.cog.callable_main(["argv0", "-r", "--markers={{ }} {{end}}", "test.cog"]) self.assertFilesSame("test.cog", "test.out") - def testTrulyWackyMarkers(self): + def test_truly_wacky_markers(self): # Make sure the markers are properly re-escaped. d = { "test.cog": """\ @@ -2504,13 +2504,13 @@ def testTrulyWackyMarkers(self): """, } - makeFiles(d) - self.cog.callableMain( + make_files(d) + self.cog.callable_main( ["argv0", "-r", "--markers=**( **) **(end)**", "test.cog"] ) self.assertFilesSame("test.cog", "test.out") - def testChangeJustOneMarker(self): + def test_change_just_one_marker(self): d = { "test.cog": """\ //**( @@ -2527,8 +2527,8 @@ def testChangeJustOneMarker(self): """, } - makeFiles(d) - self.cog.callableMain( + make_files(d) + self.cog.callable_main( ["argv0", "-r", "--markers=**( ]]] [[[end]]]", "test.cog"] ) self.assertFilesSame("test.cog", "test.out") @@ -2536,7 +2536,7 @@ def testChangeJustOneMarker(self): class BlakeTests(TestCaseWithTempDir): # Blake Winton's contributions. - def testDeleteCode(self): + def test_delete_code(self): # -o sets the output file. d = { "test.cog": """\ @@ -2559,25 +2559,25 @@ def testDeleteCode(self): """, } - makeFiles(d) - self.cog.callableMain(["argv0", "-d", "-o", "test.cogged", "test.cog"]) + make_files(d) + self.cog.callable_main(["argv0", "-d", "-o", "test.cogged", "test.cog"]) self.assertFilesSame("test.cogged", "test.out") - def testDeleteCodeWithDashRFails(self): + def test_delete_code_with_dash_r_fails(self): d = { "test.cog": """\ // This is my C++ file. """ } - makeFiles(d) + make_files(d) with self.assertRaisesRegex( CogUsageError, r"^Can't use -d with -r \(or you would delete all your source!\)$", ): - self.cog.callableMain(["argv0", "-r", "-d", "test.cog"]) + self.cog.callable_main(["argv0", "-r", "-d", "test.cog"]) - def testSettingGlobals(self): + def test_setting_globals(self): # Blake Winton contributed a way to set the globals that will be used in # processFile(). d = { @@ -2597,16 +2597,16 @@ def testSettingGlobals(self): """, } - makeFiles(d) + make_files(d) globals = {} globals["fnames"] = ["DoBlake", "DoWinton", "DoContribution"] - self.cog.options.deleteCode = True - self.cog.processFile("test.cog", "test.cogged", globals=globals) + self.cog.options.delete_code = True + self.cog.process_file("test.cog", "test.cogged", globals=globals) self.assertFilesSame("test.cogged", "test.out") class ErrorCallTests(TestCaseWithTempDir): - def testErrorCallHasNoTraceback(self): + def test_error_call_has_no_traceback(self): # Test that cog.error() doesn't show a traceback. d = { "error.cog": """\ @@ -2617,12 +2617,12 @@ def testErrorCallHasNoTraceback(self): """, } - makeFiles(d) + make_files(d) self.cog.main(["argv0", "-r", "error.cog"]) output = self.output.getvalue() self.assertEqual(output, "Cogging error.cog\nError: Something Bad!\n") - def testRealErrorHasTraceback(self): + def test_real_error_has_traceback(self): # Test that a genuine error does show a traceback. d = { "error.cog": """\ @@ -2633,7 +2633,7 @@ def testRealErrorHasTraceback(self): """, } - makeFiles(d) + make_files(d) self.cog.main(["argv0", "-r", "error.cog"]) output = self.output.getvalue() msg = "Actual output:\n" + output diff --git a/cogapp/test_makefiles.py b/cogapp/test_makefiles.py index 3cff6a5..d33e355 100644 --- a/cogapp/test_makefiles.py +++ b/cogapp/test_makefiles.py @@ -23,32 +23,32 @@ def tearDown(self): def exists(self, dname, fname): return os.path.exists(os.path.join(dname, fname)) - def checkFilesExist(self, d, dname): + def check_files_exist(self, d, dname): for fname in d.keys(): assert self.exists(dname, fname) if isinstance(d[fname], dict): - self.checkFilesExist(d[fname], os.path.join(dname, fname)) + self.check_files_exist(d[fname], os.path.join(dname, fname)) - def checkFilesDontExist(self, d, dname): + def check_files_dont_exist(self, d, dname): for fname in d.keys(): assert not self.exists(dname, fname) - def testOneFile(self): + def test_one_file(self): fname = "foo.txt" notfname = "not_here.txt" d = {fname: "howdy"} assert not self.exists(self.tempdir, fname) assert not self.exists(self.tempdir, notfname) - makefiles.makeFiles(d, self.tempdir) + makefiles.make_files(d, self.tempdir) assert self.exists(self.tempdir, fname) assert not self.exists(self.tempdir, notfname) - makefiles.removeFiles(d, self.tempdir) + makefiles.remove_files(d, self.tempdir) assert not self.exists(self.tempdir, fname) assert not self.exists(self.tempdir, notfname) - def testManyFiles(self): + def test_many_files(self): d = { "top1.txt": "howdy", "top2.txt": "hello", @@ -58,13 +58,13 @@ def testManyFiles(self): }, } - self.checkFilesDontExist(d, self.tempdir) - makefiles.makeFiles(d, self.tempdir) - self.checkFilesExist(d, self.tempdir) - makefiles.removeFiles(d, self.tempdir) - self.checkFilesDontExist(d, self.tempdir) + self.check_files_dont_exist(d, self.tempdir) + makefiles.make_files(d, self.tempdir) + self.check_files_exist(d, self.tempdir) + makefiles.remove_files(d, self.tempdir) + self.check_files_dont_exist(d, self.tempdir) - def testOverlapping(self): + def test_overlapping(self): d1 = { "top1.txt": "howdy", "sub": { @@ -79,26 +79,26 @@ def testOverlapping(self): }, } - self.checkFilesDontExist(d1, self.tempdir) - self.checkFilesDontExist(d2, self.tempdir) - makefiles.makeFiles(d1, self.tempdir) - makefiles.makeFiles(d2, self.tempdir) - self.checkFilesExist(d1, self.tempdir) - self.checkFilesExist(d2, self.tempdir) - makefiles.removeFiles(d1, self.tempdir) - makefiles.removeFiles(d2, self.tempdir) - self.checkFilesDontExist(d1, self.tempdir) - self.checkFilesDontExist(d2, self.tempdir) - - def testContents(self): + self.check_files_dont_exist(d1, self.tempdir) + self.check_files_dont_exist(d2, self.tempdir) + makefiles.make_files(d1, self.tempdir) + makefiles.make_files(d2, self.tempdir) + self.check_files_exist(d1, self.tempdir) + self.check_files_exist(d2, self.tempdir) + makefiles.remove_files(d1, self.tempdir) + makefiles.remove_files(d2, self.tempdir) + self.check_files_dont_exist(d1, self.tempdir) + self.check_files_dont_exist(d2, self.tempdir) + + def test_contents(self): fname = "bar.txt" cont0 = "I am bar.txt" d = {fname: cont0} - makefiles.makeFiles(d, self.tempdir) + makefiles.make_files(d, self.tempdir) with open(os.path.join(self.tempdir, fname)) as fcont1: assert fcont1.read() == cont0 - def testDedent(self): + def test_dedent(self): fname = "dedent.txt" d = { fname: """\ @@ -108,7 +108,7 @@ def testDedent(self): OK. """, } - makefiles.makeFiles(d, self.tempdir) + makefiles.make_files(d, self.tempdir) with open(os.path.join(self.tempdir, fname)) as fcont: assert ( fcont.read() == "This is dedent.txt\n\tTabbed in.\n spaced in.\nOK.\n" diff --git a/cogapp/test_whiteutils.py b/cogapp/test_whiteutils.py index 9551e4e..9adeacd 100644 --- a/cogapp/test_whiteutils.py +++ b/cogapp/test_whiteutils.py @@ -2,70 +2,70 @@ from unittest import TestCase -from .whiteutils import commonPrefix, reindentBlock, whitePrefix +from .whiteutils import common_prefix, reindent_block, white_prefix class WhitePrefixTests(TestCase): """Test cases for cogapp.whiteutils.""" - def testSingleLine(self): - self.assertEqual(whitePrefix([""]), "") - self.assertEqual(whitePrefix([" "]), "") - self.assertEqual(whitePrefix(["x"]), "") - self.assertEqual(whitePrefix([" x"]), " ") - self.assertEqual(whitePrefix(["\tx"]), "\t") - self.assertEqual(whitePrefix([" x"]), " ") - self.assertEqual(whitePrefix([" \t \tx "]), " \t \t") + def test_single_line(self): + self.assertEqual(white_prefix([""]), "") + self.assertEqual(white_prefix([" "]), "") + self.assertEqual(white_prefix(["x"]), "") + self.assertEqual(white_prefix([" x"]), " ") + self.assertEqual(white_prefix(["\tx"]), "\t") + self.assertEqual(white_prefix([" x"]), " ") + self.assertEqual(white_prefix([" \t \tx "]), " \t \t") - def testMultiLine(self): - self.assertEqual(whitePrefix([" x", " x", " x"]), " ") - self.assertEqual(whitePrefix([" y", " y", " y"]), " ") - self.assertEqual(whitePrefix([" y", " y", " y"]), " ") + def test_multi_line(self): + self.assertEqual(white_prefix([" x", " x", " x"]), " ") + self.assertEqual(white_prefix([" y", " y", " y"]), " ") + self.assertEqual(white_prefix([" y", " y", " y"]), " ") - def testBlankLinesAreIgnored(self): - self.assertEqual(whitePrefix([" x", " x", "", " x"]), " ") - self.assertEqual(whitePrefix(["", " x", " x", " x"]), " ") - self.assertEqual(whitePrefix([" x", " x", " x", ""]), " ") - self.assertEqual(whitePrefix([" x", " x", " ", " x"]), " ") + def test_blank_lines_are_ignored(self): + self.assertEqual(white_prefix([" x", " x", "", " x"]), " ") + self.assertEqual(white_prefix(["", " x", " x", " x"]), " ") + self.assertEqual(white_prefix([" x", " x", " x", ""]), " ") + self.assertEqual(white_prefix([" x", " x", " ", " x"]), " ") - def testTabCharacters(self): - self.assertEqual(whitePrefix(["\timport sys", "", "\tprint sys.argv"]), "\t") + def test_tab_characters(self): + self.assertEqual(white_prefix(["\timport sys", "", "\tprint sys.argv"]), "\t") - def testDecreasingLengths(self): - self.assertEqual(whitePrefix([" x", " x", " x"]), " ") - self.assertEqual(whitePrefix([" x", " x", " x"]), " ") + def test_decreasing_lengths(self): + self.assertEqual(white_prefix([" x", " x", " x"]), " ") + self.assertEqual(white_prefix([" x", " x", " x"]), " ") class ReindentBlockTests(TestCase): """Test cases for cogapp.reindentBlock.""" - def testNonTermLine(self): - self.assertEqual(reindentBlock(""), "") - self.assertEqual(reindentBlock("x"), "x") - self.assertEqual(reindentBlock(" x"), "x") - self.assertEqual(reindentBlock(" x"), "x") - self.assertEqual(reindentBlock("\tx"), "x") - self.assertEqual(reindentBlock("x", " "), " x") - self.assertEqual(reindentBlock("x", "\t"), "\tx") - self.assertEqual(reindentBlock(" x", " "), " x") - self.assertEqual(reindentBlock(" x", "\t"), "\tx") - self.assertEqual(reindentBlock(" x", " "), " x") - - def testSingleLine(self): - self.assertEqual(reindentBlock("\n"), "\n") - self.assertEqual(reindentBlock("x\n"), "x\n") - self.assertEqual(reindentBlock(" x\n"), "x\n") - self.assertEqual(reindentBlock(" x\n"), "x\n") - self.assertEqual(reindentBlock("\tx\n"), "x\n") - self.assertEqual(reindentBlock("x\n", " "), " x\n") - self.assertEqual(reindentBlock("x\n", "\t"), "\tx\n") - self.assertEqual(reindentBlock(" x\n", " "), " x\n") - self.assertEqual(reindentBlock(" x\n", "\t"), "\tx\n") - self.assertEqual(reindentBlock(" x\n", " "), " x\n") - - def testRealBlock(self): + def test_non_term_line(self): + self.assertEqual(reindent_block(""), "") + self.assertEqual(reindent_block("x"), "x") + self.assertEqual(reindent_block(" x"), "x") + self.assertEqual(reindent_block(" x"), "x") + self.assertEqual(reindent_block("\tx"), "x") + self.assertEqual(reindent_block("x", " "), " x") + self.assertEqual(reindent_block("x", "\t"), "\tx") + self.assertEqual(reindent_block(" x", " "), " x") + self.assertEqual(reindent_block(" x", "\t"), "\tx") + self.assertEqual(reindent_block(" x", " "), " x") + + def test_single_line(self): + self.assertEqual(reindent_block("\n"), "\n") + self.assertEqual(reindent_block("x\n"), "x\n") + self.assertEqual(reindent_block(" x\n"), "x\n") + self.assertEqual(reindent_block(" x\n"), "x\n") + self.assertEqual(reindent_block("\tx\n"), "x\n") + self.assertEqual(reindent_block("x\n", " "), " x\n") + self.assertEqual(reindent_block("x\n", "\t"), "\tx\n") + self.assertEqual(reindent_block(" x\n", " "), " x\n") + self.assertEqual(reindent_block(" x\n", "\t"), "\tx\n") + self.assertEqual(reindent_block(" x\n", " "), " x\n") + + def test_real_block(self): self.assertEqual( - reindentBlock("\timport sys\n\n\tprint sys.argv\n"), + reindent_block("\timport sys\n\n\tprint sys.argv\n"), "import sys\n\nprint sys.argv\n", ) @@ -73,24 +73,24 @@ def testRealBlock(self): class CommonPrefixTests(TestCase): """Test cases for cogapp.commonPrefix.""" - def testDegenerateCases(self): - self.assertEqual(commonPrefix([]), "") - self.assertEqual(commonPrefix([""]), "") - self.assertEqual(commonPrefix(["", "", "", "", ""]), "") - self.assertEqual(commonPrefix(["cat in the hat"]), "cat in the hat") + def test_degenerate_cases(self): + self.assertEqual(common_prefix([]), "") + self.assertEqual(common_prefix([""]), "") + self.assertEqual(common_prefix(["", "", "", "", ""]), "") + self.assertEqual(common_prefix(["cat in the hat"]), "cat in the hat") - def testNoCommonPrefix(self): - self.assertEqual(commonPrefix(["a", "b"]), "") - self.assertEqual(commonPrefix(["a", "b", "c", "d", "e", "f"]), "") - self.assertEqual(commonPrefix(["a", "a", "a", "a", "a", "x"]), "") + def test_no_common_prefix(self): + self.assertEqual(common_prefix(["a", "b"]), "") + self.assertEqual(common_prefix(["a", "b", "c", "d", "e", "f"]), "") + self.assertEqual(common_prefix(["a", "a", "a", "a", "a", "x"]), "") - def testUsualCases(self): - self.assertEqual(commonPrefix(["ab", "ac"]), "a") - self.assertEqual(commonPrefix(["aab", "aac"]), "aa") - self.assertEqual(commonPrefix(["aab", "aab", "aab", "aac"]), "aa") + def test_usual_cases(self): + self.assertEqual(common_prefix(["ab", "ac"]), "a") + self.assertEqual(common_prefix(["aab", "aac"]), "aa") + self.assertEqual(common_prefix(["aab", "aab", "aab", "aac"]), "aa") - def testBlankLine(self): - self.assertEqual(commonPrefix(["abc", "abx", "", "aby"]), "") + def test_blank_line(self): + self.assertEqual(common_prefix(["abc", "abx", "", "aby"]), "") - def testDecreasingLengths(self): - self.assertEqual(commonPrefix(["abcd", "abc", "ab"]), "ab") + def test_decreasing_lengths(self): + self.assertEqual(common_prefix(["abcd", "abc", "ab"]), "ab") diff --git a/cogapp/utils.py b/cogapp/utils.py index e718001..4a264d9 100644 --- a/cogapp/utils.py +++ b/cogapp/utils.py @@ -22,7 +22,7 @@ def __init__(self): self.stdout = sys.stdout self.stderr = sys.stderr - def setOutput(self, stdout=None, stderr=None): + def set_output(self, stdout=None, stderr=None): """Assign new files for standard out and/or standard error.""" if stdout: self.stdout = stdout diff --git a/cogapp/whiteutils.py b/cogapp/whiteutils.py index ebdceaa..5323268 100644 --- a/cogapp/whiteutils.py +++ b/cogapp/whiteutils.py @@ -3,7 +3,7 @@ import re -def whitePrefix(strings): +def white_prefix(strings): """Find the whitespace prefix common to non-blank lines in `strings`.""" # Remove all blank lines from the list strings = [s for s in strings if s.strip() != ""] @@ -28,7 +28,7 @@ def whitePrefix(strings): return prefix -def reindentBlock(lines, newIndent=""): +def reindent_block(lines, new_indent=""): """Re-indent a block of text. Take a block of text as a string or list of lines. @@ -41,18 +41,18 @@ def reindentBlock(lines, newIndent=""): sep, nothing = b"\n", b"" if isinstance(lines, (bytes, str)): lines = lines.split(sep) - oldIndent = whitePrefix(lines) - outLines = [] + old_indent = white_prefix(lines) + out_lines = [] for line in lines: - if oldIndent: - line = line.replace(oldIndent, nothing, 1) - if line and newIndent: - line = newIndent + line - outLines.append(line) - return sep.join(outLines) + if old_indent: + line = line.replace(old_indent, nothing, 1) + if line and new_indent: + line = new_indent + line + out_lines.append(line) + return sep.join(out_lines) -def commonPrefix(strings): +def common_prefix(strings): """Find the longest string that is a prefix of all the strings.""" if not strings: return "" diff --git a/docs/running.rst b/docs/running.rst index 02b5b37..2008dc3 100644 --- a/docs/running.rst +++ b/docs/running.rst @@ -16,7 +16,7 @@ Cog is a command-line utility which takes arguments in standard form. outf = io.StringIO() print("$ cog -h", file=outf) cog = Cog() - cog.setOutput(stdout=outf, stderr=outf) + cog.set_output(stdout=outf, stderr=outf) cog.main(["cog", "-h"]) print(textwrap.indent(outf.getvalue(), " ")) .. }}}