def test_stats_string_representations_same_as_underlying_dict(): underyling_dict = { 'key1': 'val1', 'key2': [1, 2, 3], 'key3': {}, } stats = Stats(underyling_dict) assert stats.__repr__() == underyling_dict.__repr__() assert stats.__str__() == underyling_dict.__str__()
def test_asserts_are_run_counter_check_passes(): loader = MockLoader(assertions=ASSERTIONS) stats = Stats() stats.append('counter', 10) checker = AssertionChecker(loader, stats) successes, failures, errors = checker.run() assert len(successes) == 2 assert len(failures) == 1 assert len(errors) == 1
def test_with_stats_namespace(): _stats = Stats() namespaced_stats = _stats.namespaced('level2').namespaced('level3') namespaced_stats.increment('counter') def stats_namespaced_assertion(stats): assert stats.items() == namespaced_stats.items() assert stats.get('counter') == 1 return True, None decorated_assertion = assertion(stats_namespaces=['level2', 'level3'])( stats_namespaced_assertion, ) Assertion(_stats, [decorated_assertion]).run()
def _test_visits_file_with_ast_tree_and_relative_path( mock_file_contents, expected_file_contents_for_parsing, ): mock_tree = astroid.Module(doc="", name="mock_module") file_opener = MockFileOpener(mock_file_contents) file_walker = MockFileWalker(MOCK_FILES) parser = MockParser(mock_tree) analyzer = Analyzer( MOCK_BASE_DIRECTORY_PATH, file_walker, file_opener.open, parser.parse ) analyzer.override_node_visitor_master(MockNodeMaster) analyzer.run(Stats()) assert len(file_opener.opens) == len(MOCK_FILES) assert len(MockNodeMaster.visited) == len(MOCK_FILES) assert len(parser.parses) == len(MOCK_FILES) for i, (tree, file_path) in enumerate(MockNodeMaster.visited): assert tree == mock_tree expected_file_path = RELATIVE_MOCK_FILE_PATHS[i] assert file_path == expected_file_path for i, (args, _) in enumerate(parser.parses): file_contents_received_for_parsing, file_name = args assert file_contents_received_for_parsing == _as_unicode( expected_file_contents_for_parsing ) assert file_name == MOCK_FILE_NAMES[i]
def test_sets_stats_and_file_path(): stats = Stats() file_path = "/mock/path" node_visitor = NodeVisitor(stats, file_path) assert node_visitor.stats == stats assert node_visitor.rel_file_path == file_path
def test_erroring_assertion(): successes, failures, errors = Assertion( Stats(), [erroring_assertion], ).run() assert successes == [] assert failures == {} assert errors == {erroring_assertion.__name__: MOCK_ERR}
def test_unsuccessful_assertion(): successes, failures, errors = Assertion( Stats(), [unsuccessful_assertion], ).run() assert successes == [] assert failures == {unsuccessful_assertion.__name__: MOCK_FAILURE_MSG} assert errors == {}
def test_successful_assertion(): successes, failures, errors = Assertion( Stats(), [successful_assertion], ).run() assert successes == [successful_assertion.__name__] assert failures == {} assert errors == {}
def test_track_troublesome_module_usages(code, module_name): NodeVisitorMaster.node_visitor_registry = [] module = astroid.parse(code, module_name) assert len(NodeVisitorMaster.node_visitor_registry) == 0 count_import_usages('TROUBLESOME', module_name, mock_importer) assert len(NodeVisitorMaster.node_visitor_registry) == 2 stats = Stats() NodeVisitorMaster.visit(stats, module, module_name + ".py") assert stats == {"TROUBLESOME": {"api.views.Trouble.py": 5}}
def test_multiple_assertions(): assertions = [ successful_assertion, unsuccessful_assertion, ] successes, failures, errors = Assertion(Stats(), assertions).run() assert successes == [successful_assertion.__name__] assert failures == {unsuccessful_assertion.__name__: MOCK_FAILURE_MSG}
def test_count_calling_files_function(stats_namespace, code, module_name, expected_callable_qname, expected_stats): NodeVisitorMaster.node_visitor_registry = [] module = astroid.parse(code, module_name) assert len(NodeVisitorMaster.node_visitor_registry) == 0 count_calling_files(stats_namespace, expected_callable_qname) assert len(NodeVisitorMaster.node_visitor_registry) == 1 stats = Stats() NodeVisitorMaster.visit(stats, module, module_name + ".py") assert stats == expected_stats
def test_unsuccessful_assertion_no_message(): successes, failures, errors = Assertion( Stats(), [unsuccessful_assertion_no_message], ).run() assert successes == [] assert failures == { unsuccessful_assertion_no_message.__name__: 'assert False', } assert errors == {}
def test_append(): stats = Stats() mydict = {1: 2} stats.append('mydict', mydict) mylist = [1, 2, 3] stats.append('mylist', mylist) assert stats.get('mydict', mydict) assert stats.get('mylist', mylist)
def test_responds_to_dict_methods(): stats = Stats() stats.increment('mycounter') assert list(stats.keys()) == ['mycounter'] assert list(stats.values()) == [1] assert stats['mycounter'] == 1
def run(self): try: sys.path.insert(0, self.base_directory) loader = ModuleLoader(self.codewatch_config_module) stats = Stats() file_walker = FileWalker(loader, self.base_directory) analyzer = Analyzer(self.base_directory, file_walker) analyzer.run(stats) checker = AssertionChecker(loader, stats) return checker.run() finally: del sys.path[0]
def test_count_calling_files_with_inferences(): NodeVisitorMaster.node_visitor_registry = [] code = """\ class B(object): pass class A(object): class objects(object): @staticmethod def get(): return B() @staticmethod def save(): pass a = A.objects.get() a.save() """ module = astroid.parse(code, 'infer.this') def infer_objects_get_as_a(call_node, context=None): if getattr(call_node.func, "attrname") != 'get': raise UseInferenceDefault() code = """\ class A(object): class objects(object): @staticmethod def get(): pass def save(): pass""" m = astroid.parse(code, 'infer.this') class_node = m.body[0] return iter((class_node.instantiate_class(),)) assert len(NodeVisitorMaster.node_visitor_registry) == 0 count_calling_files( 'ccf_inf_testing', 'infer.this.A.save', inferences=[inference(nodes.Call, infer_objects_get_as_a)], ) assert len(NodeVisitorMaster.node_visitor_registry) == 1 stats = Stats() NodeVisitorMaster.visit(stats, module, "infer/this.py") assert stats == {'ccf_inf_testing': {'infer/this.py': 1}}
def run(self): if '/' in self.codewatch_config_module: raise ValueError(NOT_DIR_ERR) try: sys.path.insert(0, self.base_directory) NodeVisitorMaster.node_visitor_registry = [] loader = ModuleLoader(self.codewatch_config_module) stats = Stats() file_walker = FileWalker(loader, self.base_directory) analyzer = Analyzer(self.base_directory, file_walker) analyzer.run(stats) checker = AssertionChecker(loader, stats) return checker.run() finally: del sys.path[0]
def test_parse_errors_are_rethrown(): mock_tree = astroid.Module(doc="", name="mock_module") file_opener = MockFileOpener('') file_walker = MockFileWalker(MOCK_FILES) parser = MockErrorParser(mock_tree) analyzer = Analyzer( MOCK_BASE_DIRECTORY_PATH, file_walker, file_opener.open, parser.parse ) analyzer.override_node_visitor_master(MockNodeMaster) expected_err = ( 'An exception occurred while parsing file: ' '.*{}'.format( re.escape(os.path.join(MOCK_DIR_NAME, MOCK_FILE_NAMES[0])), ) ) with pytest.raises(ParseException, match=expected_err): analyzer.run(Stats())
def test_injects_stats(): stats = Stats() stats.increment('counter') Assertion(stats, [stats_assertion]).run()
def test_can_compare_to_normal_dict_with_namespace(): stats = Stats().namespaced('level1') stats.increment('abc') assert stats == {'abc': 1} assert stats != {}
def test_can_compare_to_normal_dict(): stats = Stats() stats.increment('abc') assert stats == {'abc': 1} assert stats != {}
def test_namespaced(): stats = Stats() stats.append('counter_level1', 1) stats.namespaced('level2').append('counter_level2', 2) stats.namespaced('level2').namespaced('level3').append( 'counter_level3', 3, ) assert stats.get('counter_level1') == 1 assert stats.get('level2').get('counter_level2') == 2 assert stats.get('level2').get('level3').get('counter_level3') == 3
def test_label_assertion(): successes, _, _ = Assertion(Stats(), [label_assertion]).run() assert successes[0] == MOCK_LABEL
def test_can_insert_and_retrieve_value(): stats = Stats() stats.append('abc', 123) assert stats.get('abc') == 123
def test_increment(): stats = Stats() stats.increment('mycounter') assert stats.get('mycounter', 1) stats.increment('mycounter') assert stats.get('mycounter', 2)
def test_append_list(): stats = Stats() stats.append_list('mylist', 1) stats.append_list('mylist', 2) stats.append_list('mylist', 3) assert stats.get('mylist', [1, 2, 3])
def test_baseexception_assertion_bubbles(): with pytest.raises(MOCK_BASEEXCEPTION_CLASS): Assertion(Stats(), [baseexception_assertion]).run()