python / python/cpython

unittest.mock spec and create_autospec should support type-hints

Aberta
#124,816 0 comentários 0 reações 0 responsáveis Ver no GitHub

Ninguém assumiu esta issue ainda.

type-feature
Linguagem predominante
Python
Estrelas
77.2k
Forks
36k
Métricas de merge de PRs
Métricas de PR pendentes

Descrição

Feature or enhancement

Proposal:

Current recommendation for spec=... and create_autospec is to set a default class value in case of attributes created within an instance's __init__():

Probably the best way of solving the problem is to add class attributes as default values for instance members initialised in __init__()

The problem is that like written, Nones are never useful and together with spec_set=True it just results in a regular mock that accepts everything.

That recommendation and method are unfortunately very old and they existed long before the type hinting system was so developed. I believe type hints can now be reliably used to infer the spec, at least in simple terms, and in the other cases the same behavior as None can be implemented.

from unittest.mock import create_autospec

class A:
  a: dict[str, int]
  b: Iterator[str]
  c: int | str | complex

mock = create_autospec(A)
mock().a  # should be supported, with a dict spec.
mock().b  # Iterator spec
mock().c  # Too complex... Any spec (just like current behavior for None)

It will lead into more accurate unit tests, and we can optionally hide the behavior behind a boolean such as infer_types=True.

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

No response

Guia de contribuição

Abrir o guia de contribuição

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Direção de pesquisa

Comece rastreando os pontos de entrada de unittest.mock e create_autospec, incluindo como spec_set=True atualmente lida com atributos de instância inicializados em init. Defina o comportamento para dicas de tipo simples, uniões complexas e a flag opcional de inferência proposta; considera-se concluído quando as anotações solicitadas produzem specs apropriadas sem alterar o comportamento de fallback para casos não suportados.

Escrita pelo modelo de indexação a partir do texto da issue.

Avaliação

Stack de tecnologia
python
Domínio
testing-qa
Tipo de issue
Funcionalidade
Dificuldade
5/5
Tempo estimado
Mais de uma semana
Status de atividade
Estagnada
Clareza
Razoavelmente clara
Facilidade para iniciantes
35/100

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.