Beispiel #1
0
def _output_to_existing(parsed_file: parse.PyTestGenParsedFile,
                        output_dir: str,
                        include: List[str] = []) -> None:
    """Output the tests in 'parsed_file' to an existing file, optionally
    only including a whitelist of functions to output tests for. This function
    will ensure tests that already existed in the existing file are not
    overwritten by newly generated tests.

    Args:
        parsed_file: The parsed file to output.
        output_dir: The path to the dir to output test files in.
        include: The list of function names to generate tests for. If empty,
            all functions will be used.
    """
    test_file_path = parsed_file.input_file.get_test_file_path(output_dir)
    module_name = parsed_file.input_file.get_module()
    existing_functions = parse.get_existing_test_functions(test_file_path)
    tests_to_generate = []
    for testable_func in parsed_file.testable_funcs:
        if testable_func.function_def.name in UNTESTABLE_FUNCTIONS:
            continue

        # skip the function if it isn't in the include list (if we have one)
        if any(include) and testable_func.function_def.name not in include:
            continue

        if testable_func.get_test_name() not in existing_functions:
            tests_to_generate.append(testable_func)

    with open(test_file_path, "a", encoding="utf-8") as test_file:
        for test_func in tests_to_generate:
            test_file.write(
                generator.generate_test_func(test_func, module_name))
Beispiel #2
0
def test_output_tests_include(fs, mock_parsed_set, monkeypatch):
    pytestgen.output.output_tests(mock_parsed_set, include=["a_test_function"])
    test_file_path = path.join("output", "a_dir", "test_a_file.py")
    assert path.exists(test_file_path) == True, "test file did not exist"

    # we need to patch FunctionDef back in, it was patched out in the
    # 'mock_class_testable_func' fixture used in 'mock_parsed_set'
    # otherwise isinstance() for FunctionDef will fail in
    # get_existing_test_functions()
    monkeypatch.setattr(pytestgen.parse.ast, "FunctionDef", FunctionDef)

    outputted_funcs = get_existing_test_functions(test_file_path)
    assert outputted_funcs == ["test_a_test_function"]