def test_parse_all_signatures(self): assert_equal(parse_all_signatures(['random text', '.. function:: fn(arg', '.. function:: fn()', ' .. method:: fn2(arg)']), ([('fn', '()'), ('fn2', '(arg)')], []))
def test_as_xml(self) -> None: cobertura_package = CoberturaPackage('foobar') cobertura_package.covered_lines = 21 cobertura_package.total_lines = 42 child_package = CoberturaPackage('raz') child_package.covered_lines = 10 child_package.total_lines = 10 child_package.classes['class'] = etree.Element('class') cobertura_package.packages['raz'] = child_package expected_output = textwrap.dedent('''\ <package complexity="1.0" name="foobar" branch-rate="0" line-rate="0.5000"> <classes/> <packages> <package complexity="1.0" name="raz" branch-rate="0" line-rate="1.0000"> <classes> <class/> </classes> </package> </packages> </package> ''').encode('ascii') assert_equal(expected_output, etree.tostring(cobertura_package.as_xml(), pretty_print=True))
def test_coherence(self): # We have to special case Options.BuildType because we're required to # set a target options = Options() options.build_type = BuildType.PROGRAM_TEXT _, parsed_options = process_options(['-c', 'cmd']) assert_equal(options, parsed_options)
def test_true_only_of_instance(self): to = true_only(self.fx.a) assert_equal(str(to), "A") assert_true(to.can_be_true) assert_false(to.can_be_false) assert_type(Instance, to) # The original class still can be false assert_true(self.fx.a.can_be_false)
def test_false_only_of_instance(self): fo = false_only(self.fx.a) assert_equal(str(fo), "A") assert_false(fo.can_be_true) assert_true(fo.can_be_false) assert_type(Instance, fo) # The original class still can be true assert_true(self.fx.a.can_be_true)
def test_callable_type_with_default_args(self): c = CallableType([self.x, self.y], [ARG_POS, ARG_OPT], [None, None], AnyType(), self.function) assert_equal(str(c), 'def (X?, Y? =) -> Any') c2 = CallableType([self.x, self.y], [ARG_OPT, ARG_OPT], [None, None], AnyType(), self.function) assert_equal(str(c2), 'def (X? =, Y? =) -> Any')
def test_topsort(self) -> None: a = frozenset({"A"}) b = frozenset({"B"}) c = frozenset({"C"}) d = frozenset({"D"}) data = {a: {b, c}, b: {d}, c: {d}} # type: Dict[AbstractSet[str], Set[AbstractSet[str]]] res = list(topsort(data)) assert_equal(res, [{d}, {b, c}, {a}])
def test_sorted_components(self) -> None: manager = self._make_manager() graph = {'a': State('a', None, 'import b, c', manager), 'd': State('d', None, 'pass', manager), 'b': State('b', None, 'import c', manager), 'c': State('c', None, 'import b, d', manager), } res = sorted_components(graph) assert_equal(res, [frozenset({'d'}), frozenset({'c', 'b'}), frozenset({'a'})])
def test_generic_function_type(self): c = Callable([self.x, self.y], [ARG_POS, ARG_POS], [None, None], self.y, False, None, [TypeVarDef('X', -1, None)]) assert_equal(str(c), 'def [X] (X?, Y?) -> Y?') v = [TypeVarDef('Y', -1, None), TypeVarDef('X', -2, None)] c2 = Callable([], [], [], Void(None), False, None, v) assert_equal(str(c2), 'def [Y, X] ()')
def assert_vararg_map(self, caller_kinds, callee_kinds, expected, vararg_type): result = map_actuals_to_formals( caller_kinds, [], callee_kinds, [], lambda i: vararg_type) assert_equal(result, expected)
def test_find_unique_signatures(self): assert_equal(find_unique_signatures( [('func', '()'), ('func', '()'), ('func2', '()'), ('func2', '(arg)'), ('func3', '(arg, arg2)')]), [('func', '()'), ('func3', '(arg, arg2)')])
def test_callable_type(self): c = CallableType([self.x, self.y], [ARG_POS, ARG_POS], [None, None], AnyType(), self.function) assert_equal(str(c), 'def (X?, Y?) -> Any') c2 = CallableType([], [], [], Void(None), False) assert_equal(str(c2), 'def ()')
def assert_solve(self, vars, constraints, results): res = [] for r in results: if isinstance(r, tuple): res.append(r[0]) else: res.append(r) actual = solve_constraints(vars, constraints) assert_equal(str(actual), str(res))
def assert_expand(self, orig, map_items, result): lower_bounds = {} for id, t in map_items: lower_bounds[id] = t exp = expand_type(orig, lower_bounds) # Remove erased tags (asterisks). assert_equal(str(exp).replace('*', ''), str(result))
def assert_map(self, caller_kinds, callee_kinds, expected): caller_kinds, caller_names = expand_caller_kinds(caller_kinds) callee_kinds, callee_names = expand_callee_kinds(callee_kinds) result = map_actuals_to_formals( caller_kinds, caller_names, callee_kinds, callee_names, lambda i: Any()) assert_equal(result, expected)
def test_generic_function_type(self) -> None: c = CallableType([self.x, self.y], [ARG_POS, ARG_POS], [None, None], self.y, self.function, name=None, variables=[TypeVarDef('X', -1, None, self.fx.o)]) assert_equal(str(c), 'def [X] (X?, Y?) -> Y?') v = [TypeVarDef('Y', -1, None, self.fx.o), TypeVarDef('X', -2, None, self.fx.o)] c2 = CallableType([], [], [], Void(None), self.function, name=None, variables=v) assert_equal(str(c2), 'def [Y, X] ()')
def test_true_only_of_union(self): tup_type = self.tuple(AnyType()) # Union of something that is unknown, something that is always true, something # that is always false union_type = UnionType([self.fx.a, tup_type, self.tuple()]) to = true_only(union_type) assert_equal(len(to.items), 2) assert_true(to.items[0].can_be_true) assert_false(to.items[0].can_be_false) assert_true(to.items[1] is tup_type)
def test_generic_function_type(self): c = Callable([self.x, self.y], [ARG_POS, ARG_POS], [None, None], self.y, False, None, TypeVars([TypeVarDef('X', -1)])) assert_equal(str(c), 'def <X> (X?, Y?) -> Y?') v = TypeVars([TypeVarDef('Y', -1, UnboundType('X')), TypeVarDef('X', -2)]) c2 = Callable([], [], [], Void(None), False, None, v) assert_equal(str(c2), 'def <Y is X?, X> ()')
def test_scc(self) -> None: vertices = {'A', 'B', 'C', 'D'} edges = {'A': ['B', 'C'], 'B': ['C'], 'C': ['B', 'D'], 'D': []} # type: Dict[str, List[str]] sccs = set(frozenset(x) for x in strongly_connected_components(vertices, edges)) assert_equal(sccs, {frozenset({'A'}), frozenset({'B', 'C'}), frozenset({'D'})})
def assert_simple_join(self, s, t, join): result = join_types(s, t) actual = str(result) expected = str(join) assert_equal(actual, expected, 'join({}, {}) == {{}} ({{}} expected)'.format(s, t)) if not isinstance(s, ErrorType) and not isinstance(result, ErrorType): assert_true(is_subtype(s, result), '{} not subtype of {}'.format(s, result)) if not isinstance(t, ErrorType) and not isinstance(result, ErrorType): assert_true(is_subtype(t, result), '{} not subtype of {}'.format(t, result))
def test_false_only_of_union(self) -> None: tup_type = self.tuple() # Union of something that is unknown, something that is always true, something # that is always false union_type = UnionType([self.fx.a, self.tuple(AnyType()), tup_type]) assert_equal(len(union_type.items), 3) fo = false_only(union_type) assert isinstance(fo, UnionType) assert_equal(len(fo.items), 2) assert_false(fo.items[0].can_be_true) assert_true(fo.items[0].can_be_false) assert_true(fo.items[1] is tup_type)
def assert_simple_meet(self, s, t, meet): result = meet_types(s, t) actual = str(result) expected = str(meet) assert_equal(actual, expected, 'meet({}, {}) == {{}} ({{}} expected)'.format(s, t)) if not isinstance(s, ErrorType) and not isinstance(result, ErrorType): assert_true(is_subtype(result, s), '{} not subtype of {}'.format(result, s)) if not isinstance(t, ErrorType) and not isinstance(result, ErrorType): assert_true(is_subtype(result, t), '{} not subtype of {}'.format(result, t))
def test_order_ascc(self) -> None: manager = self._make_manager() graph = {'a': State('a', None, 'import b, c', manager), 'd': State('d', None, 'def f(): import a', manager), 'b': State('b', None, 'import c', manager), 'c': State('c', None, 'import b, d', manager), } res = sorted_components(graph) assert_equal(res, [frozenset({'a', 'd', 'c', 'b'})]) ascc = res[0] scc = order_ascc(graph, ascc) assert_equal(scc, ['d', 'c', 'b', 'a'])
def assert_line(self, s: str, a: List[int]) -> None: s = s.replace('\\n', '\n') s = s.replace('\\r', '\r') tt = lex(s)[0] r = [] for t in tt: r.append(t.line) if len(r) == len(a) + 2: a = a[:] a.append(a[-1]) a.append(a[-1]) assert_equal(r, a)
def assert_line(self, s, a): s = s.replace('\\n', '\n') s = s.replace('\\r', '\r') tt = lex(s) r = [] for t in tt: r.append(t.line) if len(r) == len(a) + 2: a = a[:] a.append(a[-1]) a.append(a[-1]) assert_equal(r, a)
def assert_solve(self, vars: List[TypeVarId], constraints: List[Constraint], results: List[Union[None, Type, Tuple[Type, Type]]], ) -> None: res = [] # type: List[Optional[Type]] for r in results: if isinstance(r, tuple): res.append(r[0]) else: res.append(r) actual = solve_constraints(vars, constraints) assert_equal(str(actual), str(res))
def assert_expand(self, orig: Type, map_items: List[Tuple[TypeVarId, Type]], result: Type, ) -> None: lower_bounds = {} for id, t in map_items: lower_bounds[id] = t exp = expand_type(orig, lower_bounds) # Remove erased tags (asterisks). assert_equal(str(exp).replace('*', ''), str(result))
def assert_vararg_map(self, caller_kinds: List[int], callee_kinds: List[int], expected: List[List[int]], vararg_type: Type, ) -> None: result = map_actuals_to_formals( caller_kinds, [], callee_kinds, [], lambda i: vararg_type) assert_equal(result, expected)
def assert_map(self, caller_kinds_: List[Union[int, str]], callee_kinds_: List[Union[int, Tuple[int, str]]], expected: List[List[int]], ) -> None: caller_kinds, caller_names = expand_caller_kinds(caller_kinds_) callee_kinds, callee_names = expand_callee_kinds(callee_kinds_) result = map_actuals_to_formals( caller_kinds, caller_names, callee_kinds, callee_names, lambda i: AnyType()) assert_equal(result, expected)
def assert_lex(self, src, lexed): src = src.replace('\\n', '\n') src = src.replace('\\r', '\r') if lexed.endswith(' ...'): lexed = lexed[:-3] + 'Break() Eof()' l = lex(src) r = [] for t in l: r.append(str(t)) act = ' '.join(r) if act != lexed: print('Actual: ', act) print('Expected:', lexed) assert_equal(act, lexed)
def test_parse_all_signatures(self) -> None: assert_equal( parse_all_signatures([ 'random text', '.. function:: fn(arg', '.. function:: fn()', ' .. method:: fn2(arg)' ]), ([('fn', '()'), ('fn2', '(arg)')], []))
def test_type_variable_binding(self): assert_equal(str(TypeVarDef('X', 1, None, self.fx.o)), 'X') assert_equal(str(TypeVarDef('X', 1, [self.x, self.y], self.fx.o)), 'X in (X?, Y?)')
def test_tuple_type(self): assert_equal(str(TupleType([], None)), 'Tuple[]') assert_equal(str(TupleType([self.x], None)), 'Tuple[X?]') assert_equal(str(TupleType([self.x, AnyType()], None)), 'Tuple[X?, Any]')
def test_void_type(self): assert_equal(str(Void(None)), 'void')
def assert_vararg_map(self, caller_kinds, callee_kinds, expected, vararg_type): result = map_actuals_to_formals(caller_kinds, [], callee_kinds, [], lambda i: vararg_type) assert_equal(result, expected)
def test_infer_hash_sig(self) -> None: assert_equal(infer_method_sig('__hash__'), '()')
def test_build_signature(self): assert_equal(build_signature([], []), '()') assert_equal(build_signature(['arg'], []), '(arg)') assert_equal(build_signature(['arg', 'arg2'], []), '(arg, arg2)') assert_equal(build_signature(['arg'], ['arg2']), '(arg, arg2=Undefined)') assert_equal(build_signature(['arg'], ['arg2', '**x']), '(arg, arg2=Undefined, **x)')
def test_any(self) -> None: assert_equal(str(AnyType(TypeOfAny.special_form)), 'Any')
def assert_parse_signature(self, sig, result): assert_equal(parse_signature(sig), result)
def test_infer_getitem_sig(self) -> None: assert_equal(infer_method_sig('__getitem__'), '(index)')
def test_simple_unbound_type(self): u = UnboundType('Foo') assert_equal(str(u), 'Foo?')
def assert_parse_signature( self, sig: str, result: Tuple[str, List[str], List[str]]) -> None: assert_equal(parse_signature(sig), result)
def test_generate_c_type_stub_no_crash_for_object(self) -> None: output = [] # type: List[str] mod = ModuleType('module', '') # any module is fine generate_c_type_stub(mod, 'alias', object, output) assert_equal(output[0], 'class alias:')
def test_infer_unary_op_sig(self) -> None: for op in ('neg', 'pos'): assert_equal(infer_method_sig('__%s__' % op), '()')
def assert_erase(self, orig: Type, result: Type) -> None: assert_equal(str(erase_type(orig)), str(result))
def test_find_unique_signatures(self) -> None: assert_equal( find_unique_signatures([('func', '()'), ('func', '()'), ('func2', '()'), ('func2', '(arg)'), ('func3', '(arg, arg2)')]), [('func', '()'), ('func3', '(arg, arg2)')])
def test_generic_unbound_type(self) -> None: u = UnboundType('Foo', [UnboundType('T'), AnyType(TypeOfAny.special_form)]) assert_equal(str(u), 'Foo?[T?, Any]')
def test_infer_sig_from_docstring(self) -> None: assert_equal(infer_sig_from_docstring('\nfunc(x) - y', 'func'), '(x)') assert_equal(infer_sig_from_docstring('\nfunc(x, Y_a=None)', 'func'), '(x, Y_a=None)') assert_equal(infer_sig_from_docstring('\nafunc(x) - y', 'func'), None) assert_equal(infer_sig_from_docstring('\nfunc(x, y', 'func'), None) assert_equal(infer_sig_from_docstring('\nfunc(x=z(y))', 'func'), None) assert_equal(infer_sig_from_docstring('\nfunc x', 'func'), None)
def test_tuple_type(self) -> None: assert_equal(str(TupleType([], self.fx.std_tuple)), 'Tuple[]') assert_equal(str(TupleType([self.x], self.fx.std_tuple)), 'Tuple[X?]') assert_equal(str(TupleType([self.x, AnyType()], self.fx.std_tuple)), 'Tuple[X?, Any]')
def assert_erase(self, orig, result): assert_equal(str(erase_type(orig)), str(result))
def assert_replace(self, orig, result): assert_equal(str(replace_type_vars(orig)), str(result))
def assert_erase(self, orig, result): assert_equal(str(erase_type(orig, self.fx.basic)), str(result))
def test_get_line_rate(self) -> None: assert_equal('1.0', get_line_rate(0, 0)) assert_equal('0.3333', get_line_rate(1, 3))
def test_any(self): assert_equal(str(AnyType()), 'Any')
def test_infer_setitem_sig(self) -> None: assert_equal(infer_method_sig('__setitem__'), '(index, object)')
def test_generic_unbound_type(self): u = UnboundType('Foo', [UnboundType('T'), AnyType()]) assert_equal(str(u), 'Foo?[T?, Any]')
def test_infer_binary_op_sig(self) -> None: for op in ('eq', 'ne', 'lt', 'le', 'gt', 'ge', 'add', 'radd', 'sub', 'rsub', 'mul', 'rmul'): assert_equal(infer_method_sig('__%s__' % op), '(other)')
def test_build_signature(self) -> None: assert_equal(build_signature([], []), '()') assert_equal(build_signature(['arg'], []), '(arg)') assert_equal(build_signature(['arg', 'arg2'], []), '(arg, arg2)') assert_equal(build_signature(['arg'], ['arg2']), '(arg, arg2=...)') assert_equal(build_signature(['arg'], ['arg2', '**x']), '(arg, arg2=..., **x)')