Juan-Carlos Gandhi (
juan_gandhi) wrote2020-08-23 09:18 pm
![[personal profile]](https://www.dreamwidth.org/img/silk/identity/user.png)
Entry tags:
TWIMC: tests using random and current time
So, if you think you call a function in your code, and this function returns current time, or a random number... IT'S NOT A FUNCTION. Your code is function of "random number", or "time".
So, if your code is written as something that retrieves this kind of data, to test your code, you should provide that data. Not just today, but try the time, like 10 years from now. As to "random", You provide the randomness. If your code cannot be fixed to behave as a function of those inputs, make your "random stream" or "time stream" not hard-coded, but substitutable. Mockable. And mock it in your tests. MAKE SURE that you don't provide just happy-path data. Provide anything. A sequence of 100 numbers 4 for random. Time that is 10 years from now. Or even 30 yeas from now.
Make sure that your tests don't depend on anything. Because test Must Be Reproducible.
All these things, I know, are obvious to some, and not obvious to others.
So, if your code is written as something that retrieves this kind of data, to test your code, you should provide that data. Not just today, but try the time, like 10 years from now. As to "random", You provide the randomness. If your code cannot be fixed to behave as a function of those inputs, make your "random stream" or "time stream" not hard-coded, but substitutable. Mockable. And mock it in your tests. MAKE SURE that you don't provide just happy-path data. Provide anything. A sequence of 100 numbers 4 for random. Time that is 10 years from now. Or even 30 yeas from now.
Make sure that your tests don't depend on anything. Because test Must Be Reproducible.
All these things, I know, are obvious to some, and not obvious to others.
If you still have questions, ask. But don't argue. Because what I say is math. Unless you have another math (some people do), or another logic (there's plenty of them), please don't argue.
I'd be glad to see how all this changes if logic is e.g. linear.
Re: Multiple separate places to modify code
Re: Multiple separate places to modify code
Иногда нужно. Но далеко не всегда.
Например, если у нас есть длинный словарь, и новые требования нуждаются в расширении этого словаря -- из этого совсем не следует, что тесты тоже нужно при этом расширять.
Re: Multiple separate places to modify code
Re: Multiple separate places to modify code
Я согласен, что необходимость менять код в нескольких местах при изменении одного требования -- это далеко не самое страшное, что случается при поддержке кода.
Но, все же, довольно неприятно.
Потому что можно же одно из мест упустить из виду. Тесты, обычно, помогают самодиагностироваться, но не всегда.
Re: Multiple separate places to modify code
Потому что можно же одно из мест упустить из виду. Тесты, обычно, помогают самодиагностироваться, но не всегда.
Я не знаю, что конкретно имеется в виду, но тесты, наверное, нужно писать так, чтобы они помогали самодиагностироваться всегда.
Re: Multiple separate places to modify code
Да, бывает и так.
> тесты, наверное, нужно писать так, чтобы они помогали самодиагностироваться всегда
Это невозможно.
Тем более, что самодиагностика - это лишь второстепенная цель тестов.
Основная цель тестов - диагностировать production code.
Re: Multiple separate places to modify code
Tests self-diagnostic
~~~
static int Return1() {return 1;}
~~~
If in test we incorrectly write:
-----
Assert.AreEqual(2, Return1())
-----
then this test will complain (fail). That complain will force developer to investigate and find out that test (but not production code) contained error.
So that ability of test to [sometimes] find problems in its own code -- I call "self-diagnostic".
Does it make sense?
Re: Tests self-diagnostic
Re: Tests self-diagnostic
Вы так пишете, как будто считаете способность тестов к самодиагностике - проблемой.
Способность тестов к самодиагностике - не проблема, а достоинство.
Проблема заключается в том, что тесты могут далеко не все свои ошибки самодиагностировать.
Например в этом случае:
~~~
static int Return1() {return 2;}
~~~
этот тест:
-----
Assert.AreEqual(2, Return1())
-----
Не в состоянии выявить проблему (passes).
Re: Tests self-diagnostic
В чем тут проблема, если не секрет?
Re: Tests self-diagnostic
Но и в имплементации и в тестовом коде - ошибки.
Re: Tests self-diagnostic
Не отражено. Мало ли что люди имеют в виду. Первый Возврат, и чо?
Re: Tests self-diagnostic
Отражено.
Я - автор этого метода.
Я знаю, что именно я вложил в имя этого метода, когда назвал его "Return1".
> Первый Возврат, и чо?
"Первый Возврат" - это твоя некорректная интерпретация имени.
Из этого может следовать, что этот метод желательно переименовать (чтобы уменьшить вероятность некорректной интерпретации в будущем).
Но ошибка в тесте от переименования метода не исчезнет, потому что метод, в соответствии с бизнес требованиями - все равно должен возвращать 1.
Re: Tests self-diagnostic
К счастью мне такие случаи не встречались на практике, так что я полагаю их вероятность минимальной.
Re: Tests self-diagnostic
Re: Tests self-diagnostic
Re: Tests self-diagnostic
Re: Tests self-diagnostic
Re: Tests self-diagnostic
Say:
the bug in the intention is not very easy to see. (And, by the way, is_odd(2) produces 100% code coverage, which says something about that metric).
Re: Tests self-diagnostic
Разве ? По-моему, это больше похоже на "чётное количество ошибок".