Browse Source

Removed old tests. Cleaned up new tests

pull/90/merge
chriskiehl 9 years ago
parent
commit
5cf42a17b8
9 changed files with 384 additions and 586 deletions
  1. 74
      gooey/tests/action_sorter_unittest.py
  2. 46
      gooey/tests/advanced_config_unittest.py
  3. 62
      gooey/tests/code_prep_unittest.py
  4. 26
      gooey/tests/component_register_unittest.py
  5. 159
      gooey/tests/components_unittest.py
  6. 73
      gooey/tests/i18n_unittest.py
  7. 19
      gooey/tests/modules_unittest.py
  8. 36
      gooey/tests/option_reader_unittest.py
  9. 475
      gooey/tests/source_parser_unittest.py

74
gooey/tests/action_sorter_unittest.py

@ -1,74 +0,0 @@
"""
Created on Jan 16, 2014
@author: Chris
"""
import unittest
from argparse import _HelpAction
from action_sorter import ActionSorter
from gooey.gui import argparse_test_data
class TestActionSorter(unittest.TestCase):
def setUp(self):
self._actions = argparse_test_data.parser._actions
self.sorted_actions = ActionSorter(self._actions)
# pain in the A...
self.expected_positionals = [
"_StoreAction(option_strings=[], dest='filename', nargs=None, const=None, default=None, type=None, choices=None, help='Name of the file you want to read', metavar=None)",
"""_StoreAction(option_strings=[], dest='outfile', nargs=None, const=None, default=None, type=None, choices=None, help="Name of the file where you'll save the output", metavar=None)"""
]
self.expected_choices = [
"""_StoreAction(option_strings=['-T', '--tester'], dest='tester', nargs=None, const=None, default=None, type=None, choices=['yes', 'no'], help="Yo, what's up man? I'm a help message!", metavar=None)"""
]
self.expected_optionals = [
"""_StoreAction(option_strings=['-m', '--moutfile'], dest='moutfile', nargs=None, const=None, default=None, type=None, choices=None, help='Redirects output to the file specified by you, the awesome user', metavar=None)""",
"""_StoreAction(option_strings=['-v', '--verbose'], dest='verbose', nargs=None, const=None, default=None, type=None, choices=None, help='Toggles verbosity off', metavar=None)""",
"""_StoreAction(option_strings=['-s', '--schimzammy'], dest='schimzammy', nargs=None, const=None, default=None, type=None, choices=None, help='Add in an optional shimzammy parameter', metavar=None)"""
]
self.expected_counters = [
"""_CountAction(option_strings=['-e', '--repeat'], dest='repeat', nargs=0, const=None, default=None, type=None, choices=None, help='Set the number of times to repeat', metavar=None)"""
]
self.expected_flags = [
"""_StoreConstAction(option_strings=['-c', '--constoption'], dest='constoption', nargs=0, const='myconstant', default=None, type=None, choices=None, help='Make sure the const action is correctly sorted', metavar=None)""",
"""_StoreTrueAction(option_strings=['-t', '--truify'], dest='truify', nargs=0, const=True, default=False, type=None, choices=None, help='Ensure the store_true actions are sorted', metavar=None)""",
"""_StoreFalseAction(option_strings=['-f', '--falsificle'], dest='falsificle', nargs=0, const=False, default=True, type=None, choices=None, help='Ensure the store_false actions are sorted', metavar=None)"""
]
def test_positionals_returns_only_positional_actions(self):
positionals = self.sorted_actions._positionals
self.assertEqual(len(positionals), 2)
self.assert_for_all_actions_in_list(positionals, self.expected_positionals)
def test_help_action_not_in_optionals(self):
_isinstance = lambda x: isinstance(x, _HelpAction)
self.assertFalse(any(map(_isinstance, self.sorted_actions._optionals)))
def test_choices_only_returns_choices(self):
self.assert_for_all_actions_in_list(self.sorted_actions._choices,
self.expected_choices)
def test_optionals_only_returns_optionals(self):
self.assert_for_all_actions_in_list(self.sorted_actions._optionals,
self.expected_optionals)
def test_counter_sort_only_returns_counters(self):
self.assert_for_all_actions_in_list(self.sorted_actions._counters,
self.expected_counters)
def test_flag_sort_returns_only_flags(self):
self.assert_for_all_actions_in_list(self.sorted_actions._flags,
self.expected_flags)
def assert_for_all_actions_in_list(self, actions, expected_actions):
for index, action in enumerate(actions):
self.assertEqual(str(action), expected_actions[index])
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()

46
gooey/tests/advanced_config_unittest.py

@ -1,46 +0,0 @@
'''
Created on Jan 7, 2014
@author: Chris
'''
import os
import sys
import unittest
import wx
from gooey.gui.client_app import ClientApp
from gooey.gui import argparse_test_data
from gooey.gui.windows import advanced_config
class TestAdvancedConfigPanel(unittest.TestCase):
def setUp(self):
self.parser = argparse_test_data.parser
def buildWindow(self):
app = wx.PySimpleApp()
module_name = os.path.split(sys.argv[0])[-1]
frame = wx.Frame(None, -1, module_name, size=(640, 480))
panel = advanced_config.AdvancedConfigPanel(frame, ClientApp(self.parser))
frame.Show()
app.MainLoop()
def testAdvancedConfigPanel(self):
self.buildWindow()
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()

62
gooey/tests/code_prep_unittest.py

@ -1,57 +1,55 @@
__author__ = 'Chris'
import unittest
import code_prep
from gooey.python_bindings import code_prep
class TestCodePrep(unittest.TestCase):
def test_split_line(self):
line = "parser = ArgumentParser(description='Example Argparse Program')"
self.assertEqual("parser", code_prep.split_line(line)[0])
self.assertEqual("ArgumentParser(description='Example Argparse Program')", code_prep.split_line(line)[1])
def test_split_line():
line = "parser = ArgumentParser(description='Example Argparse Program')"
assert "parser" == code_prep.split_line(line)[0]
assert "ArgumentParser(description='Example Argparse Program')" == code_prep.split_line(line)[1]
def test_update_parser_varname_assigns_new_name_to_parser_var(self):
line = ["parser = ArgumentParser(description='Example Argparse Program')"]
self.assertEqual(
"jarser = ArgumentParser(description='Example Argparse Program')",
code_prep.update_parser_varname('jarser', line)[0]
)
def test_update_parser_varname_assigns_new_name_to_parser_var__multiline(self):
lines = '''
def test_update_parser_varname_assigns_new_name_to_parser_var():
line = ["parser = ArgumentParser(description='Example Argparse Program')"]
expected = "jarser = ArgumentParser(description='Example Argparse Program')"
result = code_prep.update_parser_varname('jarser', line)[0]
assert result == expected
def test_update_parser_varname_assigns_new_name_to_parser_var__multiline():
lines = '''
import argparse
from argparse import ArgumentParser
parser = ArgumentParser(description='Example Argparse Program')
parser.parse_args()
'''.split('\n')
'''.split('\n')
line = "jarser = ArgumentParser(description='Example Argparse Program')"
result = code_prep.update_parser_varname('jarser', lines)[2]
assert line == result
self.assertEqual(
"jarser = ArgumentParser(description='Example Argparse Program')",
code_prep.update_parser_varname('jarser', lines)[2]
)
def test_take_imports_drops_all_non_imports_statements(self):
lines = '''
def test_take_imports_drops_all_non_imports_statements():
lines = '''
import argparse
from argparse import ArgumentParser
parser = ArgumentParser(description='Example Argparse Program')
parser.parse_args()
'''.split('\n')[1:]
'''.split('\n')[1:]
self.assertEqual(2, len(list(code_prep.take_imports(lines))))
self.assertEqual('import argparse', list(code_prep.take_imports(lines))[0])
assert 2 == len(list(code_prep.take_imports(lines)))
assert 'import argparse' == list(code_prep.take_imports(lines))[0]
def test_drop_imports_excludes_all_imports_statements(self):
lines = '''
def test_drop_imports_excludes_all_imports_statements():
lines = '''
import argparse
from argparse import ArgumentParser
parser = ArgumentParser(description='Example Argparse Program')
parser.parse_args()
'''.split('\n')[1:]
'''.split('\n')[1:]
assert 2 == len(list(code_prep.take_imports(lines)))
assert 'parser.parse_args()' == list(code_prep.drop_imports(lines))[1]
self.assertEqual(2, len(list(code_prep.take_imports(lines))))
self.assertEqual('parser.parse_args()', list(code_prep.drop_imports(lines))[1])
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()

26
gooey/tests/component_register_unittest.py

@ -1,26 +0,0 @@
'''
Created on Jan 26, 2014
@author: Chris
'''
import unittest
from gooey.gui.component_register import ComponentRegister
class Test(unittest.TestCase):
def setUp(self):
class FakeClassWithoutImplementation(ComponentRegister):
def __init__(self):
pass
self.test_class = FakeClassWithoutImplementation()
def testHostClassReceivesMixinFunctions(self):
pass
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()

159
gooey/tests/components_unittest.py

@ -1,84 +1,75 @@
'''
Created on Jan 4, 2014
@author: Chris
'''
import os
import sys
import unittest
from argparse import ArgumentParser
import wx
from gooey.gui import components
class ComponentsTest(unittest.TestCase):
def setUp(self):
parser = ArgumentParser(description='Example Argparse Program')
parser.add_argument("filename", help="Name of the file you want to read")
parser.add_argument('-T', '--tester', choices=['yes', 'no'])
parser.add_argument('-o', '--outfile', help='Redirects output to the specified file')
parser.add_argument('-v', '--verbose', help='Toggles verbosity off')
parser.add_argument('-e', '--repeat', action='count')
action = parser._actions
self.actions = {
'help': action[0],
'Positional': action[1],
'Choice': action[2],
'Optional': action[3],
'Flag': action[4],
'Counter': action[5]
}
def BuildWindow(self, component, _type):
app = wx.PySimpleApp()
module_name = os.path.split(sys.argv[0])[-1]
frame = wx.Frame(None, -1, _type)
panel = wx.Panel(frame, -1, size=(320, 240))
component_sizer = component.Build(panel)
panel.SetSizer(component_sizer)
frame.Show(True)
app.MainLoop()
def testPositionalWidgetBuild(self):
self.SetupWidgetAndBuildWindow('Positional')
def testChoiceWidgetBuild(self):
self.SetupWidgetAndBuildWindow('Choice')
def testOptionalWidgetBuild(self):
self.SetupWidgetAndBuildWindow('Optional')
def testFlagWidgetBuild(self):
self.SetupWidgetAndBuildWindow('Flag')
def testCounterWidgetBuild(self):
self.SetupWidgetAndBuildWindow('Counter')
def SetupWidgetAndBuildWindow(self, _type):
component = getattr(components, _type)(self.actions[_type])
self.BuildWindow(component, _type)
if __name__ == "__main__":
# import sys;sys.argv = ['', 'Test.testName']
unittest.main()
# '''
# Created on Jan 4, 2014
#
# @author: Chris
#
#
#
#
# '''
#
# import os
# import sys
# import unittest
# from argparse import ArgumentParser
#
# import wx
#
#
# class ComponentsTest(unittest.TestCase):
# def setUp(self):
# parser = ArgumentParser(description='Example Argparse Program')
# parser.add_argument("filename", help="Name of the file you want to read")
# parser.add_argument('-T', '--tester', choices=['yes', 'no'])
# parser.add_argument('-o', '--outfile', help='Redirects output to the specified file')
# parser.add_argument('-v', '--verbose', help='Toggles verbosity off')
# parser.add_argument('-e', '--repeat', action='count')
# action = parser._actions
# self.actions = {
# 'help': action[0],
# 'Positional': action[1],
# 'Choice': action[2],
# 'Optional': action[3],
# 'Flag': action[4],
# 'Counter': action[5]
# }
#
#
# def BuildWindow(self, component, _type):
# app = wx.PySimpleApp()
# module_name = os.path.split(sys.argv[0])[-1]
# frame = wx.Frame(None, -1, _type)
#
# panel = wx.Panel(frame, -1, size=(320, 240))
# component_sizer = component.Build(panel)
# panel.SetSizer(component_sizer)
#
# frame.Show(True)
#
# app.MainLoop()
#
#
# def testPositionalWidgetBuild(self):
# self.SetupWidgetAndBuildWindow('Positional')
#
# def testChoiceWidgetBuild(self):
# self.SetupWidgetAndBuildWindow('Choice')
#
# def testOptionalWidgetBuild(self):
# self.SetupWidgetAndBuildWindow('Optional')
#
# def testFlagWidgetBuild(self):
# self.SetupWidgetAndBuildWindow('Flag')
#
# def testCounterWidgetBuild(self):
# self.SetupWidgetAndBuildWindow('Counter')
#
# def SetupWidgetAndBuildWindow(self, _type):
# component = getattr(components, _type)(self.actions[_type])
# self.BuildWindow(component, _type)
#
#
# if __name__ == "__main__":
# # import sys;sys.argv = ['', 'Test.testName']
# unittest.main()
#

73
gooey/tests/i18n_unittest.py

@ -1,38 +1,35 @@
'''
Created on Jan 25, 2014
@author: Chris
'''
import unittest
import i18n
# from i18n import I18N
#
class Test(unittest.TestCase):
def test_i18n_loads_module_by_name(self):
self.assertTrue(i18n._DICTIONARY is None)
i18n.load('english')
self.assertTrue(i18n._DICTIONARY is not None)
self.assertEqual('Cancel', i18n.translate('cancel'))
i18n.load('french')
self.assertEqual('Annuler', i18n.translate('cancel'))
def test_i18n_throws_exception_on_no_lang_file_found(self):
self.assertRaises(IOError, i18n.load, 'chionenglish')
if __name__ == "__main__":
pass
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
# '''
# Created on Jan 25, 2014
#
# @author: Chris
# '''
#
# import unittest
#
# import i18n
#
#
# class Test(unittest.TestCase):
#
# def test_i18n_loads_module_by_name(self):
# self.assertTrue(i18n._DICTIONARY is None)
#
# i18n.load('english')
# self.assertTrue(i18n._DICTIONARY is not None)
# self.assertEqual('Cancel', i18n.translate('cancel'))
#
# i18n.load('french')
# self.assertEqual('Annuler', i18n.translate('cancel'))
#
#
# def test_i18n_throws_exception_on_no_lang_file_found(self):
# self.assertRaises(IOError, i18n.load, 'chionenglish')
#
#
#
#
#
# if __name__ == "__main__":
# pass
# #import sys;sys.argv = ['', 'Test.testName']
# unittest.main()

19
gooey/tests/modules_unittest.py

@ -1,23 +1,16 @@
from gooey.python_bindings import modules
__author__ = 'Chris'
import unittest
class TestModules(unittest.TestCase):
def test_load_creates_and_imports_module_from_string_source(self):
module_source = '''
module_source = \
'''
some_var = 1234
def fooey():
return 10
'''
'''
def test_load_creates_and_imports_module_from_string_source():
module = modules.load(module_source)
self.assertEqual(10, module.fooey())
assert 10 == module.fooey()
def test_generate_pyfilename_does_not_begin_with_digit(self):
self.assertTrue(not modules.generate_pyfilename()[0].isdigit())

36
gooey/tests/option_reader_unittest.py

@ -1,36 +0,0 @@
'''
Created on Jan 26, 2014
@author: Chris
'''
import unittest
from gooey.gui.option_reader import OptionReader
class FakeClassWithoutImplementation(OptionReader):
def __init__(self):
pass
class FakeClassWithImplementation(OptionReader):
def __init__(self):
pass
def GetOptions(self):
pass
class Test(unittest.TestCase):
def test_mixin_classes_throws_typeerror_without_implementation(self):
with self.assertRaises(TypeError):
fake_class = FakeClassWithoutImplementation()
def test_mixin_classes_passes_with_implementation(self):
fc = FakeClassWithImplementation()
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()

475
gooey/tests/source_parser_unittest.py

@ -1,237 +1,238 @@
'''
Created on Feb 2, 2014
@author: Chris
TODO:
- test no argparse module
- test argparse in main
- test argparse in try/catch
-
'''
import os
import ast
import unittest
from gooey.python_bindings import source_parser
basic_pyfile = '''
import os
def say_jello():
print "Jello!"
def main():
print "hello!"
parser = ArgumentParser(description='Example Argparse Program', formatter_class=RawDescriptionHelpFormatter)
parser.add_argument("filename", help="filename")
parser.add_argument("-r", "--recursive", dest="recurse", action="store_true",
help="recurse into subfolders [default: %(default)s]")
parser.add_argument("-v", "--verbose", dest="verbose", action="count",
help="set verbosity level [default: %(default)s]")
parser.add_argument("-i", "--include", action="append",
help="only include paths matching this regex pattern. Note: exclude is given preference over include. [default: %(default)s]",
metavar="RE")
parser.add_argument("-m", "--mycoolargument", help="mycoolargument")
parser.add_argument("-e", "--exclude", dest="exclude",
help="exclude paths matching this regex pattern. [default: %(default)s]", metavar="RE")
parser.add_argument('-V', '--version', action='version')
parser.add_argument('-T', '--tester', choices=['yes', 'no'])
parser.add_argument(dest="paths", help="paths to folder(s) with source file(s) [default: %(default)s]",
metavar="path", nargs='+')
if __name__ == '__main__':
main()
'''
class TestSourceParser(unittest.TestCase):
PATH = os.path.join(os.path.dirname(__file__), 'examples')
def module_path(self, name):
return os.path.join(self.PATH, name)
def setUp(self):
self._mockapp = self.module_path('examples.py')
self._module_with_noargparse = self.module_path('module_with_no_argparse.py')
self._module_with_arparse_in_try = self.module_path('TODO.py')
self._module_with_argparse_in_main = self.module_path('example_argparse_souce_in_main.py')
def test_should_throw_parser_exception_if_no_argparse_found_in_module(self):
with self.assertRaises(source_parser.ParserError):
source_parser.parse_source_file(self._module_with_noargparse)
def test_find_main(self):
example_source = '''
def main(): pass
'''
nodes = ast.parse(example_source)
main_node = source_parser.find_main(nodes)
self.assertEqual('main', main_node.name)
def test_find_main_throws_exception_if_not_found(self):
example_source = '''
def some_cool_function_that_is_not_main(): pass
'''
with self.assertRaises(source_parser.ParserError):
nodes = ast.parse(example_source)
main_node = source_parser.find_main(nodes)
self.assertEqual('main', main_node.name)
def test_find_try_blocks_finds_all_tryblock_styles(self):
example_source = '''
try: a = 1
except: pass
try: pass
finally: pass
try: pass
except: pass
else: pass
'''
nodes = ast.parse(example_source)
try_blocks = source_parser.find_try_blocks(nodes)
self.assertEqual(3, len(try_blocks))
def test_find_try_blocks_returns_empty_if_no_blocks_present(self):
example_source = 'def main(): pass'
nodes = ast.parse(example_source)
result = source_parser.find_try_blocks(nodes)
self.assertEqual(list(), result)
def test_find_argparse_located_object_when_imported_by_direct_name(self):
example_source = '''
def main():
parser = ArgumentParser(description='Example Argparse Program', formatter_class=RawDescriptionHelpFormatter)
'''
nodes = ast.parse(example_source)
main_node = source_parser.find_main(nodes)
self.assertEqual('main', main_node.name)
containing_block = source_parser.find_block_containing_argparse([main_node])
self.assertTrue(containing_block is not None)
def test_find_argparse_located_object_when_access_through_module_dot_notation(self):
example_source = '''
def main():
parser = argparse.ArgumentParser(description='Example Argparse Program', formatter_class=RawDescriptionHelpFormatter)
'''
nodes = ast.parse(example_source)
main_node = source_parser.find_main(nodes)
self.assertEqual('main', main_node.name)
containing_block = source_parser.find_block_containing_argparse([main_node])
self.assertTrue(containing_block is not None)
def test_find_argparse_locates_assignment_stmnt_in_main(self):
nodes = ast.parse(source_parser._openfile(self._module_with_argparse_in_main))
main_node = source_parser.find_main(nodes)
self.assertEqual('main', main_node.name)
containing_block = source_parser.find_block_containing_argparse([main_node])
self.assertTrue(containing_block is not None)
self.assertEqual('main', containing_block.name)
def test_find_argparse_locates_assignment_stmnt_in_try_block(self):
nodes = ast.parse(source_parser._openfile(self._module_with_arparse_in_try))
main_node = source_parser.find_main(nodes)
self.assertEqual('main', main_node.name)
try_nodes = source_parser.find_try_blocks(main_node)
self.assertTrue(len(try_nodes) > 0)
containing_block = source_parser.find_block_containing_argparse([main_node] + try_nodes)
self.assertEqual(ast.TryExcept, type(containing_block))
def test_find_argparse_throws_exception_if_not_found(self):
with self.assertRaises(source_parser.ParserError):
nodes = ast.parse(source_parser._openfile(self._module_with_noargparse))
main_node = source_parser.find_main(nodes)
self.assertEqual('main', main_node.name)
try_nodes = source_parser.find_try_blocks(main_node)
containing_block = source_parser.find_block_containing_argparse([main_node] + try_nodes)
def test_has_instantiator_returns_true_if_object_found(self):
source = '''
parser = ArgumentParser(description='Example Argparse Program', formatter_class=RawDescriptionHelpFormatter)
parser.add_argument("filename", help="filename")
'''
nodes = ast.parse(source)
self.assertTrue(source_parser.has_instantiator(nodes.body[0], 'ArgumentParser'))
def test_has_instantiator_returns_false_if_object_not_found(self):
source = '''
parser = NopeParser(description='Example Argparse Program', formatter_class=RawDescriptionHelpFormatter)
parser.add_argument("filename", help="filename")
'''
nodes = ast.parse(source)
self.assertFalse(source_parser.has_instantiator(nodes.body[0], 'ArgumentParser'))
def test_has_assignment_returns_true_if_object_found(self):
source = '''
parser = ArgumentParser(description='Example Argparse Program', formatter_class=RawDescriptionHelpFormatter)
parser.add_argument("filename", help="filename")
'''
nodes = ast.parse(source)
self.assertTrue(source_parser.has_assignment(nodes.body[1], 'add_argument'))
def test_has_assignment_returns_false_if_object_not_found(self):
source = '''
parser = ArgumentParser(description='Example Argparse Program', formatter_class=RawDescriptionHelpFormatter)
parser.add_argument("filename", help="filename")
'''
nodes = ast.parse(source)
self.assertFalse(source_parser.has_instantiator(nodes.body[1], 'add_argument'))
def test_parser_identifies_import_module(self):
source = '''
import os
import itertools
from os import path
'''
import _ast
nodes = ast.parse(source)
module_imports = source_parser.get_nodes_by_instance_type(nodes, _ast.Import)
self.assertEqual(2, len(module_imports))
def test_parser_identifies_import_from(self):
source = '''
import os
import itertools
from os import path
from gooey.gooey_decorator import Gooey
'''
import _ast
nodes = ast.parse(source)
from_imports = source_parser.get_nodes_by_instance_type(nodes, _ast.ImportFrom)
self.assertEqual(2, len(from_imports))
def test_get_indent_return_indent_amount_for_tabs_and_spaces(self):
spaced_lines = ["def main"," def main"," def main"," def main"]
expected_indent = ["", " ", " ", " "]
for line, expected in zip(spaced_lines, expected_indent):
self.assertEqual(expected, source_parser.get_indent(line))
# def test_parse_source_file__file_with_argparse_in_main__succesfully_finds_and_returns_ast_obejcts(self):
# ast_objects = source_parser.parse_source_file(self._module_with_argparse_in_main)
# for obj in ast_objects:
# self.assertTrue(type(obj) in (ast.Assign, ast.Expr))
#
# def test_parse_source_file__file_with_argparse_in_try_block__succesfully_finds_and_returns_ast_obejcts(self):
# ast_objects = source_parser.parse_source_file(self._module_with_arparse_in_try)
# for obj in ast_objects:
# self.assertTrue(type(obj) in (ast.Assign, ast.Expr))
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
# '''
# Created on Feb 2, 2014
#
# @author: Chris
#
# TODO:
# - test no argparse module
# - test argparse in main
# - test argparse in try/catch
# -
#
# '''
#
# import os
# import ast
# import unittest
# from gooey.python_bindings import source_parser
#
#
# basic_pyfile = \
# '''
# import os
#
# def say_jello():
# print "Jello!"
#
# def main():
# print "hello!"
# parser = ArgumentParser(description='Example Argparse Program', formatter_class=RawDescriptionHelpFormatter)
# parser.add_argument("filename", help="filename")
# parser.add_argument("-r", "--recursive", dest="recurse", action="store_true",
# help="recurse into subfolders [default: %(default)s]")
# parser.add_argument("-v", "--verbose", dest="verbose", action="count",
# help="set verbosity level [default: %(default)s]")
# parser.add_argument("-i", "--include", action="append",
# help="only include paths matching this regex pattern. Note: exclude is given preference over include. [default: %(default)s]",
# metavar="RE")
# parser.add_argument("-m", "--mycoolargument", help="mycoolargument")
# parser.add_argument("-e", "--exclude", dest="exclude",
# help="exclude paths matching this regex pattern. [default: %(default)s]", metavar="RE")
# parser.add_argument('-V', '--version', action='version')
# parser.add_argument('-T', '--tester', choices=['yes', 'no'])
# parser.add_argument(dest="paths", help="paths to folder(s) with source file(s) [default: %(default)s]",
# metavar="path", nargs='+')
#
# if __name__ == '__main__':
# main()
# '''
#
#
#
# class TestSourceParser(unittest.TestCase):
# PATH = os.path.join(os.path.dirname(__file__), 'examples')
#
# def module_path(self, name):
# return os.path.join(self.PATH, name)
#
# def setUp(self):
# self._mockapp = self.module_path('examples.py')
# self._module_with_noargparse = self.module_path('module_with_no_argparse.py')
# self._module_with_arparse_in_try = self.module_path('TODO.py')
# self._module_with_argparse_in_main = self.module_path('example_argparse_souce_in_main.py')
#
# def test_should_throw_parser_exception_if_no_argparse_found_in_module(self):
# with self.assertRaises(source_parser.ParserError):
# source_parser.parse_source_file(self._module_with_noargparse)
#
#
# def test_find_main(self):
# example_source = '''
# def main(): pass
# '''
# nodes = ast.parse(example_source)
# main_node = source_parser.find_main(nodes)
# self.assertEqual('main', main_node.name)
#
#
# def test_find_main_throws_exception_if_not_found(self):
# example_source = '''
# def some_cool_function_that_is_not_main(): pass
# '''
# with self.assertRaises(source_parser.ParserError):
# nodes = ast.parse(example_source)
# main_node = source_parser.find_main(nodes)
# self.assertEqual('main', main_node.name)
#
#
# def test_find_try_blocks_finds_all_tryblock_styles(self):
# example_source = '''
# try: a = 1
# except: pass
#
# try: pass
# finally: pass
#
# try: pass
# except: pass
# else: pass
# '''
# nodes = ast.parse(example_source)
# try_blocks = source_parser.find_try_blocks(nodes)
# self.assertEqual(3, len(try_blocks))
#
#
# def test_find_try_blocks_returns_empty_if_no_blocks_present(self):
# example_source = 'def main(): pass'
# nodes = ast.parse(example_source)
# result = source_parser.find_try_blocks(nodes)
# self.assertEqual(list(), result)
#
# def test_find_argparse_located_object_when_imported_by_direct_name(self):
# example_source = '''
# def main():
# parser = ArgumentParser(description='Example Argparse Program', formatter_class=RawDescriptionHelpFormatter)
# '''
# nodes = ast.parse(example_source)
# main_node = source_parser.find_main(nodes)
# self.assertEqual('main', main_node.name)
# containing_block = source_parser.find_block_containing_argparse([main_node])
# self.assertTrue(containing_block is not None)
#
# def test_find_argparse_located_object_when_access_through_module_dot_notation(self):
# example_source = '''
# def main():
# parser = argparse.ArgumentParser(description='Example Argparse Program', formatter_class=RawDescriptionHelpFormatter)
# '''
# nodes = ast.parse(example_source)
# main_node = source_parser.find_main(nodes)
# self.assertEqual('main', main_node.name)
# containing_block = source_parser.find_block_containing_argparse([main_node])
# self.assertTrue(containing_block is not None)
#
# def test_find_argparse_locates_assignment_stmnt_in_main(self):
# nodes = ast.parse(source_parser._openfile(self._module_with_argparse_in_main))
# main_node = source_parser.find_main(nodes)
# self.assertEqual('main', main_node.name)
# containing_block = source_parser.find_block_containing_argparse([main_node])
# self.assertTrue(containing_block is not None)
# self.assertEqual('main', containing_block.name)
#
#
# def test_find_argparse_locates_assignment_stmnt_in_try_block(self):
# nodes = ast.parse(source_parser._openfile(self._module_with_arparse_in_try))
# main_node = source_parser.find_main(nodes)
# self.assertEqual('main', main_node.name)
# try_nodes = source_parser.find_try_blocks(main_node)
# self.assertTrue(len(try_nodes) > 0)
# containing_block = source_parser.find_block_containing_argparse([main_node] + try_nodes)
# self.assertEqual(ast.TryExcept, type(containing_block))
#
#
# def test_find_argparse_throws_exception_if_not_found(self):
# with self.assertRaises(source_parser.ParserError):
# nodes = ast.parse(source_parser._openfile(self._module_with_noargparse))
# main_node = source_parser.find_main(nodes)
# self.assertEqual('main', main_node.name)
# try_nodes = source_parser.find_try_blocks(main_node)
# containing_block = source_parser.find_block_containing_argparse([main_node] + try_nodes)
#
#
# def test_has_instantiator_returns_true_if_object_found(self):
# source = '''
# parser = ArgumentParser(description='Example Argparse Program', formatter_class=RawDescriptionHelpFormatter)
# parser.add_argument("filename", help="filename")
# '''
# nodes = ast.parse(source)
# self.assertTrue(source_parser.has_instantiator(nodes.body[0], 'ArgumentParser'))
#
#
# def test_has_instantiator_returns_false_if_object_not_found(self):
# source = '''
# parser = NopeParser(description='Example Argparse Program', formatter_class=RawDescriptionHelpFormatter)
# parser.add_argument("filename", help="filename")
# '''
# nodes = ast.parse(source)
# self.assertFalse(source_parser.has_instantiator(nodes.body[0], 'ArgumentParser'))
#
# def test_has_assignment_returns_true_if_object_found(self):
# source = '''
# parser = ArgumentParser(description='Example Argparse Program', formatter_class=RawDescriptionHelpFormatter)
# parser.add_argument("filename", help="filename")
# '''
# nodes = ast.parse(source)
# self.assertTrue(source_parser.has_assignment(nodes.body[1], 'add_argument'))
#
# def test_has_assignment_returns_false_if_object_not_found(self):
# source = '''
# parser = ArgumentParser(description='Example Argparse Program', formatter_class=RawDescriptionHelpFormatter)
# parser.add_argument("filename", help="filename")
# '''
# nodes = ast.parse(source)
# self.assertFalse(source_parser.has_instantiator(nodes.body[1], 'add_argument'))
#
# def test_parser_identifies_import_module(self):
# source = '''
# import os
# import itertools
# from os import path
# '''
# import _ast
# nodes = ast.parse(source)
# module_imports = source_parser.get_nodes_by_instance_type(nodes, _ast.Import)
# self.assertEqual(2, len(module_imports))
#
# def test_parser_identifies_import_from(self):
# source = '''
# import os
# import itertools
# from os import path
# from gooey.gooey_decorator import Gooey
# '''
# import _ast
# nodes = ast.parse(source)
# from_imports = source_parser.get_nodes_by_instance_type(nodes, _ast.ImportFrom)
# self.assertEqual(2, len(from_imports))
#
#
# def test_get_indent_return_indent_amount_for_tabs_and_spaces(self):
# spaced_lines = ["def main"," def main"," def main"," def main"]
# expected_indent = ["", " ", " ", " "]
# for line, expected in zip(spaced_lines, expected_indent):
# self.assertEqual(expected, source_parser.get_indent(line))
#
# # def test_parse_source_file__file_with_argparse_in_main__succesfully_finds_and_returns_ast_obejcts(self):
# # ast_objects = source_parser.parse_source_file(self._module_with_argparse_in_main)
# # for obj in ast_objects:
# # self.assertTrue(type(obj) in (ast.Assign, ast.Expr))
# #
# # def test_parse_source_file__file_with_argparse_in_try_block__succesfully_finds_and_returns_ast_obejcts(self):
# # ast_objects = source_parser.parse_source_file(self._module_with_arparse_in_try)
# # for obj in ast_objects:
# # self.assertTrue(type(obj) in (ast.Assign, ast.Expr))
#
#
# if __name__ == "__main__":
# #import sys;sys.argv = ['', 'Test.testName']
# unittest.main()
#
Loading…
Cancel
Save