![[personal profile]](https://www.dreamwidth.org/img/silk/identity/user.png)
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: What to test in time-dependent function?
Date: 2020-08-24 07:08 pm (UTC)И Вам нужно написать тест, который проверяет правильность ответа (что с 4:00 до 12:00 по местному времени сервис возвращает ""Доброе утро" и так далее).
Re: What to test in time-dependent function?
Date: 2020-08-24 08:01 pm (UTC)В данном случае, достаточно extract deterministic метод:
static string TimeToGreeting(DateTime time) { ... }
и покрыть его тестами.
Зачем, в данном случае, mocks?
Re: What to test in time-dependent function?
Date: 2020-08-24 08:06 pm (UTC)Разумеется. Если такой, правильно написанный, код - то и проблемы нету!
Re: What to test in time-dependent function?
Date: 2020-08-24 08:24 pm (UTC)Re: What to test in time-dependent function?
Date: 2020-08-24 09:21 pm (UTC)В целом да; но не всегда получается.
"Should provide that data"?
Date: 2020-08-24 10:03 pm (UTC)Re: "Should provide that data"?
Date: 2020-08-24 10:45 pm (UTC)There's no such thing as "nondeterministic function".
Nondeterministic function
Date: 2020-08-24 11:34 pm (UTC)Do you mean that your personal lexicon does not contain "nondeterministic function" concept?
~~~~~~~
https://www.google.com/search?q=%22nondeterministic+function%22
About 6,000 results
~~~~~~~
Re: Nondeterministic function
Date: 2020-08-24 11:39 pm (UTC)"almighty god allah" finds over 7m records. And? It's also in my personal lexicon.
Re: Nondeterministic function
Date: 2020-08-25 12:08 am (UTC)~~~~~~~~
https://www.google.com/search?q=%22almighty+god+allah%22
About 292,000 results
~~~~~~~~
You used "almighty god allah" without quotes in your search query...
> It's also in my personal lexicon
So you understand what people want to express when they write "Nondeterministic function"?
Then why do you refuse to use "Nondeterministic function" term to communicate that concept -- in order to clearly communicate your message?
"Nondeterministic function" is less ambiguous than "function".
Re: Nondeterministic function
Date: 2020-08-25 01:22 am (UTC)You seem to be seriously determined to teach me math.
Re: Nondeterministic function
Date: 2020-08-25 03:26 pm (UTC)Re: What to test in time-dependent function?
Date: 2020-08-24 08:33 pm (UTC)Re: What to test in time-dependent function?
Date: 2020-08-24 08:41 pm (UTC)Так целый сервис тоже тестировать. Но в целом тесте проверять только ту часть, которая не зависит от времени.
С моками, кстати, тесты тоже не полностью все покрывают.
Re: What to test in time-dependent function?
Date: 2020-08-24 08:49 pm (UTC)Так тоже можно, но упражение состояло в том, чтобы проверить весь сервис целиком для разных, зависящих от времени случаев. Тем более, что проверять весь сервис целиком для разных случаев надёжнее.
Re: What to test in time-dependent function?
Date: 2020-08-24 08:59 pm (UTC)Проверять весь сервис целиком (integration test) - может быть надежнее.
А может быть и менее надежно.
Менее надежно может быть, например потому, что результат внутренней функции (TimeToGreeting()) может быть искажен в коде, который его вызывает.
Соответственно, integration test может начать выдавать либо false positive evaluation result, либо false negative evaluation result.
Re: What to test in time-dependent function?
Date: 2020-08-24 09:06 pm (UTC)Соответственно, integration test может начать выдавать либо false positive evaluation result, либо false negative evaluation result.
Здесь я Вас не понял. Можно примеры false positive evaluation result или false negative evaluation result ?
Re: What to test in time-dependent function?
Date: 2020-08-24 09:28 pm (UTC)Тест утверждает, что Greeting формируется правильно.
А на самом деле, Greeting формируется неправильно (ошибка в TimeToGreeting()), но из-за дополнительного кода, в некоторых случаях общий результат в integration test - все равно правильный.
> или false negative evaluation result
Тест утверждает, что результат неправильный.
А на самом деле, результат правильный.
Просто код, который вызывает TimeToGreeting() - отрезал кусок Greeting, потому что он оказался слишком длинным [и не входит в Tweet/Email subject/Whatever].
Re: What to test in time-dependent function?
Date: 2020-08-24 09:36 pm (UTC)А на самом деле, Greeting формируется неправильно (ошибка в TimeToGreeting()), но из-за дополнительного кода, в некоторых случаях общий результат в integration test - все равно правильный.
А мы не тестируем функцию TimeToGreeting. Нас интересует только сервис как таковой. Ведь пользователю неважно, что там внутри. Важно, чтобы сервис выдавал правильные ответы на запросы.
Re: What to test in time-dependent function?
Date: 2020-08-24 09:49 pm (UTC)Если мы не тестируем функцию TimeToGreeting, то мы не можем сделать некоторые предположения, упрощающие тестирование.
Например, если TimeToGreeting возвращает несколько сотен значений из предопределенного списка, то мы можем выбрать пару edge cases, протестировать их, и сделать предположение, что все остальные случаи тоже, с высокой вероятностью, работают.
Однако, если мы тестируем "только сервис как таковой", то предположение, что достаточно протестировать лишь пару edge cases -- вполне может оказаться неверным.
Что поставит нас в весьма затруднительное положение: оставлять only 2 test cases -- плохо, но и добавлять дополнительные test cases -- тоже плохо (too brittle tests).
Re: What to test in time-dependent function?
Date: 2020-08-24 10:01 pm (UTC)2) Почему дополнительные тесты помимо двух это too brittle tests ?
Re: What to test in time-dependent function?
Date: 2020-08-24 10:10 pm (UTC)Можем.
Но такие предположения "о структуре сервиса в целом" - гораздо менее надежные, чем предположения по структуре TimeToGreeting.
Даже если наше предположение о структуре сервиса в целом - верно на данный момент, может быть довольно сложно предсказать как верность нашего предположения будет сохраняться в будущем при модификациях нашего сервиса.
> Почему дополнительные тесты помимо двух это too brittle tests ?
Например потому, что при изменении списка возвращаемых значений, наши тесты, которые опираются на эти значения - тоже придется менять.
Re: What to test in time-dependent function?
Date: 2020-08-24 10:44 pm (UTC)Отнюдь. Весь сервис ненамного сложнее TimeToGreeting.
Например потому, что при изменении списка возвращаемых значений, наши тесты, которые опираются на эти значения - тоже придется менять.
Мне это не кажется большим недостатком. Особенно в сравнении с тем, что зато мы покрываем тестами весь сервис.
Re: What to test in time-dependent function?
Date: 2020-08-24 11:22 pm (UTC)Если весь сервис - ненамного сложнее, то и предположения о структуре делать не намного сложнее.
Но, все равно, сложнее.
И есть еще риск того, что сервис станет сложнее в будущем.
> Мне это не кажется большим недостатком.
Необходимость изменять данные в двух местах - отнимает дополнительное время и создает существенные проблемы.
> зато мы покрываем тестами весь сервис
Так ведь не покрываем весь сервис.
Потому что мы тестируем mocks, а не полный оригинальный сервис.
Re: What to test in time-dependent function?
Date: 2020-08-25 05:30 am (UTC)То же самое можно сказать и о функции TimeToGreeting.
Необходимость изменять данные в двух местах - отнимает дополнительное время и создает существенные проблемы.
В двух местах это в смысле и в имплементации сервиса, и в тестах для него ?
Так ведь не покрываем весь сервис. Потому что мы тестируем mocks, а не полный оригинальный сервис.
Это Ваше предположение, но мы этого пока не знаем, т.к. ещё не обсуждали, как имплементировать сервис и mocks.
Re: What to test in time-dependent function?
From:Re: What to test in time-dependent function?
From:Re: What to test in time-dependent function?
From:Re: What to test in time-dependent function?
From:Multiple separate places to modify code
From:Re: Multiple separate places to modify code
From:Re: Multiple separate places to modify code
From:Re: Multiple separate places to modify code
From:Re: Multiple separate places to modify code
From:Re: Multiple separate places to modify code
From:Re: Multiple separate places to modify code
From:Re: Multiple separate places to modify code
From:Tests self-diagnostic
From:Re: Tests self-diagnostic
From:Re: Tests self-diagnostic
From:Re: Tests self-diagnostic
From:Re: Tests self-diagnostic
From:Re: Tests self-diagnostic
From:Re: Tests self-diagnostic
From:Re: Tests self-diagnostic
From:Re: Tests self-diagnostic
From:Re: Tests self-diagnostic
From:Re: Tests self-diagnostic
From:Re: Tests self-diagnostic
From:Re: Tests self-diagnostic
From:Re: Tests self-diagnostic
From:Is full service test coverage possible with mocks?
From:Re: Is full service test coverage possible with mocks?
From:Re: Is full service test coverage possible with mocks?
From:Re: Is full service test coverage possible with mocks?
From:Re: Is full service test coverage possible with mocks?
From:Re: Is full service test coverage possible with mocks?
From:Re: Is full service test coverage possible with mocks?
From:Re: Is full service test coverage possible with mocks?
From:Re: Is full service test coverage possible with mocks?
From:Re: Is full service test coverage possible with mocks?
From:Re: Is full service test coverage possible with mocks?
From:Re: Is full service test coverage possible with mocks?
From:Re: Is full service test coverage possible with mocks?
From:Re: Is full service test coverage possible with mocks?
From:Признаки непонимания
From:Re: Признаки непонимания
From:Re: Признаки непонимания
From:Re: Признаки непонимания
From:Re: Признаки непонимания
From:Re: Признаки непонимания
From:Re: Признаки непонимания
From:Re: Признаки непонимания
From:Re: Признаки непонимания
From:Re: Is full service test coverage possible with mocks?
From:Re: Is full service test coverage possible with mocks?
From:Re: Is full service test coverage possible with mocks?
From:Re: Is full service test coverage possible with mocks?
From:Re: Is full service test coverage possible with mocks?
From:Re: Is full service test coverage possible with mocks?
From:Re: Is full service test coverage possible with mocks?
From:Re: Is full service test coverage possible with mocks?
From:Re: Is full service test coverage possible with mocks?
From:"Mock" и "mocking" in programming
From:Re: "Mock" и "mocking" in programming
From:Re: Is full service test coverage possible with mocks?
From:Re: Is full service test coverage possible with mocks?
From:Re: Is full service test coverage possible with mocks?
From:Re: Is full service test coverage possible with mocks?
From:Re: Is full service test coverage possible with mocks?
From: