def testExecute(self, embed_data): execute_py = os.path.normcase(embed_data['testExecute.py_']) self._AssertExecute( Dedent( ''' testExecute Arguments: - 0 - %s - 1 - alpha - 2 - bravo ''' % execute_py ), ['python', execute_py, 'alpha', 'bravo'] ) # Tests string argument (instead of list) and its splitting algorithm. self._AssertExecute( Dedent( r''' testExecute Arguments: - 0 - %s - 1 - alpha - 2 - bravo - 3 - charlie is number three - 4 - delta '''.replace('\\n', os.linesep) % execute_py ), 'python %(testExecute.py_)s alpha bravo "charlie is number three" delta' % embed_data, )
def test_embed_data_AssertEqualFiles(self, embed_data): CreateFile(embed_data.GetDataFilename('equal.txt'), 'This is alpha.txt') embed_data.AssertEqualFiles('alpha.txt', 'equal.txt') CreateFile(embed_data.GetDataFilename('different.txt'), 'This is different.txt') with pytest.raises(AssertionError) as e: embed_data.AssertEqualFiles('alpha.txt', 'different.txt') assert str(e.value) == Dedent(''' *** FILENAME: data_fixtures__test_embed_data_AssertEqualFiles/alpha.txt ***\w ---\w *************** *** 1 **** ! This is alpha.txt --- 1 ---- ! This is different.txt '''.replace('\w', ' ')) with pytest.raises(MultipleFilesNotFound) as e: embed_data.AssertEqualFiles('alpha.txt', 'missing.txt') assert ( str(e.value) == 'Files not found: ' 'missing.txt,data_fixtures__test_embed_data_AssertEqualFiles/missing.txt' )
def testDedent4(self): string = Dedent(''' oneline tabbed detabbed ''') assert string == 'oneline\n tabbed\ndetabbed'
def testRepeatingTags(self): ''' <root> <elements> <name>Alpha</name> <name>Bravo</name> <name>Charlie</name> </elements> <components> <component> <name>Alpha</name> </component> <component> <name>Bravo</name> </component> <component> <name>Charlie</name> </component> </components> </root> ''' factory = XmlFactory('root') factory['elements/name'] = 'Alpha' factory['elements/name+'] = 'Bravo' factory['elements/name+'] = 'Charlie' factory['components/component+/name'] = 'Alpha' factory['components/component+/name'] = 'Bravo' factory['components/component+/name'] = 'Charlie' assert ( factory.GetContent() == Dedent(self.testRepeatingTags.__doc__) )
def testExecuteInput(self, embed_data): self._AssertExecute( Dedent( ''' testExecuteInput: Hello, planet earth! ''' ), ['python', embed_data.GetDataFilename('testExecuteInput.py_')], input='planet earth', )
def testDedent8(self): ''' Test not the first line in the right indent. ''' string = Dedent(''' alpha bravo charlie ''') assert string == ' alpha\n bravo\ncharlie'
def testDedent10(self): ''' Checking how Dedent handles empty lines at the end of string without parameters. ''' string = Dedent(''' alpha ''') assert string == 'alpha' string = Dedent(''' alpha ''') assert string == 'alpha\n' string = Dedent(''' alpha ''') assert string == 'alpha\n\n'
def testDedent9(self): ''' Coverage 100% TODO: BEN-21: Strange behavior on Dedent when mixing tabs and spaces. ''' string = Dedent(''' alpha \tbravo ''') assert string == ' alpha\n \tbravo'
def testDedent7(self): ''' Test a string that has an 'empty line' with 4 spaces above indent level ''' # Using a trick to avoid auto-format to remove the empty spaces. string = Dedent(''' line %s other_line ''' % ' ') assert string == 'line\n \nother_line'
def testExecuteAndEnviron(self, embed_data): self._AssertExecute( Dedent( ''' testExecuteAndEnviron: ALPHA: alpha testExecuteAndEnviron: BRAVO: bravo ''' ), ['python', embed_data.GetDataFilename('testExecuteAndEnviron.py_')], environ={ 'ALPHA' : 'alpha', 'BRAVO' : 'bravo', }, )
def testHudsonJob(self): ''' <project> <actions/> <description/> <logRotator> <daysToKeep>7</daysToKeep> <numToKeep>7</numToKeep> </logRotator> <keepDependencies>false</keepDependencies> <properties/> <scm class="hudson.scm.SubversionSCM"> <useUpdate>true</useUpdate> <excludedRegions/> <excludedUsers/> <excludedRevprop/> </scm> <assignedNode>KATARN</assignedNode> <canRoam>false</canRoam> <disabled>false</disabled> <blockBuildWhenUpstreamBuilding>true</blockBuildWhenUpstreamBuilding> <concurrentBuild>false</concurrentBuild> <buildWrappers/> <customWorkspace>WORKSPACE</customWorkspace> </project> ''' factory = XmlFactory('project') factory['actions'] factory['description'] factory['logRotator/daysToKeep'] = '7' factory['logRotator/numToKeep'] = '7' factory['keepDependencies'] = 'false' factory['properties'] factory['scm@class'] = 'hudson.scm.SubversionSCM' factory['scm/useUpdate'] = 'true' factory['scm/excludedRegions'] factory['scm/excludedUsers'] factory['scm/excludedRevprop'] factory['assignedNode'] = 'KATARN' factory['canRoam'] = 'false' factory['disabled'] = 'false' factory['blockBuildWhenUpstreamBuilding'] = 'true' factory['concurrentBuild'] = 'false' factory['buildWrappers'] factory['customWorkspace'] = 'WORKSPACE' assert ( factory.GetContent() == Dedent(self.testHudsonJob.__doc__) )
def DoTest(slash): python_filename = os.path.normcase(embed_data.GetDataFilename('testExecute.py_', absolute=True)) cmd_filename = embed_data.GetDataDirectory() + slash + 'testExecute.bat' self._AssertExecute( Dedent( r''' testExecute Arguments: - 0 - %s - 1 - alpha - 2 - bravo '''.replace('\\n', os.linesep) % python_filename ), '%s alpha bravo' % cmd_filename, )
def testTriggerClass(self): ''' <root> <triggers class="vector"/> </root> ''' # Simulating the use for HudsonJobGenerator._CreateTriggers factory = XmlFactory('root') triggers = factory['triggers'] triggers['@class'] = 'vector' assert ( factory.GetContent() == Dedent(self.testTriggerClass.__doc__) )
def testSimplest(self): ''' <?xml version="1.0" ?> <user> <name>Alpha</name> <login>Bravo</login> </user> ''' factory = XmlFactory('user') factory['name'] = 'Alpha' factory['login'] = '******' assert ( factory.GetContent(xml_header=True) == Dedent(self.testSimplest.__doc__) )
def testPrettyXMLToStream(self, embed_data): ''' <root> <alpha enabled="true"> <bravo> <charlie/> </bravo> <bravo.one/> <delta>XXX</delta> </alpha> </root> ''' iss = file(embed_data['input.xml'], 'r') oss = StringIO() WritePrettyXML(iss, oss) assert oss.getvalue() == Dedent(self.testPrettyXMLToStream.__doc__)
def testAttributes(self): ''' <root> <alpha one="1" two="2">Alpha</alpha> <bravo> <charlie three="3"/> </bravo> </root> ''' factory = XmlFactory('root') factory['alpha'] = 'Alpha' factory['alpha@one'] = '1' factory['alpha@two'] = '2' factory['bravo/charlie@three'] = '3' assert ( factory.GetContent() == Dedent(self.testAttributes.__doc__) )
def testSimple(self): ''' <user> <name>Alpha</name> <login>Bravo</login> <location> <city>Charlie</city> </location> </user> ''' factory = XmlFactory('user') factory['name'] = 'Alpha' factory['login'] = '******' factory['location/city'] = 'Charlie' assert ( factory.GetContent() == Dedent(self.testSimple.__doc__) )
def testUnknownOptionArgs(self): app = App('test', color=False, buffered_console=True) def Command(console_): console_.Print('hello') app.Add(Command) app.TestScript( Dedent(''' >test command --foo --bar ERROR: Unrecognized arguments: --foo --bar (no description) Usage: command\s\s Parameters: Options: '''.replace('\s', ' ')))
def testColor(self): app = App('test', color=True, buffered_console=True) assert app.console.color == True def Case(): ''' This is Case. ''' app.Add(Case) self._TestMain( app, '', Dedent(''' Usage: test <subcommand> [options] Commands: %(teal)scase%(reset)s This is Case. ''' % Console.COLOR_CODES))
def testFixtureDecorator(self): app = App('test', color=False, buffered_console=True) @app.Fixture def Alpha(): return 'alpha' @app.Fixture() def Bravo(): return 'bravo' def Command(console_, alpha_, bravo_): console_.Print('The names are: %(alpha_)s and %(bravo_)s.' % locals()) app.Add(Command) self._TestMain( app, 'command', Dedent(''' The names are: alpha and bravo. '''))
def testDedent6(self): string = Dedent(''' oneline ''', ignore_last_linebreak=False) assert string == 'oneline\n'
def testDedent5(self): string = Dedent(''' oneline ''', ignore_first_linebreak=False) assert string == '\noneline'
def testHelp(self): def TestCmd(console_, first, second, option=1, option_no=False): ''' This is a test. :param first: This is the first parameter. :param second: This is the second and last parameter. :param option: This must be a number. :param option_no: If set, says nop. ''' app = App('test', color=False, buffered_console=True) app.Add(TestCmd) self._TestMain( app, '', Dedent(''' Usage: test <subcommand> [options] Commands: test-cmd This is a test. ''')) self._TestMain( app, '--help', Dedent(''' Usage: test <subcommand> [options] Commands: test-cmd This is a test. ''')) self._TestMain( app, 'test-cmd --help', Dedent(''' This is a test. Usage: test-cmd <first> <second> [--option=1],[--option-no] Parameters: first This is the first parameter. second This is the second and last parameter. Options: --option This must be a number. [default: 1] --option-no If set, says nop. ''')) self._TestMain( app, 'test-cmd', Dedent(''' ERROR: Too few arguments. This is a test. Usage: test-cmd <first> <second> [--option=1],[--option-no] Parameters: first This is the first parameter. second This is the second and last parameter. Options: --option This must be a number. [default: 1] --option-no If set, says nop. '''), app.RETCODE_ERROR)
def testDedent2(self): string = Dedent(''' oneline twoline ''') assert string == 'oneline\ntwoline'
def testPageWidthParameter(self): oss = TextOutput() oss.c_page_width = 80 oss.RegisterKeyword('yes', 'This will be shown') oss.RegisterKeyword('no', 'This will not be shown') oss.SetKeyword('yes', True) stream = StringIO() oss.SetOutputStream(stream) try: raise RuntimeError('This is an exception') except Exception: oss.EXCEPTION() assert stream.getvalue() == Dedent(''' ******************************************************************************** RuntimeError: This is an exception -------------------------------------------------------------------------------- %s raise RuntimeError('This is an exception') ******************************************************************************** ''') % '\n'.join(textwrap.wrap(__file__ + ':52:', 80)) stream = StringIO() oss.SetOutputStream(stream) oss.P('alpha bravo charlie delta echo foxtrot') oss.P('No show', verbose=4) oss.P('No show', keywords=('no', )) assert stream.getvalue() == Dedent(''' alpha bravo charlie delta echo foxtrot ''') stream = StringIO() oss.SetOutputStream(stream) oss.P('alpha bravo charlie delta echo foxtrot', page_width=12) assert stream.getvalue() == Dedent(''' alpha bravo charlie delta echo foxtrot ''') stream = StringIO() oss.SetOutputStream(stream) oss.I('alpha') oss.I('bravo') oss.I('charlie') oss.I('No show', verbose=4) oss.I('No show', keywords=('no', )) assert stream.getvalue() == Dedent(''' - alpha - bravo - charlie ''') stream = StringIO() oss.SetOutputStream(stream) oss.TABLE([7, 8, 9], ['alpha', 'bravo', 'charlie'], [[1, 2, 3], [4, 5, 6]]) assert 'x\n' + stream.getvalue() == Dedent(''' x alpha bravo charlie 1 2 3 4 5 6 ''') stream = StringIO() oss.SetOutputStream(stream) oss.HEADER("This is header") oss.HEADER('No show', verbose=4) oss.HEADER('No show', keywords=('no', )) assert stream.getvalue() == Dedent(''' -------------------------------------------------------------------------------- This is header -------------------------------------------------------------------------------- ''') stream = StringIO() oss.SetOutputStream(stream) oss.ERROR('Oops!') oss.ERROR('Oops!', verbose=4) oss.ERROR('Oops!', keywords=('no', )) assert stream.getvalue() == Dedent(''' ******************************************************************************** ERROR Oops! ******************************************************************************** ''') stream = StringIO() oss.SetOutputStream(stream) oss.PROCESSING('...', 'Doing') oss.PROCESSING('Done') oss.PROCESSING('...', 'Multi\nline\ndoing') oss.PROCESSING('Done') oss.flat_output = True oss.PROCESSING('...', 'Doing') oss.PROCESSING('Done') oss.PROCESSING('No show', verbose=4) oss.PROCESSING('No show', keywords=('no', )) assert stream.getvalue() == Dedent(''' ...Doing\\rDone ...Multi line doing \\rDone Doing...Done ''') stream = StringIO() oss.SetOutputStream(stream) oss.DT('caption', 'value') oss.DT('No show', verbose=4) oss.DT('No show', keywords=('no', )) assert (stream.getvalue() == 'caption value:\n') stream = StringIO() oss.SetOutputStream(stream) oss.DD('caption', 'value') oss.DD('No show', 'No show', verbose=4) oss.DD('No show', 'No show', keywords=('no', )) assert (stream.getvalue() == 'caption:\n value\n') stream = StringIO() oss.SetOutputStream(stream) oss.LINE('-') oss.LINE('X', verbose=4) oss.LINE('X', keywords=('no', )) assert (stream.getvalue() == '-' * 80 + '\n') stream = StringIO() oss.SetOutputStream(stream) oss.Indent() oss.Indent() oss.P('alpha') oss.Dedent() oss.P('bravo') oss.ResetIndentation() oss.P('charlie') assert (stream.getvalue() == ' alpha\n bravo\ncharlie\n')
def TestScript(self, script): ''' Executes a test script, containing command calls (prefixed by ">") and expected results. Example: app = App('ii') app = TestScript(Dedent( """ > ii list - alpha - bravo """ ) :param unicode string: A multi-line string with command calls and expected results. Consider the following syntax rules: - Lines starting with '>' are command execution (command); - Lines starting with "###" are ignored; - Everything else is expected output of the previous "command"; - Use [retcode=X] syntax to check for non-zero return from a command. ''' def Execute(cmd, expected_output, expected_retcode): obtained_retcode, obtained = self.TestCall(cmd) obtained_string = obtained.rstrip('\n') + '\n' expected_string = expected_output.rstrip('\n') + '\n' assert obtained_string == expected_string assert expected_retcode == obtained_retcode, Dedent( ''' >>> %(cmd)s Command finished with return code "%(obtained_retcode)s", was expecting "%(expected_retcode)s" Use ">>>my_command [retcode=X]" syntax to define the expected return code. ''' % locals() ) def GetExpectedReturnCode(input_line): ''' Find the return code we expect from this command. Expected return code must be in format '[retcode=999]' If not specified, we assume that the expected retcode is 0 e.g. >>>DoSomethingThatFails [retcode=1] >>>DoSomethingOk [retcode=0] :param unicode input_line: ''' import re pattern = '\[retcode=(\d+)\]' match = re.search(pattern, input_line) if match: expected_retcode = int(match.groups()[0]) else: expected_retcode = 0 return re.sub(pattern, '', input_line), expected_retcode cmd = None expected_output = '' expected_retcode = 0 script = Dedent(script) for i_line in script.splitlines(): if i_line.startswith('###'): continue elif i_line.startswith('>'): if cmd is not None: Execute(cmd, expected_output, expected_retcode) expected_output = '' cmd = i_line[1:] cmd, expected_retcode = GetExpectedReturnCode(cmd) else: expected_output += i_line + '\n' if cmd is not None: Execute(cmd, expected_output, expected_retcode)
def testDedent1(self): string = Dedent(''' oneline ''') assert string == 'oneline'
def testApp(self): ''' Tests App usage and features. ''' def Case1(console_): ''' A "hello" message from case 1 ''' console_.Print('Hello from case 1') def Case2(console_): ''' A "hello" message from case 2 Additional help for this function is available. ''' console_.Print('Hello from case 2') def Case3(console_): console_.Print('Hello from case 3') def Case4(console_): console_.Print('Hello from case 4 (AKA: four)') app = App('test', color=False, buffered_console=True) app.Add(Case1, alias='cs') app.Add(Case2) case3_cmd = app.Add(Case3, alias=('c3', 'cs3')) app.Add(Case4, name='four') # Test duplicate name with pytest.raises(ValueError): app.Add(case3_cmd.func, alias='cs') # Test commands listing assert app.ListAllCommandNames() == [ 'case1', 'cs', 'case2', 'case3', 'c3', 'cs3', 'four' ] # Tests all commands output self._TestMain(app, 'case1', 'Hello from case 1\n') self._TestMain(app, 'cs', 'Hello from case 1\n') self._TestMain(app, 'case2', 'Hello from case 2\n') self._TestMain(app, 'case3', 'Hello from case 3\n') self._TestMain(app, 'c3', 'Hello from case 3\n') self._TestMain(app, 'cs3', 'Hello from case 3\n') # Tests output when an invalid command is requested self._TestMain( app, 'INVALID', Dedent(''' ERROR: Unknown command 'INVALID' Usage: test <subcommand> [options] Commands: case1, cs A "hello" message from case 1 case2 A "hello" message from case 2 case3, c3, cs3 (no description) four (no description) '''), app.RETCODE_ERROR)