Herramientas de desarrollo
**************************

The modules described in this chapter help you write software.  For
example, the "pydoc" module takes a module and generates documentation
based on the module's contents.  The "doctest" and "unittest" modules
contains frameworks for writing unit tests that automatically exercise
code and verify that the expected output is produced.

La lista de módulos descritos en este capítulo es:

* "typing" --- Soporte para *type hints*

  * Specification for the Python Type System

  * Alias de tipo

  * NewType

  * Annotating callable objects

  * Genéricos

  * Annotating tuples

  * The type of class objects

  * Annotating generators and coroutines

  * Tipos genéricos definidos por el usuario

  * El tipo "Any"

  * Subtipado nominal vs estructural

  * Contenido del módulo

    * Primitivos especiales de tipado

      * Tipos especiales

        * "Any"

        * "AnyStr"

        * "LiteralString"

        * "Never"

        * "NoReturn"

        * "Self"

        * "TypeAlias"

      * Formas especiales

        * "Union"

        * "Optional"

        * "Concatenate"

        * "Literal"

        * "ClassVar"

        * "Final"

        * "Required"

        * "NotRequired"

        * "ReadOnly"

        * "Annotated"

        * "TypeIs"

        * "TypeGuard"

        * "Unpack"

      * Building generic types and type aliases

        * "Generic"

        * "TypeVar"

          * "__name__"

          * "__covariant__"

          * "__contravariant__"

          * "__infer_variance__"

          * "__bound__"

          * "__constraints__"

          * "__default__"

          * "has_default()"

        * "TypeVarTuple"

          * "__name__"

          * "__default__"

          * "has_default()"

        * "ParamSpec"

          * "args"

          * "kwargs"

          * "__name__"

          * "__default__"

          * "has_default()"

        * "ParamSpecArgs"

        * "ParamSpecKwargs"

        * "TypeAliasType"

          * "__name__"

          * "__module__"

          * "__type_params__"

          * "__value__"

      * Otras directivas especiales

        * "NamedTuple"

        * "NewType"

          * "__module__"

          * "__name__"

          * "__supertype__"

        * "Protocol"

        * "runtime_checkable()"

        * "TypedDict"

          * "__total__"

          * "__required_keys__"

          * "__optional_keys__"

          * "__readonly_keys__"

          * "__mutable_keys__"

    * Protocolos

      * "SupportsAbs"

      * "SupportsBytes"

      * "SupportsComplex"

      * "SupportsFloat"

      * "SupportsIndex"

      * "SupportsInt"

      * "SupportsRound"

    * ABCs for working with IO

      * "IO"

      * "TextIO"

      * "BinaryIO"

    * Funciones y decoradores

      * "cast()"

      * "assert_type()"

      * "assert_never()"

      * "reveal_type()"

      * "dataclass_transform()"

      * "overload()"

      * "get_overloads()"

      * "clear_overloads()"

      * "final()"

      * "no_type_check()"

      * "no_type_check_decorator()"

      * "override()"

      * "type_check_only()"

    * Ayudas de introspección

      * "get_type_hints()"

      * "get_origin()"

      * "get_args()"

      * "get_protocol_members()"

      * "is_protocol()"

      * "is_typeddict()"

      * "ForwardRef"

      * "NoDefault"

    * Constantes

      * "TYPE_CHECKING"

    * Deprecated aliases

      * Aliases to built-in types

        * "Dict"

        * "List"

        * "Set"

        * "FrozenSet"

        * "Tuple"

        * "Type"

      * Aliases to types in "collections"

        * "DefaultDict"

        * "OrderedDict"

        * "ChainMap"

        * "Counter"

        * "Deque"

      * Aliases to other concrete types

        * "Pattern"

        * "Match"

        * "Text"

      * Aliases to container ABCs in "collections.abc"

        * "AbstractSet"

        * "ByteString"

        * "Collection"

        * "Container"

        * "ItemsView"

        * "KeysView"

        * "Mapping"

        * "MappingView"

        * "MutableMapping"

        * "MutableSequence"

        * "MutableSet"

        * "Sequence"

        * "ValuesView"

      * Aliases to asynchronous ABCs in "collections.abc"

        * "Coroutine"

        * "AsyncGenerator"

        * "AsyncIterable"

        * "AsyncIterator"

        * "Awaitable"

      * Aliases to other ABCs in "collections.abc"

        * "Iterable"

        * "Iterator"

        * "Callable"

        * "Generator"

        * "Hashable"

        * "Reversible"

        * "Sized"

      * Aliases to "contextlib" ABCs

        * "ContextManager"

        * "AsyncContextManager"

  * Línea de tiempo de obsolescencia de características principales

* "pydoc" --- Documentation generator and online help system

* Modo de desarrollo de Python

  * Efectos del modo de desarrollo de Python

  * Ejemplo de ResourceWarning

  * Ejemplo de error de descriptor de archivo incorrecto

* "doctest" --- Test interactive Python examples

  * Uso simple: verificar ejemplos en docstrings

  * Uso Simple: Verificar ejemplos en un Archivo de Texto

  * Cómo funciona

    * ¿Qué docstrings son examinados?

    * ¿Cómo se reconocen los ejemplos de docstring?

    * ¿Cuál es el contexto de ejecución?

    * ¿Y las excepciones?

    * Banderas de Opción

      * "DONT_ACCEPT_TRUE_FOR_1"

      * "DONT_ACCEPT_BLANKLINE"

      * "NORMALIZE_WHITESPACE"

      * "ELLIPSIS"

      * "IGNORE_EXCEPTION_DETAIL"

      * "SKIP"

      * "COMPARISON_FLAGS"

      * "REPORT_UDIFF"

      * "REPORT_CDIFF"

      * "REPORT_NDIFF"

      * "REPORT_ONLY_FIRST_FAILURE"

      * "FAIL_FAST"

      * "REPORTING_FLAGS"

      * "register_optionflag()"

    * Directivas

    * Advertencias

  * API básica

    * "testfile()"

    * "testmod()"

    * "run_docstring_examples()"

  * API de unittest

    * "DocFileSuite()"

    * "DocTestSuite()"

    * "failureException"

    * "set_unittest_reportflags()"

  * API avanzada

    * Objetos DocTest

      * "DocTest"

        * "examples"

        * "globs"

        * "name"

        * "filename"

        * "lineno"

        * "docstring"

    * Objetos *Example*

      * "Example"

        * "source"

        * "want"

        * "exc_msg"

        * "lineno"

        * "indent"

        * "options"

    * Objetos *DocTestFinder*

      * "DocTestFinder"

        * "find()"

    * Objetos *DocTestParser*

      * "DocTestParser"

        * "get_doctest()"

        * "get_examples()"

        * "parse()"

    * TestResults objects

      * "TestResults"

        * "failed"

        * "attempted"

        * "skipped"

    * Objetos *DocTestRunner*

      * "DocTestRunner"

        * "report_start()"

        * "report_success()"

        * "report_failure()"

        * "report_unexpected_exception()"

        * "run()"

        * "summarize()"

        * "tries"

        * "failures"

        * "skips"

    * Objetos *OutputChecker*

      * "OutputChecker"

        * "check_output()"

        * "output_difference()"

  * Depuración

    * "script_from_examples()"

    * "testsource()"

    * "debug()"

    * "debug_src()"

    * "DebugRunner"

    * "DocTestFailure"

    * "test"

    * "example"

    * "got"

    * "UnexpectedException"

    * "test"

    * "example"

    * "exc_info"

  * Plataforma improvisada

* "unittest" --- Unit testing framework

  * Ejemplo sencillo

  * Interfaz de línea de comandos

    * Opciones de la línea de órdenes

  * Descubrimiento de pruebas

  * Organización del código de pruebas

  * Reutilización de código de prueba anterior

  * Omitir tests y fallos esperados

    * "skip()"

    * "skipIf()"

    * "skipUnless()"

    * "expectedFailure()"

    * "SkipTest"

  * Distinguiendo iteraciones de tests empleando subtests

  * Clases y funciones

    * Casos de test

      * "TestCase"

        * "setUp()"

        * "tearDown()"

        * "setUpClass()"

        * "tearDownClass()"

        * "run()"

        * "skipTest()"

        * "subTest()"

        * "debug()"

        * "assertEqual()"

        * "assertNotEqual()"

        * "assertTrue()"

        * "assertFalse()"

        * "assertIs()"

        * "assertIsNot()"

        * "assertIsNone()"

        * "assertIsNotNone()"

        * "assertIn()"

        * "assertNotIn()"

        * "assertIsInstance()"

        * "assertNotIsInstance()"

        * "assertRaises()"

        * "assertRaisesRegex()"

        * "assertWarns()"

        * "assertWarnsRegex()"

        * "assertLogs()"

          * "records"

          * "output"

        * "assertNoLogs()"

        * "assertAlmostEqual()"

        * "assertNotAlmostEqual()"

        * "assertGreater()"

        * "assertGreaterEqual()"

        * "assertLess()"

        * "assertLessEqual()"

        * "assertRegex()"

        * "assertNotRegex()"

        * "assertCountEqual()"

        * "addTypeEqualityFunc()"

        * "assertMultiLineEqual()"

        * "assertSequenceEqual()"

        * "assertListEqual()"

        * "assertTupleEqual()"

        * "assertSetEqual()"

        * "assertDictEqual()"

        * "fail()"

        * "failureException"

        * "longMessage"

        * "maxDiff"

        * "countTestCases()"

        * "defaultTestResult()"

        * "id()"

        * "shortDescription()"

        * "addCleanup()"

        * "enterContext()"

        * "doCleanups()"

        * "addClassCleanup()"

        * "enterClassContext()"

        * "doClassCleanups()"

      * "IsolatedAsyncioTestCase"

        * "loop_factory"

        * "asyncSetUp()"

        * "asyncTearDown()"

        * "addAsyncCleanup()"

        * "enterAsyncContext()"

        * "run()"

      * "FunctionTestCase"

    * Agrupando tests

      * "TestSuite"

        * "addTest()"

        * "addTests()"

        * "run()"

        * "debug()"

        * "countTestCases()"

        * "__iter__()"

    * Cargando y ejecutando tests

      * "TestLoader"

        * "errors"

        * "loadTestsFromTestCase()"

        * "loadTestsFromModule()"

        * "loadTestsFromName()"

        * "loadTestsFromNames()"

        * "getTestCaseNames()"

        * "discover()"

        * "testMethodPrefix"

        * "sortTestMethodsUsing"

        * "suiteClass"

        * "testNamePatterns"

      * "TestResult"

        * "errors"

        * "failures"

        * "skipped"

        * "expectedFailures"

        * "unexpectedSuccesses"

        * "collectedDurations"

        * "shouldStop"

        * "testsRun"

        * "buffer"

        * "failfast"

        * "tb_locals"

        * "wasSuccessful()"

        * "stop()"

        * "startTest()"

        * "stopTest()"

        * "startTestRun()"

        * "stopTestRun()"

        * "addError()"

        * "addFailure()"

        * "addSuccess()"

        * "addSkip()"

        * "addExpectedFailure()"

        * "addUnexpectedSuccess()"

        * "addSubTest()"

        * "addDuration()"

      * "TextTestResult"

      * "defaultTestLoader"

      * "TextTestRunner"

        * "_makeResult()"

        * "run()"

      * "main()"

      * load_tests protocolo

  * Instalaciones para clases y módulos

    * setUpClass y tearDownClass

    * setUpModule y tearDownModule

      * "addModuleCleanup()"

      * "enterModuleContext()"

      * "doModuleCleanups()"

  * Manejo de señales

    * "installHandler()"

    * "registerResult()"

    * "removeResult()"

    * "removeHandler()"

* "unittest.mock" --- mock object library

  * Guía rápida

  * La clase Mock

    * "Mock"

      * "assert_called()"

      * "assert_called_once()"

      * "assert_called_with()"

      * "assert_called_once_with()"

      * "assert_any_call()"

      * "assert_has_calls()"

      * "assert_not_called()"

      * "reset_mock()"

      * "mock_add_spec()"

      * "attach_mock()"

      * "configure_mock()"

      * "__dir__()"

      * "_get_child_mock()"

      * "called"

      * "call_count"

      * "return_value"

      * "side_effect"

      * "call_args"

      * "call_args_list"

      * "method_calls"

      * "mock_calls"

      * "__class__"

    * "NonCallableMock"

    * "PropertyMock"

    * "AsyncMock"

      * "assert_awaited()"

      * "assert_awaited_once()"

      * "assert_awaited_with()"

      * "assert_awaited_once_with()"

      * "assert_any_await()"

      * "assert_has_awaits()"

      * "assert_not_awaited()"

      * "reset_mock()"

      * "await_count"

      * "await_args"

      * "await_args_list"

    * "ThreadingMock"

      * "wait_until_called()"

      * "wait_until_any_call_with()"

      * "DEFAULT_TIMEOUT"

    * Llamar a los objetos simulados

    * Eliminar atributos

    * Los nombres de los objetos simulados y el atributo *name*

    * Adjuntar objetos simulados como atributos

  * Parcheadores

    * patch

      * "patch()"

    * patch.object

      * "object()"

    * patch.dict

      * "dict()"

    * patch.multiple

      * "multiple()"

    * métodos start y stop de patch

      * "stopall()"

    * parchear objetos incorporados (builtins)

    * TEST_PREFIX

    * Anidando decoradores patch

    * Dónde parchear

    * Parcheando descriptores y objetos proxy

  * MagicMock y el soporte de métodos mágicos

    * Simular métodos mágicos

    * Magic Mock

      * "MagicMock"

      * "NonCallableMagicMock"

  * Ayudantes

    * sentinel

      * "sentinel"

    * DEFAULT

      * "DEFAULT"

    * call

      * "call()"

      * "call_list()"

    * create_autospec

      * "create_autospec()"

    * ANY

      * "ANY"

    * FILTER_DIR

      * "FILTER_DIR"

    * mock_open

      * "mock_open()"

    * Autoespecificación

    * Sellar objetos simulados

      * "seal()"

  * Order of precedence of "side_effect", "return_value" and *wraps*

* "unittest.mock" --- getting started

  * Usando mock

    * Métodos de parcheo mock

    * Mock de llamadas a métodos sobre un objeto

    * Clases de Mock

    * Nombrando tus mocks

    * Siguiendo todas las llamadas

    * Establecer valores de retorno y atributos

    * Generar excepciones con mocks

    * Funciones de efectos secundarios e iterables

    * Iteradores asincrónicos de Mocking

    * El gestor de contexto asincrónico de Mocking

    * Creando un mock desde un objeto existente

    * Uso de side_effect para devolver el contenido por archivo

  * Decoradores de Parches

  * Otros ejemplos

    * Mocking de llamadas encadenadas

    * Mocking parcial

    * Mocking de un método generador

    * Aplicar el mismo parche a cada método de prueba

    * Mocking de métodos sin enlazar

    * Comprobación de varias llamadas con mock

    * Copiando con argumentos mutables

    * Anidando parches

    * Mocking a un diccionario usando MagickMock

    * Mock de subclases y sus atributos

    * Importaciones de Mocking con patch.dict

    * Seguimiento del orden de las llamadas y de las aserciones de
      llamadas menos detalladas

    * Coincidencia de argumentos más compleja

* "test" --- Regression tests package for Python

  * Escritura de pruebas unitarias para el paquete "test"

  * Ejecución de pruebas utilizando la interfaz de línea de comandos

* "test.support" --- Utilidades para el conjunto de pruebas de Python

  * "TestFailed"

  * "ResourceDenied"

  * "verbose"

  * "is_jython"

  * "is_android"

  * "unix_shell"

  * "LOOPBACK_TIMEOUT"

  * "INTERNET_TIMEOUT"

  * "SHORT_TIMEOUT"

  * "LONG_TIMEOUT"

  * "PGO"

  * "PIPE_MAX_SIZE"

  * "Py_DEBUG"

  * "SOCK_MAX_SIZE"

  * "TEST_SUPPORT_DIR"

  * "TEST_HOME_DIR"

  * "TEST_DATA_DIR"

  * "MAX_Py_ssize_t"

  * "max_memuse"

  * "real_max_memuse"

  * "MISSING_C_DOCSTRINGS"

  * "HAVE_DOCSTRINGS"

  * "TEST_HTTP_URL"

  * "ALWAYS_EQ"

  * "NEVER_EQ"

  * "LARGEST"

  * "SMALLEST"

  * "busy_retry()"

  * "sleeping_retry()"

  * "is_resource_enabled()"

  * "python_is_optimized()"

  * "with_pymalloc()"

  * "requires()"

  * "sortdict()"

  * "findfile()"

  * "get_pagesize()"

  * "setswitchinterval()"

  * "check_impl_detail()"

  * "set_memlimit()"

  * "record_original_stdout()"

  * "get_original_stdout()"

  * "args_from_interpreter_flags()"

  * "optim_args_from_interpreter_flags()"

  * "captured_stdin()"

  * "captured_stdout()"

  * "captured_stderr()"

  * "disable_faulthandler()"

  * "gc_collect()"

  * "disable_gc()"

  * "swap_attr()"

  * "swap_item()"

  * "flush_std_streams()"

  * "print_warning()"

  * "wait_process()"

  * "calcobjsize()"

  * "calcvobjsize()"

  * "checksizeof()"

  * "anticipate_failure()"

  * "system_must_validate_cert()"

  * "run_with_locale()"

  * "run_with_tz()"

  * "requires_freebsd_version()"

  * "requires_linux_version()"

  * "requires_mac_version()"

  * "requires_gil_enabled()"

  * "requires_IEEE_754()"

  * "requires_zlib()"

  * "requires_gzip()"

  * "requires_bz2()"

  * "requires_lzma()"

  * "requires_resource()"

  * "requires_docstrings()"

  * "requires_limited_api()"

  * "cpython_only()"

  * "impl_detail()"

  * "no_tracing()"

  * "refcount_test()"

  * "bigmemtest()"

  * "bigaddrspacetest()"

  * "check_syntax_error()"

  * "open_urlresource()"

  * "reap_children()"

  * "get_attribute()"

  * "catch_unraisable_exception()"

  * "load_package_tests()"

  * "detect_api_mismatch()"

  * "patch()"

  * "run_in_subinterp()"

  * "check_free_after_iterating()"

  * "missing_compiler_executable()"

  * "check__all__()"

  * "skip_if_broken_multiprocessing_synchronize()"

  * "check_disallow_instantiation()"

  * "adjust_int_max_str_digits()"

  * "SuppressCrashReport"

  * "SaveSignals"

    * "save()"

    * "restore()"

  * "Matcher"

    * "matches()"

    * "match_value()"

* "test.support.socket_helper" --- Utilidades para pruebas de socket

  * "IPV6_ENABLED"

  * "find_unused_port()"

  * "bind_port()"

  * "bind_unix_socket()"

  * "skip_unless_bind_unix_socket()"

  * "transient_internet()"

* "test.support.script_helper" ---Utilidades para las pruebas de
  ejecución de Python

  * "interpreter_requires_environment()"

  * "run_python_until_end()"

  * "assert_python_ok()"

  * "assert_python_failure()"

  * "spawn_python()"

  * "kill_python()"

  * "make_script()"

  * "make_zip_script()"

  * "make_pkg()"

  * "make_zip_pkg()"

* "test.support.bytecode_helper" --- Herramientas de apoyo para
  comprobar la correcta generación de bytecode

  * "BytecodeTestCase"

  * "get_disassembly_as_string()"

  * "assertInBytecode()"

  * "assertNotInBytecode()"

* "test.support.threading_helper" --- Utilidades para pruebas con
  hilos

  * "join_thread()"

  * "reap_threads()"

  * "start_threads()"

  * "threading_cleanup()"

  * "threading_setup()"

  * "wait_threads_exit()"

  * "catch_threading_exception()"

* "test.support.os_helper" --- Utilidades para pruebas de sistemas
  operativos

  * "FS_NONASCII"

  * "SAVEDCWD"

  * "TESTFN"

  * "TESTFN_NONASCII"

  * "TESTFN_UNENCODABLE"

  * "TESTFN_UNDECODABLE"

  * "TESTFN_UNICODE"

  * "EnvironmentVarGuard"

  * "FakePath"

  * "set()"

  * "unset()"

  * "can_symlink()"

  * "can_xattr()"

  * "change_cwd()"

  * "create_empty_file()"

  * "fd_count()"

  * "fs_is_case_insensitive()"

  * "make_bad_fd()"

  * "rmdir()"

  * "rmtree()"

  * "skip_unless_symlink()"

  * "skip_unless_xattr()"

  * "temp_cwd()"

  * "temp_dir()"

  * "temp_umask()"

  * "unlink()"

* "test.support.import_helper" --- Utilidades para pruebas de
  importación

  * "forget()"

  * "import_fresh_module()"

  * "import_module()"

  * "modules_setup()"

  * "modules_cleanup()"

  * "unload()"

  * "make_legacy_pyc()"

  * "CleanImport"

  * "DirsOnSysPath"

* "test.support.warnings_helper" --- Utilidades para pruebas de
  advertencias

  * "ignore_warnings()"

  * "check_no_resource_warning()"

  * "check_syntax_warning()"

  * "check_warnings()"

  * "WarningsRecorder"
