juan_gandhi: (Default)
[personal profile] juan_gandhi
 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.

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. 

 

Date: 2020-08-24 05:07 am (UTC)
perdakot: (Default)
From: [personal profile] perdakot
Диск и сеть туда же.

Date: 2020-08-24 08:43 am (UTC)
From: [personal profile] a2is
Интерактивные тесты - туда же :)

Date: 2020-08-24 05:59 am (UTC)
From: [personal profile] mikkim08
У меня было такое задание на интервью. Написать довольно простой вебсервис, который зависит от времени, и юнит-тест для него.

Date: 2020-08-24 09:09 am (UTC)
From: [personal profile] mikkim08
Да нет, мне в целом интервью понравилось :)) Мне дали лаптоп, чтобы на нём программировать, интервьюер сидел рядом и очень доброжелательно помогал. Типа, pair-programming.

Сначала мы быстро-быстро написали простенький сервис (ипользуя jetty), а потом писали тесты, для чего нужно было рефакторить код. При этом пришлось выковыривать из бизнес-логики системный таймер и явно передавать его извне. А потом для тестов этот таймер "замочить" (от слова mock).

Ушло на это всё немногим больше часа.

What to test in time-dependent function?

Date: 2020-08-24 06:01 pm (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
> потом писали тесты, для чего нужно было рефакторить код

Что именно вы тестировали, что требовало рефакторинг?

Re: What to test in time-dependent function?

Date: 2020-08-24 07:08 pm (UTC)
From: [personal profile] mikkim08
Я сейчас не помню точно, но вот например у Вас сервис, который на запрос "/hello" возвращает "Добрый вечер", "Добрый день", или "Доброе утро" в зависимости от своего местного времени.

И Вам нужно написать тест, который проверяет правильность ответа (что с 4:00 до 12:00 по местному времени сервис возвращает ""Доброе утро" и так далее).

Re: What to test in time-dependent function?

Date: 2020-08-24 08:01 pm (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
> Добрый вечер", "Добрый день", или "Доброе утро" в зависимости от своего местного времени.

В данном случае, достаточно extract deterministic метод:
static string TimeToGreeting(DateTime time) { ... }
и покрыть его тестами.
Зачем, в данном случае, mocks?

Re: What to test in time-dependent function?

Date: 2020-08-24 08:24 pm (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
Так если код написан неправильно и есть проблема с его тестированием, то ведь, обычно, оптимальный подход - refactor такой код до правильного состояния, верно?

"Should provide that data"?

Date: 2020-08-24 10:03 pm (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
If in many cases it is possible to separate nondeterministic function and test it separately, then in these cases your recommendation ["if your code is written as something that retrieves this kind of data, to test your code, you should provide that data"] is not correct, right?

Nondeterministic function

Date: 2020-08-24 11:34 pm (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
> There's no such thing as "nondeterministic function".

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-25 12:08 am (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
> "almighty god allah" finds over 7m records

~~~~~~~~
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 03:26 pm (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
Communication, not math.

Re: What to test in time-dependent function?

Date: 2020-08-24 08:33 pm (UTC)
From: [personal profile] mikkim08
В таком случае Вы протестируете только "TimeToGreeting", а не целый сервис, который по запросу возвращает приветствие.

Re: What to test in time-dependent function?

Date: 2020-08-24 08:41 pm (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
> Вы протестируете только "TimeToGreeting", а не целый сервис

Так целый сервис тоже тестировать. Но в целом тесте проверять только ту часть, которая не зависит от времени.

С моками, кстати, тесты тоже не полностью все покрывают.

Re: What to test in time-dependent function?

Date: 2020-08-24 08:49 pm (UTC)
From: [personal profile] mikkim08
Так целый сервис тоже тестировать. Но в целом тесте проверять только ту часть, которая не зависит от времени.

Так тоже можно, но упражение состояло в том, чтобы проверить весь сервис целиком для разных, зависящих от времени случаев. Тем более, что проверять весь сервис целиком для разных случаев надёжнее.
Edited Date: 2020-08-24 08:49 pm (UTC)

Re: What to test in time-dependent function?

Date: 2020-08-24 08:59 pm (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
> проверять весь сервис целиком для разных случаев надёжнее

Проверять весь сервис целиком (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)
From: [personal profile] mikkim08
Менее надежно может быть, например потому, что результат внутренней функции (TimeToGreeting()) может быть искажен в коде, который его вызывает.
Соответственно, 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)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
> примеры false positive evaluation result

Тест утверждает, что 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)
From: [personal profile] mikkim08
Тест утверждает, что Greeting формируется правильно.
А на самом деле, Greeting формируется неправильно (ошибка в TimeToGreeting()), но из-за дополнительного кода, в некоторых случаях общий результат в integration test - все равно правильный.


А мы не тестируем функцию TimeToGreeting. Нас интересует только сервис как таковой. Ведь пользователю неважно, что там внутри. Важно, чтобы сервис выдавал правильные ответы на запросы.

Re: What to test in time-dependent function?

Date: 2020-08-24 09:49 pm (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
> А мы не тестируем функцию TimeToGreeting.

Если мы не тестируем функцию 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)
From: [personal profile] mikkim08
1) Мы вполне можем сделать предположения об имплементации сервиса, упрощающие тестирование, тестируя при этом сервис целиком, а не тестируя функцию TimeToGreeting.

2) Почему дополнительные тесты помимо двух это too brittle tests ?

Re: What to test in time-dependent function?

Date: 2020-08-24 10:10 pm (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
> Мы вполне можем сделать предположения об имплементации сервиса

Можем.
Но такие предположения "о структуре сервиса в целом" - гораздо менее надежные, чем предположения по структуре TimeToGreeting.
Даже если наше предположение о структуре сервиса в целом - верно на данный момент, может быть довольно сложно предсказать как верность нашего предположения будет сохраняться в будущем при модификациях нашего сервиса.

> Почему дополнительные тесты помимо двух это too brittle tests ?

Например потому, что при изменении списка возвращаемых значений, наши тесты, которые опираются на эти значения - тоже придется менять.

Re: What to test in time-dependent function?

Date: 2020-08-24 10:44 pm (UTC)
From: [personal profile] mikkim08
Но такие предположения "о структуре сервиса в целом" - гораздо менее надежные, чем предположения по структуре TimeToGreeting.

Отнюдь. Весь сервис ненамного сложнее TimeToGreeting.

Например потому, что при изменении списка возвращаемых значений, наши тесты, которые опираются на эти значения - тоже придется менять.

Мне это не кажется большим недостатком. Особенно в сравнении с тем, что зато мы покрываем тестами весь сервис.
Edited Date: 2020-08-24 10:46 pm (UTC)

Re: What to test in time-dependent function?

Date: 2020-08-24 11:22 pm (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
> Весь сервис ненамного сложнее TimeToGreeting.

Если весь сервис - ненамного сложнее, то и предположения о структуре делать не намного сложнее.
Но, все равно, сложнее.
И есть еще риск того, что сервис станет сложнее в будущем.

> Мне это не кажется большим недостатком.

Необходимость изменять данные в двух местах - отнимает дополнительное время и создает существенные проблемы.

> зато мы покрываем тестами весь сервис

Так ведь не покрываем весь сервис.
Потому что мы тестируем mocks, а не полный оригинальный сервис.

Re: What to test in time-dependent function?

Date: 2020-08-25 05:30 am (UTC)
From: [personal profile] mikkim08
И есть еще риск того, что сервис станет сложнее в будущем.

То же самое можно сказать и о функции TimeToGreeting.

Необходимость изменять данные в двух местах - отнимает дополнительное время и создает существенные проблемы.

В двух местах это в смысле и в имплементации сервиса, и в тестах для него ?

Так ведь не покрываем весь сервис. Потому что мы тестируем mocks, а не полный оригинальный сервис.

Это Ваше предположение, но мы этого пока не знаем, т.к. ещё не обсуждали, как имплементировать сервис и mocks.
Edited Date: 2020-08-25 06:19 am (UTC)

Re: What to test in time-dependent function?

Date: 2020-08-25 03:31 pm (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
>> риск того, что сервис станет сложнее в будущем.

> То же самое можно сказать и о функции TimeToGreeting.

Да, но риск от усложнения функции TimeToGreeting, которая напрямую покрыта юнит тестами -- меньше. Потому что:
1) Меньше потенциального шума между тестами и функцией TimeToGreeting.
2) Наличие тестов у функции TimeToGreeting более очевидно.
3) Принадлежность тестов к функции TimeToGreeting - более очевидна.

Re: What to test in time-dependent function?

Date: 2020-08-25 03:36 pm (UTC)
From: [personal profile] mikkim08
Тогда, наверное, нужно стремиться к тому, чтобы риск от усложнения всего сервиса был не больше чем риск от усложнения функции TimeToGreeting. Я думаю, это можно сделать.

Re: What to test in time-dependent function?

Date: 2020-08-25 03:48 pm (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
> нужно стремиться к тому, чтобы риск от усложнения всего сервиса был не больше чем риск от усложнения функции TimeToGreeting.

Это какая-то странная цель.

Если я очень сильно увеличу риск от усложнения функции TimeToGreeting, то ваша цель вполне может быть достигнута, верно?
Но непонятно, зачем нужно достигать такую странную цель.

Re: What to test in time-dependent function?

Date: 2020-08-25 08:09 pm (UTC)
From: [personal profile] mikkim08
Конечно, хотелось бы снизить риск от усложнения сервиса, а не увеличить риск от усложнения функции TimeToGreeting.

Multiple separate places to modify code

Date: 2020-08-25 03:36 pm (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
>> Необходимость изменять данные в двух местах - отнимает дополнительное время и создает существенные проблемы.

> В двух местах это в смысле и в имплементации сервиса, и в тестах для него ?

Да.
Не так уж и важно что это за два места. Проблематично, что таких мест - больше одного.

Re: Multiple separate places to modify code

Date: 2020-08-25 03:38 pm (UTC)
From: [personal profile] mikkim08
Мне кажется это естественным. Если меняются требования, то нужно переделывать и тесты, и сам сервис.

Re: Multiple separate places to modify code

Date: 2020-08-25 03:50 pm (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
> Если меняются требования, то нужно переделывать и тесты, и сам сервис.

Иногда нужно. Но далеко не всегда.
Например, если у нас есть длинный словарь, и новые требования нуждаются в расширении этого словаря -- из этого совсем не следует, что тесты тоже нужно при этом расширять.

Re: Multiple separate places to modify code

Date: 2020-08-25 08:12 pm (UTC)
From: [personal profile] mikkim08
Бывает, конечно, по-разному, и "хрупкие" тесты, которые нужно всё время переделывать, я тоже не люблю, но в целом тот факт, что при изменении требований нужно переделывать и сервис, и тесты, меня не очень заботит.

Re: Multiple separate places to modify code

Date: 2020-08-25 08:21 pm (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
> что при изменении требований нужно переделывать и сервис, и тесты, меня не очень заботит.

Я согласен, что необходимость менять код в нескольких местах при изменении одного требования -- это далеко не самое страшное, что случается при поддержке кода.
Но, все же, довольно неприятно.
Потому что можно же одно из мест упустить из виду. Тесты, обычно, помогают самодиагностироваться, но не всегда.

Re: Multiple separate places to modify code

Date: 2020-08-26 08:02 pm (UTC)
From: [personal profile] mikkim08
Видимо, тут имеет место компромисс между количеством тестов и накладными расходами на их поддержку. Выбор тут, наверное, зависит от многих разных факторов, в том числе субъективных. Но я могу себе представить ситуации, когда лучше написать побольше тестов несмотря на затраты по их сопровождению чем наоборот.

Потому что можно же одно из мест упустить из виду. Тесты, обычно, помогают самодиагностироваться, но не всегда.

Я не знаю, что конкретно имеется в виду, но тесты, наверное, нужно писать так, чтобы они помогали самодиагностироваться всегда.

Re: Multiple separate places to modify code

Date: 2020-08-26 08:09 pm (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
> могу себе представить ситуации, когда лучше написать побольше тестов несмотря на затраты по их сопровождению

Да, бывает и так.

> тесты, наверное, нужно писать так, чтобы они помогали самодиагностироваться всегда

Это невозможно.
Тем более, что самодиагностика - это лишь второстепенная цель тестов.
Основная цель тестов - диагностировать production code.

Re: Multiple separate places to modify code

Date: 2020-08-26 08:12 pm (UTC)
From: [personal profile] mikkim08
Возможно, я не понял, что значит самодиагностика и для чего она. Можете привести пример ?

Tests self-diagnostic

Date: 2020-08-26 08:20 pm (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
Let's imagine we have production method
~~~
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

Date: 2020-08-27 08:11 pm (UTC)
From: [personal profile] mikkim08
Да, такое может быть. Но эти ошибки исправляются в процессе написания этих тестов, так что в релизе их не будет.

Re: Tests self-diagnostic

Date: 2020-08-27 11:35 pm (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
> Но эти ошибки исправляются

Вы так пишете, как будто считаете способность тестов к самодиагностике - проблемой.
Способность тестов к самодиагностике - не проблема, а достоинство.
Проблема заключается в том, что тесты могут далеко не все свои ошибки самодиагностировать.
Например в этом случае:
~~~
static int Return1() {return 2;}
~~~

этот тест:
-----
Assert.AreEqual(2, Return1())
-----
Не в состоянии выявить проблему (passes).

Re: Tests self-diagnostic

Date: 2020-08-28 12:19 am (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
Проблема в том, что, с точки зрения бизнес требований, нужно чтобы результат был 1 (это требование отражено в названии метода Return1()).
Но и в имплементации и в тестовом коде - ошибки.

Re: Tests self-diagnostic

Date: 2020-08-28 08:48 am (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
> Не отражено.

Отражено.
Я - автор этого метода.
Я знаю, что именно я вложил в имя этого метода, когда назвал его "Return1".


> Первый Возврат, и чо?

"Первый Возврат" - это твоя некорректная интерпретация имени.
Из этого может следовать, что этот метод желательно переименовать (чтобы уменьшить вероятность некорректной интерпретации в будущем).
Но ошибка в тесте от переименования метода не исчезнет, потому что метод, в соответствии с бизнес требованиями - все равно должен возвращать 1.

Re: Tests self-diagnostic

Date: 2020-08-28 07:57 pm (UTC)
From: [personal profile] mikkim08
Возможно, я тогда ошибся. Теперь я понял, что имеется в виду.
К счастью мне такие случаи не встречались на практике, так что я полагаю их вероятность минимальной.

Re: Tests self-diagnostic

Date: 2020-08-29 12:52 am (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
Вы имеете ввиду, что вам не встречались тесты, которые successfully pass, а production код, при этом, работает неправильно?

Re: Tests self-diagnostic

Date: 2020-08-29 08:33 pm (UTC)
From: [personal profile] mikkim08
Да, такого типа не встречались.

Re: Tests self-diagnostic

Date: 2020-08-29 09:52 pm (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
"Такого типа" - это какого?

Re: Tests self-diagnostic

Date: 2020-08-30 05:12 pm (UTC)
From: [personal profile] mikkim08
Чтобы была ошибка в production коде и компенсирующая её ошибка в тесте.

Re: Tests self-diagnostic

Date: 2020-08-29 08:12 am (UTC)
From: [personal profile] sassa_nf
It's a bug in the specification. It happens sometimes. But the tests only test the correspondence between the test and the code, not between the code and the intention.

Say:
fn is_even(x: u32) -> bool {
   is_odd(x + 1)
}

fn is_odd(x: u32) -> bool {
   x != 0 && is_even(x + 1)
}
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

Date: 2020-08-29 08:35 pm (UTC)
From: [personal profile] mikkim08
It's a bug in the specification.

Разве ? По-моему, это больше похоже на "чётное количество ошибок".
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
> ещё не обсуждали, как имплементировать сервис и mocks.

Если при тестировании с помощью mocks, в тестах приходится делать какие-то дополнительные операции, которые не делаются в production code, то такое тестирование с помощью mocks -- не покрывает весь сервис.
В частности, не покрыта та часть, которая делает то же, что делают тесты, манипулируя mocks.
From: [personal profile] mikkim08
Тут я уже запутался. В особенности из-за последней фразы.
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
Mock тестирование - не просто передает параметры в тестируемую функцию, но и делает дополнительные операции (обычно устанавливает значения некоторых properties у mock объекта), верно?

Аналоги этих дополнительных операций -- выполняются и при регулярном выполнении production code, верно?

Так вот эти аналоги (части production code) -- не покрыты mock тестами.
То есть покрытие неполное.
From: [personal profile] mikkim08
Я не вполне согласен.

Представьте, что в код, который исполняет new DateTime(), передаёся какой-нибудь DateTimeCreator с методом newDateTime(), и все вызовы new DateTime() меняются на вызовы newDateTime().

Теперь в production мы передаём одну имплементацию DateTimeCreator, а в тестах -- другую (я называю её, возможно ошибочно, mock). Я не вижу тут неполного покрытия.
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
У вас получилось хорошее описание примера использования mock.

> в production мы передаём одну имплементацию DateTimeCreator,

Так вот эта "production" имплементация -- и не тестируется.
И процесс передачи этой "production" имплементации -- тоже не тестируется.

Это и делает тестовое покрытие с помощью mocks - неполным.
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
Если ты разобрался, то почему ты не можешь указать на мою ошибку?

А если ты не разобрался, то откуда ты знаешь, что это ахинея (а не твое упущение)?
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
Вместо того, чтобы попытаться добиться взаимопонимания в частном случае (что проще), ты выдал обобщенное утверждение (кстати, неверное), которое не отвечает на мой вопрос.

Зачем ты это сделал?
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
> Зачем я комментирую ахинею, что ты несешь?

Нет.

Зачем ты высказал утверждение, не относящееся к вопросу, который я задал?

> Чисто из зрительного зала.

Ты имеешь ввиду, что прикольно иногда покричать какие-нибудь глупости из зрительного зала?

> Для взаимопонимания нужно понимание,

Да.

> а у тебя полный швах с этим делом.

Из каких признаков ты сделал такой вывод?

Признаки непонимания

Date: 2020-08-26 11:37 pm (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
Ты в состоянии пошагово объяснить как из того, что я написал следует, что у меня "швах" с пониманием?

Давай я тебе дам пару примеров признаков непонимания:
1) Когда ты на мой вопрос отвечаешь нерелеватным утверждением -- это признак твоего непонимания.
2) Когда на мой вопрос с запросом более детального объяснения ты повторяешь недоказанное утверждение -- это признак твоего непонимания.

Re: Признаки непонимания

Date: 2020-08-27 04:56 pm (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
Кому ты можешь объяснить, как из того, что я написал следует, что у меня "швах" с пониманием?

Re: Признаки непонимания

Date: 2020-08-27 11:29 pm (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
Так объясни "половине собравшихся".

Пока что ты никому не объяснил вообще.
Выглядит как "У нас есть ТАКИЕ приборы! Но мы вам о них не расскажем."

Re: Признаки непонимания

Date: 2020-08-28 12:21 am (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
Откуда ты знаешь, что "они" и так в курсе?

Пока что этому нет никаких подтверждений.

Re: Признаки непонимания

Date: 2020-08-28 08:30 am (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
Потому что "они" не знают, какие именно обоснования ты придумал своей выдумке.
From: [personal profile] mikkim08
DateTimeCreator можно тоже покрыть тестами.
Процесс его передачи, наверное, тоже.
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
> DateTimeCreator можно тоже покрыть тестами.

Если можно покрыть тестами DateTimeCreator, то зачем нужен Mock, подменяющий DateTimeCreator?

> Процесс его передачи, наверное, тоже.

Можно. В полноценном integration тесте, который не использует Mock.
From: [personal profile] mikkim08
Если можно покрыть тестами DateTimeCreator, то зачем нужен Mock, подменяющий DateTimeCreator?

Чтобы можно было протестировать наш сервис для разных DateTime.

Можно. В полноценном integration тесте, который не использует Mock.

И в тесте, который использует мок тоже, потому что процессы передачи настоящего "DateTimeCreator" и его мока -- одинаковые.
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
>> Если можно покрыть тестами DateTimeCreator, то зачем нужен Mock, подменяющий DateTimeCreator?

> Чтобы можно было протестировать наш сервис для разных DateTime.

Вы имеете ввиду, что покрыть тестами DateTimeCreator можно, но не для всех значений?
И что Mocks - позволяют тщательно протестировать остальную часть сервиса (а DateTimeCreator будет протестирован лишь для некоторых значений)?

> И в тесте, который использует мок тоже, потому что процессы передачи настоящего "DateTimeCreator" и его мока -- одинаковые.

Нет.
Mock не дает полноценного тестирования в данном случае.
"Передача DateTimeCreator" - состоит из двух частей:
Часть №1: Посылка DateTimeCreator.
Часть №2: Получение DateTimeCreator.

Часть №2 - одна и та же и в тесте с моками и в production коде. Поэтому тестирование покрывает production код.

Но, увы, Часть №1 - разная в коде тестов с моками и в production коде. Поэтому тестирование с моками не покрывает эту Часть №1 ("Посылка DateTimeCreator").

Эту проблему (с отсутствием покрытия "посылки DateTimeCreator" можно продемонстрировать следующим образом:
1) Написать production код.
2) Написать mock test (который successfully passes).
3) Модифицировать ту часть production кода, которая передает DateTimeCreator (чтобы она передавала неправильную функцию).
Mock test, при этом, увы, будет продолжать демонстрировать success (fake success).
From: [personal profile] mikkim08
Ага, теперь я, кажется, понял.
Да, при тестировании с моком одна часть рабочего кода не покрывается.
Но её вроде можно покрыть, добавив тест с настоящим DateTimeCreator.
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
Если тест должен явным образом добавлять работу с настоящим DateTimeCreator, то полного покрытия не получится.

Но если работа с настоящим DateTimeCreator - имплементирована в моке по умолчанию - тогда, действительно, может получиться покрыть рабочий код тестами полностью.
From: [personal profile] mikkim08
Не могу согласиться. Сервис может включать настоящий DateTimeCreator по умолчанию.
И мы можем протестировать его в таком виде.
А для тестов, которые требуют DateTimeCreator mock, мы втыкаем этот mock в наш сервис вместо настоящего DateTimeCreator-а.
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
> Сервис может включать настоящий DateTimeCreator по умолчанию.
> И мы можем протестировать его в таком виде.

Я именно это и имел ввиду, когда написал "Но если работа с настоящим DateTimeCreator - имплементирована в моке по умолчанию - тогда, действительно, может получиться покрыть рабочий код тестами полностью."

Похоже, разница между нашими утверждениями лишь в том, что вы называете "моком" лишь изменяемую часть, а я называю "моком" весь класс, который включает в себя изменяемую часть.
From: [personal profile] mikkim08
Похоже, разница между нашими утверждениями лишь в том, что вы называете "моком" лишь изменяемую часть, а я называю "моком" весь класс, который включает в себя изменяемую часть.

Да, похоже на то. А как правильно ?

"Mock" и "mocking" in programming

Date: 2020-08-31 12:18 pm (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
Я не знаю, как правильно. Вероятно так, как обсуждающие договорятся на момент дискуссии.

Термины "mock" и "mocking" в программировании - несколько неустоявшиеся.

Первые две web pages в списке https://www.google.com/search?q=mock+programming - довольно запутанные:
1) https://en.wikipedia.org/wiki/Mock_object
2) https://stackoverflow.com/questions/2665812/what-is-mocking

Обычно, и Wikipedia и Stackoverflow четко и ясно описывают концепцию, которой они посвящены, но в случае с "mock" и "mocking" - даже в 2020-м году остается довольно путаницы и упущений.

Re: "Mock" и "mocking" in programming

Date: 2020-08-31 08:06 pm (UTC)
From: [personal profile] mikkim08
Я пока не занимался этим вопросом, но надеюсь найти хорошее определение.
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
> Сервис может включать настоящий DateTimeCreator по умолчанию.
> И мы можем протестировать его в таком виде.

Обратите внимание, что обратное - тоже верно: если сервис не включает в себя настоящий DateTimeCreator по умолчанию, то полный test coverage такого кода - невозможен.

Что приводит нас к "best practice" рекомендации о том, как имплементировать моки:
Для того, чтобы повысить test coverage, имплементация мока для рабочего кода - должна быть включена по умолчанию в сервис (чтобы рабочий код, вызывающий этот сервис, не должен был заморачиваться explicit инициализацией mock).

Это, пожалуй, основной вывод из нашей с вами дискуссии о моках.
From: [personal profile] mikkim08
Это, пожалуй, основной вывод из нашей с вами дискуссии о моках.

Да, можно сделать такой вывод.
From: [personal profile] mikkim08
Да вроде нет, пока держусь.

Date: 2020-08-24 06:50 am (UTC)
spamsink: (Default)
From: [personal profile] spamsink
Or even 30 yeas from now.

Remember, remember the 19th of January 2038.

Date: 2020-08-24 08:10 am (UTC)
From: [personal profile] sassa_nf
> A sequence of 100 numbers 4 for random.

I am not sure I understand what one could do about it. How do you defend against this? Write a piece of code for validating the randoms provided are sufficiently random?

It makes more sense to write tests supposing the entropy is depleted. (and the rng device blocks indefinitely)

Date: 2020-08-24 04:46 pm (UTC)
From: [personal profile] sassa_nf
I think I get your point now. We shouldn't mock the entire RNG, but we do need to keep track what seed was used for a given test, so you can re-run the test, if it is seen to fail.

Re: blocking indefinitely - I was thinking of /dev/random. We can deplete it, and we have seen what happens to the programs that don't think that's possible.

Date: 2020-08-24 08:28 am (UTC)
norian: (Default)
From: [personal profile] norian
рандомность в тестах часто обрабатывается записью какой-то достаточно длинной (для создания субъективной иллюзии) последовательности и канонического, прочеканого лапками, вывода, ну то есть регрешн

время есть область ответственности оси, прикладной софт не должно парить что где там переполнилось вообще

Date: 2020-08-24 02:45 pm (UTC)
norian: (Default)
From: [personal profile] norian
это когда пишецца простой логгер, который вкрячиваецца в реальный источнег рандомной цыфири и потом его изображает, ну и конечно можно добавить туда чего угодно лапгами при желании

How to test nondeterministic functions

Date: 2020-08-24 05:52 pm (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
> 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.

What you describe as "FUNCTION", is usually called "deterministic function".
~~~~~~~~~~
https://www.google.com/search?q=deterministic+function
Deterministic functions always return the same result any time they are called with a specific set of input values and given the same state of the database.
~~~~~~~~~~
Why did you chose using non-standard "function" label for "deterministic function" concept?

> So, if your code is written as something that retrieves this kind of data, to test your code, you should provide that data.

Not necessarily.
It depends on what exactly we are testing.
For example, if it is sufficient for us to test that nondeterministic function output contains specific phrase that does not depend on random input -- why should we provide random data to that test?

> Make sure that your tests don't depend on anything.

Test that does not depend on anything - does not test production code.
Do you use non-standard definition of word "anything" or phrase "don't depend"?

Edited Date: 2020-08-24 05:54 pm (UTC)

Re: How to test nondeterministic functions

Date: 2020-08-24 09:39 pm (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
What are the signs that these people are clueless about what function is?

"Idiots" sign

Date: 2020-08-24 11:24 pm (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
If I do not understand your answer -- this is a sign about you and me, not about other people.

Re: "Idiots" sign

Date: 2020-08-24 11:49 pm (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
> Whom here do you understand, name one.

I understand almost everyone, including you.
It is your [incorrect] opinion that I do not understand you.
But most of the time I do understand. I just do not always agree.
Or, sometimes, I misunderstand. But, most of the time, I understand correctly.
Edited Date: 2020-08-24 11:52 pm (UTC)

Sings of understanding

Date: 2020-08-25 03:24 pm (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
Why do you think that I do not understand almost everyone [who I choose to carefully read]?

Re: Sings of understanding

Date: 2020-08-25 05:13 pm (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
If there is no answer -- it is hard to understand it.

Still, lack of answer suggests: unwillingness to teach and unwillingness to expose your thoughts for external testing.

The book

Date: 2020-08-25 05:38 pm (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
> Buy my book

Why do you think your book will teach me what I need?

Re: The book

Date: 2020-08-25 06:47 pm (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
> It obviously won't.

Then why did you recommend to buy your book?
Edited Date: 2020-08-25 06:51 pm (UTC)

Re: The book

Date: 2020-08-25 07:17 pm (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
> For the case you change, with time.

It would make more sense to recommend your book after this hypothetical change will happen, not before that, right?

> Also, https://juan-gandhi.dreamwidth.org/4300834.html

I am not sure what to take from it.
My guess is that you are tired?

Re: How to test nondeterministic functions

Date: 2020-08-25 07:20 am (UTC)
From: [personal profile] sassa_nf
If you actually read what the search results are about, you would see it is about SQL specifically. It is no longer "usually". No one outside SQL community uses that term. Even the second best result - google corrected the term to "deterministic algorithm", because google knows people don't know what they are talking about, and what they really mean is algorithm.

Is "nondeterministic function" a useful concept

Date: 2020-08-25 04:01 pm (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
> No one outside SQL community uses that term.

Your observation is incorrect.

https://www.google.com/search?q=%22deterministic+function%22
About 451,000 results

https://www.google.com/search?q=%22deterministic+function%22+-sql
About 524,000 results

Google's search count estimates are a bit weird here, but the main point is that there are plenty of "deterministic function" results with the word "SQL" in it.

> Even the second best result - google corrected the term to "deterministic algorithm"

It looks like you forgot to add quotes around "deterministic algorithm" in your search.
From: [personal profile] sassa_nf
My observation is what I see. Your implication of what I should see has no relevance to the original statement.

But in the end if you understood the substance of what juan gandhi said, bickering about the term is pointless. And if you did not understand the substance, bickering about the term is shallow.
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
> bickering about the term is pointless

I am not "bickering". I have a very specific question.
Such as -- why use more ambiguous term "function" instead of more specific and very searchable "deterministic function"?
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
> Math uses terms.

True, but irrelevant to discussion about testing in programming.

> What people on the internets say, does not matter.

That is incorrect.
What people say on the internets -- matter, at least, to some degree.

> Your opinion, e.g., does not matter. My neither.

These are also incorrect statements.
Our opinions do matter.
From: [personal profile] sassa_nf
Having a specific question does not make it not bickering.

I would rather you answered whether you understood the substance of the post.

If I cared.
Edited Date: 2020-08-25 07:12 pm (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
> Having a specific question does not make it not bickering.

If that specific question help to clarify the opponent's position -- then it is not bickering.

> whether you understood the substance of the post

What post?
From: [personal profile] sassa_nf
The summary of this thread: you started with "you [OP] said X, but the correct thing to say is Y"; then you accused me of using wrong search and offered to do a different search (again a variation on "you said X, but the correct thing to say is Y"), whereas I only described what can be seen when clicking the search URL you posted; now you are weaseling some more shrugging the shoulders in bewilderment.

It doesn't look like you have anything of substance to say.

Usage of term "deterministic function"

Date: 2020-08-26 01:04 pm (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
> I only described what can be seen when clicking the search URL you posted

Are you implying that you did not write "No one outside SQL community uses that term."?
From: [personal profile] sassa_nf
I am not implying, I am plain telling you that you haven't even read what you've found - nevermind what I've found, or could have found.

But then who would expect an admission that yes, the term appears to be SQL-only and doesn't really cut it as a serious objection to the use of a certain well-established term. Diversion is so much easier to play.
Edited Date: 2020-08-26 01:23 pm (UTC)

Misunderstanding question

Date: 2020-08-26 02:48 pm (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
>> Are you implying that you did not write "No one outside SQL community uses that term."?

> I am not implying, I am plain telling you that you haven't even read what you've found

You did not really answer my question here.
I asked you about "No one outside SQL community uses that term" statement, not about me reading or finding something.

Did you misunderstand my question or did you pretend to misunderstand it?

> Diversion is so much easier to play.

Is that what you are doing? Diversion?

Re: "то есть" trick

Date: 2020-08-26 03:45 pm (UTC)
From: [personal profile] sassa_nf
> Did you ... or did you ...?

I am not inclined to answer your questions because you are not inclined to answer mine. Although by saying this I've just answered one of yours.

> Is that what you are doing?

This is a "то есть" trick of yours, so the best I can do is ignore.

Expecting answers to unasked questions

Date: 2020-08-26 06:09 pm (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
> I am not inclined to answer your questions

Yes.
That suggests that you are avoiding reaching clarity in our communication.

> because

That causality claim is wrong.

> you are not inclined to answer mine

This your hypothesis is wrong.
I am, actually, inclined to answer your questions, but you did not ask any questions [at least in the last 8 your replies to me].

Re: Expecting answers to unasked questions

Date: 2020-08-27 06:10 am (UTC)
From: [personal profile] sassa_nf
> I would rather you answered whether you understood the substance of the post.

Re: Expecting answers to unasked questions

Date: 2020-08-27 04:59 pm (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
Are you implying that it was your way of asking a question?

Re: "то есть" trick

Date: 2020-08-26 06:16 pm (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
>> Is that what you are doing?

> This is a "то есть" trick of yours

What is "то есть" trick?
How is that trick relevant to my question?

> the best I can do is ignore

Nope.
Not entering discussion in the first place -- is a much better for saving time.
Answering the question is the best for reaching clarity.
Entering discussion and then not answer clarifying questions that pop up in that discussion -- is, usually, a bad choice. I disrespect such behavior.
Edited Date: 2020-08-26 06:18 pm (UTC)

Infallible teacher

Date: 2020-08-24 05:57 pm (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
> But don't argue.

Because you are perfect and cannot make mistakes, right?

Re: Infallible teacher

Date: 2020-08-24 08:12 pm (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
> demonstrate your expertise

I demonstrated my expertise.
Unfortunately, today you are unwilling to comprehend it.

What kind of demonstration would convince you?
Edited Date: 2020-08-24 08:15 pm (UTC)

Re: Infallible teacher

Date: 2020-08-24 09:55 pm (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
> I see that it's bullshit.

If it is bullshit -- then there should be clear mistakes that are not too hard to identify.
But you are not identifying these mistakes.

> If you learned some math, or something, you would see it yourself.

1) I did learn some math.
2) I do not see how what I wrote is "bullshit".
3) Therefore your statement is incorrect.
4) Furthermore, unit tests are about programming and only tangentially about math.

Date: 2020-08-28 09:27 am (UTC)
From: [identity profile] http://users.livejournal.com/sorcerer-/
Мне не очень понятно почему оно не happy path?
Мне очевидно, что любое конечное количество моков - это happy path при бесконечном оригинале.
Ну и так же, что все, что придумает конкретный программист, - это тоже happy path, т.к. он уже это придумал, и значит предусмотрел в коде.
Я считаю, что тесты бывают только двух видов: integration - что реально видит наш юзер и regression - настоящий un-happy path из баг репортов. Все остальное - карго культ.

Profile

juan_gandhi: (Default)
Juan-Carlos Gandhi

June 2025

S M T W T F S
1 2345 6 7
8 9 10 11 121314
15161718192021
22232425262728
2930     

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Jun. 13th, 2025 01:25 pm
Powered by Dreamwidth Studios