![[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.
no subject
Date: 2020-08-24 05:07 am (UTC)no subject
Date: 2020-08-24 06:06 am (UTC)Вот; и это тоже.
no subject
Date: 2020-08-24 08:43 am (UTC)no subject
Date: 2020-08-24 05:59 am (UTC)no subject
Date: 2020-08-24 06:06 am (UTC)Ну это как-то довольно свирепо уже.
no subject
Date: 2020-08-24 09:09 am (UTC)Сначала мы быстро-быстро написали простенький сервис (ипользуя jetty), а потом писали тесты, для чего нужно было рефакторить код. При этом пришлось выковыривать из бизнес-логики системный таймер и явно передавать его извне. А потом для тестов этот таймер "замочить" (от слова mock).
Ушло на это всё немногим больше часа.
What to test in time-dependent function?
Date: 2020-08-24 06:01 pm (UTC)Что именно вы тестировали, что требовало рефакторинг?
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?
Date: 2020-08-25 03:31 pm (UTC)> То же самое можно сказать и о функции TimeToGreeting.
Да, но риск от усложнения функции TimeToGreeting, которая напрямую покрыта юнит тестами -- меньше. Потому что:
1) Меньше потенциального шума между тестами и функцией TimeToGreeting.
2) Наличие тестов у функции TimeToGreeting более очевидно.
3) Принадлежность тестов к функции TimeToGreeting - более очевидна.
Re: What to test in time-dependent function?
Date: 2020-08-25 03:36 pm (UTC)Re: What to test in time-dependent function?
Date: 2020-08-25 03:48 pm (UTC)Это какая-то странная цель.
Если я очень сильно увеличу риск от усложнения функции TimeToGreeting, то ваша цель вполне может быть достигнута, верно?
Но непонятно, зачем нужно достигать такую странную цель.
Re: What to test in time-dependent function?
Date: 2020-08-25 08:09 pm (UTC)Multiple separate places to modify code
Date: 2020-08-25 03:36 pm (UTC)> В двух местах это в смысле и в имплементации сервиса, и в тестах для него ?
Да.
Не так уж и важно что это за два места. Проблематично, что таких мест - больше одного.
Re: Multiple separate places to modify code
Date: 2020-08-25 03:38 pm (UTC)Re: Multiple separate places to modify code
Date: 2020-08-25 03:50 pm (UTC)Иногда нужно. Но далеко не всегда.
Например, если у нас есть длинный словарь, и новые требования нуждаются в расширении этого словаря -- из этого совсем не следует, что тесты тоже нужно при этом расширять.
Re: Multiple separate places to modify code
Date: 2020-08-25 08:12 pm (UTC)Re: Multiple separate places to modify code
Date: 2020-08-25 08:21 pm (UTC)Я согласен, что необходимость менять код в нескольких местах при изменении одного требования -- это далеко не самое страшное, что случается при поддержке кода.
Но, все же, довольно неприятно.
Потому что можно же одно из мест упустить из виду. Тесты, обычно, помогают самодиагностироваться, но не всегда.
Re: Multiple separate places to modify code
Date: 2020-08-26 08:02 pm (UTC)Потому что можно же одно из мест упустить из виду. Тесты, обычно, помогают самодиагностироваться, но не всегда.
Я не знаю, что конкретно имеется в виду, но тесты, наверное, нужно писать так, чтобы они помогали самодиагностироваться всегда.
Re: Multiple separate places to modify code
Date: 2020-08-26 08:09 pm (UTC)Да, бывает и так.
> тесты, наверное, нужно писать так, чтобы они помогали самодиагностироваться всегда
Это невозможно.
Тем более, что самодиагностика - это лишь второстепенная цель тестов.
Основная цель тестов - диагностировать production code.
Re: Multiple separate places to modify code
Date: 2020-08-26 08:12 pm (UTC)Tests self-diagnostic
Date: 2020-08-26 08:20 pm (UTC)~~~
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)Re: Tests self-diagnostic
Date: 2020-08-27 11:35 pm (UTC)Вы так пишете, как будто считаете способность тестов к самодиагностике - проблемой.
Способность тестов к самодиагностике - не проблема, а достоинство.
Проблема заключается в том, что тесты могут далеко не все свои ошибки самодиагностировать.
Например в этом случае:
~~~
static int Return1() {return 2;}
~~~
этот тест:
-----
Assert.AreEqual(2, Return1())
-----
Не в состоянии выявить проблему (passes).
Re: Tests self-diagnostic
Date: 2020-08-27 11:39 pm (UTC)В чем тут проблема, если не секрет?
Re: Tests self-diagnostic
Date: 2020-08-28 12:19 am (UTC)Но и в имплементации и в тестовом коде - ошибки.
Re: Tests self-diagnostic
Date: 2020-08-28 03:16 am (UTC)Не отражено. Мало ли что люди имеют в виду. Первый Возврат, и чо?
Re: Tests self-diagnostic
Date: 2020-08-28 08:48 am (UTC)Отражено.
Я - автор этого метода.
Я знаю, что именно я вложил в имя этого метода, когда назвал его "Return1".
> Первый Возврат, и чо?
"Первый Возврат" - это твоя некорректная интерпретация имени.
Из этого может следовать, что этот метод желательно переименовать (чтобы уменьшить вероятность некорректной интерпретации в будущем).
Но ошибка в тесте от переименования метода не исчезнет, потому что метод, в соответствии с бизнес требованиями - все равно должен возвращать 1.
Re: Tests self-diagnostic
Date: 2020-08-28 07:57 pm (UTC)К счастью мне такие случаи не встречались на практике, так что я полагаю их вероятность минимальной.
Re: Tests self-diagnostic
Date: 2020-08-29 12:52 am (UTC)Re: Tests self-diagnostic
Date: 2020-08-29 08:33 pm (UTC)Re: Tests self-diagnostic
Date: 2020-08-29 09:52 pm (UTC)Re: Tests self-diagnostic
Date: 2020-08-30 05:12 pm (UTC)Re: Tests self-diagnostic
Date: 2020-08-29 08:12 am (UTC)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
Date: 2020-08-29 08:35 pm (UTC)Разве ? По-моему, это больше похоже на "чётное количество ошибок".
Is full service test coverage possible with mocks?
Date: 2020-08-25 03:43 pm (UTC)Если при тестировании с помощью mocks, в тестах приходится делать какие-то дополнительные операции, которые не делаются в production code, то такое тестирование с помощью mocks -- не покрывает весь сервис.
В частности, не покрыта та часть, которая делает то же, что делают тесты, манипулируя mocks.
Re: Is full service test coverage possible with mocks?
Date: 2020-08-25 08:08 pm (UTC)Re: Is full service test coverage possible with mocks?
Date: 2020-08-25 08:16 pm (UTC)Аналоги этих дополнительных операций -- выполняются и при регулярном выполнении production code, верно?
Так вот эти аналоги (части production code) -- не покрыты mock тестами.
То есть покрытие неполное.
Re: Is full service test coverage possible with mocks?
Date: 2020-08-26 08:10 pm (UTC)Представьте, что в код, который исполняет new DateTime(), передаёся какой-нибудь DateTimeCreator с методом newDateTime(), и все вызовы new DateTime() меняются на вызовы newDateTime().
Теперь в production мы передаём одну имплементацию DateTimeCreator, а в тестах -- другую (я называю её, возможно ошибочно, mock). Я не вижу тут неполного покрытия.
Re: Is full service test coverage possible with mocks?
Date: 2020-08-26 08:15 pm (UTC)> в production мы передаём одну имплементацию DateTimeCreator,
Так вот эта "production" имплементация -- и не тестируется.
И процесс передачи этой "production" имплементации -- тоже не тестируется.
Это и делает тестовое покрытие с помощью mocks - неполным.
Re: Is full service test coverage possible with mocks?
Date: 2020-08-26 08:22 pm (UTC)Да... мои соболезнования твоим сотрудникам.
Re: Is full service test coverage possible with mocks?
Date: 2020-08-26 08:38 pm (UTC)Re: Is full service test coverage possible with mocks?
Date: 2020-08-26 08:56 pm (UTC)Красиво несешь нескладуху и ахинею, а им разбирайся и пытаться внести какой-то смысл.
Re: Is full service test coverage possible with mocks?
Date: 2020-08-26 08:59 pm (UTC)А если ты не разобрался, то откуда ты знаешь, что это ахинея (а не твое упущение)?
Re: Is full service test coverage possible with mocks?
Date: 2020-08-26 09:19 pm (UTC)Это не ошибка, когда несут ахинею. Это система.
Re: Is full service test coverage possible with mocks?
Date: 2020-08-26 09:27 pm (UTC)Зачем ты это сделал?
Re: Is full service test coverage possible with mocks?
Date: 2020-08-26 10:09 pm (UTC)Зачем я комментирую ахинею, что ты несешь? Чисто из зрительного зала. Обсуждать с тобой это нет смысла. Был бы ты программист, тогда могло бы иметь смысл. Какое тут нафиг взаимопонимание. Для взаимопонимания нужно понимание, а у тебя полный швах с этим делом.
Re: Is full service test coverage possible with mocks?
Date: 2020-08-26 11:11 pm (UTC)Нет.
Зачем ты высказал утверждение, не относящееся к вопросу, который я задал?
> Чисто из зрительного зала.
Ты имеешь ввиду, что прикольно иногда покричать какие-нибудь глупости из зрительного зала?
> Для взаимопонимания нужно понимание,
Да.
> а у тебя полный швах с этим делом.
Из каких признаков ты сделал такой вывод?
Re: Is full service test coverage possible with mocks?
Date: 2020-08-26 11:28 pm (UTC)Из той чепухи, что ты нес.
Признаки непонимания
Date: 2020-08-26 11:37 pm (UTC)Давай я тебе дам пару примеров признаков непонимания:
1) Когда ты на мой вопрос отвечаешь нерелеватным утверждением -- это признак твоего непонимания.
2) Когда на мой вопрос с запросом более детального объяснения ты повторяешь недоказанное утверждение -- это признак твоего непонимания.
Re: Признаки непонимания
Date: 2020-08-27 01:12 am (UTC)Могу, но не тебе. И не моей кошке тоже.
Я также уверен, что в доказательствах ты столько же примерно понимаешь, сколько и в функциях.
Re: Признаки непонимания
Date: 2020-08-27 04:56 pm (UTC)Re: Признаки непонимания
Date: 2020-08-27 08:29 pm (UTC)Как минимум половине собравшихся.
Re: Признаки непонимания
Date: 2020-08-27 11:29 pm (UTC)Пока что ты никому не объяснил вообще.
Выглядит как "У нас есть ТАКИЕ приборы! Но мы вам о них не расскажем."
Re: Признаки непонимания
Date: 2020-08-27 11:39 pm (UTC)А все уже и так в курсе, объяснять-то нечего.
Re: Признаки непонимания
Date: 2020-08-28 12:21 am (UTC)Пока что этому нет никаких подтверждений.
Re: Признаки непонимания
Date: 2020-08-28 03:15 am (UTC)Подумай, почему ты не видишь никаких подтверждений.
Re: Признаки непонимания
Date: 2020-08-28 08:30 am (UTC)Re: Is full service test coverage possible with mocks?
Date: 2020-08-27 08:09 pm (UTC)Процесс его передачи, наверное, тоже.
Re: Is full service test coverage possible with mocks?
Date: 2020-08-27 11:39 pm (UTC)Если можно покрыть тестами DateTimeCreator, то зачем нужен Mock, подменяющий DateTimeCreator?
> Процесс его передачи, наверное, тоже.
Можно. В полноценном integration тесте, который не использует Mock.
Re: Is full service test coverage possible with mocks?
Date: 2020-08-28 08:01 pm (UTC)Чтобы можно было протестировать наш сервис для разных DateTime.
Можно. В полноценном integration тесте, который не использует Mock.
И в тесте, который использует мок тоже, потому что процессы передачи настоящего "DateTimeCreator" и его мока -- одинаковые.
Re: Is full service test coverage possible with mocks?
Date: 2020-08-29 12:50 am (UTC)> Чтобы можно было протестировать наш сервис для разных 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).
Re: Is full service test coverage possible with mocks?
Date: 2020-08-29 08:32 pm (UTC)Да, при тестировании с моком одна часть рабочего кода не покрывается.
Но её вроде можно покрыть, добавив тест с настоящим DateTimeCreator.
Re: Is full service test coverage possible with mocks?
Date: 2020-08-29 09:51 pm (UTC)Но если работа с настоящим DateTimeCreator - имплементирована в моке по умолчанию - тогда, действительно, может получиться покрыть рабочий код тестами полностью.
Re: Is full service test coverage possible with mocks?
Date: 2020-08-30 05:11 pm (UTC)И мы можем протестировать его в таком виде.
А для тестов, которые требуют DateTimeCreator mock, мы втыкаем этот mock в наш сервис вместо настоящего DateTimeCreator-а.
Re: Is full service test coverage possible with mocks?
Date: 2020-08-30 06:12 pm (UTC)> И мы можем протестировать его в таком виде.
Я именно это и имел ввиду, когда написал "Но если работа с настоящим DateTimeCreator - имплементирована в моке по умолчанию - тогда, действительно, может получиться покрыть рабочий код тестами полностью."
Похоже, разница между нашими утверждениями лишь в том, что вы называете "моком" лишь изменяемую часть, а я называю "моком" весь класс, который включает в себя изменяемую часть.
Re: Is full service test coverage possible with mocks?
Date: 2020-08-31 09:09 am (UTC)Да, похоже на то. А как правильно ?
"Mock" и "mocking" in programming
Date: 2020-08-31 12:18 pm (UTC)Термины "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)Re: Is full service test coverage possible with mocks?
Date: 2020-08-31 03:24 pm (UTC)"Partial mocking is not acceptable", сказала мне одна менеджерка в Гугле. Ну, книжек-то она не читала, а нести что-то надо.
Re: Is full service test coverage possible with mocks?
Date: 2020-08-30 06:58 pm (UTC)> И мы можем протестировать его в таком виде.
Обратите внимание, что обратное - тоже верно: если сервис не включает в себя настоящий DateTimeCreator по умолчанию, то полный test coverage такого кода - невозможен.
Что приводит нас к "best practice" рекомендации о том, как имплементировать моки:
Для того, чтобы повысить test coverage, имплементация мока для рабочего кода - должна быть включена по умолчанию в сервис (чтобы рабочий код, вызывающий этот сервис, не должен был заморачиваться explicit инициализацией mock).
Это, пожалуй, основной вывод из нашей с вами дискуссии о моках.
Re: Is full service test coverage possible with mocks?
Date: 2020-08-31 09:10 am (UTC)Да, можно сделать такой вывод.
Re: Is full service test coverage possible with mocks?
Date: 2020-08-29 10:03 pm (UTC)Вижу, вам уже заморочили голову.
Re: Is full service test coverage possible with mocks?
Date: 2020-08-30 05:13 pm (UTC)no subject
Date: 2020-08-24 06:50 am (UTC)Remember, remember the 19th of January 2038.
no subject
Date: 2020-08-24 07:24 am (UTC)Exactly.
no subject
Date: 2020-08-24 08:10 am (UTC)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)
no subject
Date: 2020-08-24 01:57 pm (UTC)This one is basically a joke. But if people count on dispersion...
Regarding blocks indefinitely, we would be testing the RNG itself here, right?
no subject
Date: 2020-08-24 04:46 pm (UTC)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.
no subject
Date: 2020-08-24 08:28 am (UTC)время есть область ответственности оси, прикладной софт не должно парить что где там переполнилось вообще
no subject
Date: 2020-08-24 01:58 pm (UTC)По первому вопросу - это мы happy path проходим? Его, конечно, тоже надо. Но вообще речь была лишь о воспроизводимости.
no subject
Date: 2020-08-24 02:45 pm (UTC)How to test nondeterministic functions
Date: 2020-08-24 05:52 pm (UTC)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"?
Re: How to test nondeterministic functions
Date: 2020-08-24 06:23 pm (UTC)Oh, you found some idiots and their opinions. Congratulations.
Re: How to test nondeterministic functions
Date: 2020-08-24 08:14 pm (UTC)Re: How to test nondeterministic functions
Date: 2020-08-24 09:22 pm (UTC)People that are clueless regarding what is function.
Re: How to test nondeterministic functions
Date: 2020-08-24 09:39 pm (UTC)Re: How to test nondeterministic functions
Date: 2020-08-24 10:49 pm (UTC)You won't understand my answer. That's one of the signs.
"Idiots" sign
Date: 2020-08-24 11:24 pm (UTC)Re: "Idiots" sign
Date: 2020-08-24 11:40 pm (UTC)As if I care.
Whom here do you understand, name one.
Re: "Idiots" sign
Date: 2020-08-24 11:49 pm (UTC)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.
Re: "Idiots" sign
Date: 2020-08-25 01:23 am (UTC)No, you did not.
Sings of understanding
Date: 2020-08-25 03:24 pm (UTC)Re: Sings of understanding
Date: 2020-08-25 04:24 pm (UTC)You won't understand my answer either.
Re: Sings of understanding
Date: 2020-08-25 05:13 pm (UTC)Still, lack of answer suggests: unwillingness to teach and unwillingness to expose your thoughts for external testing.
Re: Sings of understanding
Date: 2020-08-25 05:32 pm (UTC)I said I don't care. Why would I? I'm not your teacher. You want to learn something - learn something. Buy my book, read it and ask questions. When done, we can talk.
The book
Date: 2020-08-25 05:38 pm (UTC)Why do you think your book will teach me what I need?
Re: The book
Date: 2020-08-25 06:42 pm (UTC)It obviously won't. You seem to be unteachable. And I don't know what you need.
Re: The book
Date: 2020-08-25 06:47 pm (UTC)Then why did you recommend to buy your book?
Re: The book
Date: 2020-08-25 07:00 pm (UTC)For the case you change, with time.
Also, https://juan-gandhi.dreamwidth.org/4300834.html
Re: The book
Date: 2020-08-25 07:17 pm (UTC)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)Is "nondeterministic function" a useful concept
Date: 2020-08-25 04:01 pm (UTC)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.
Re: Is "nondeterministic function" a useful concept
Date: 2020-08-25 05:58 pm (UTC)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.
Re: Is "nondeterministic function" a useful concept
Date: 2020-08-25 06:36 pm (UTC)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"?
Re: Is "nondeterministic function" a useful concept
Date: 2020-08-25 06:39 pm (UTC)Math uses terms. What people on the internets say, does not matter. Your opinion, e.g., does not matter. My neither.
Re: Is "nondeterministic function" a useful concept
Date: 2020-08-25 06:50 pm (UTC)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.
Re: Is "nondeterministic function" a useful concept
Date: 2020-08-25 07:10 pm (UTC)I would rather you answered whether you understood the substance of the post.
If I cared.
Re: Is "nondeterministic function" a useful concept
Date: 2020-08-25 07:19 pm (UTC)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?
Re: Is "nondeterministic function" a useful concept
Date: 2020-08-26 10:30 am (UTC)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)Are you implying that you did not write "No one outside SQL community uses that term."?
Sweeping the uncomfortable facts under the carpet
Date: 2020-08-26 01:22 pm (UTC)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.
Misunderstanding question
Date: 2020-08-26 02:48 pm (UTC)> 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)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)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)Re: Expecting answers to unasked questions
Date: 2020-08-27 04:59 pm (UTC)Re: "то есть" trick
Date: 2020-08-26 06:16 pm (UTC)> 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.
Infallible teacher
Date: 2020-08-24 05:57 pm (UTC)Because you are perfect and cannot make mistakes, right?
Re: Infallible teacher
Date: 2020-08-24 06:22 pm (UTC)No. Because you need to have a certain level of expertise to argue. Go ahead, demonstrate your expertise.
Re: Infallible teacher
Date: 2020-08-24 08:12 pm (UTC)I demonstrated my expertise.
Unfortunately, today you are unwilling to comprehend it.
What kind of demonstration would convince you?
Re: Infallible teacher
Date: 2020-08-24 09:24 pm (UTC)I see that it's bullshit. That's it. There's nothing to comprehend. Bullshit. If you learned some math, or something, you would see it yourself.
Re: Infallible teacher
Date: 2020-08-24 09:55 pm (UTC)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.
Re: Infallible teacher
Date: 2020-08-24 10:49 pm (UTC)I identified the mistakes, that's why I wrote the post. The fact that you do not understand shit is none of my business. You don't have the right education; okay. None of my business. You want to learn - learn. You don't want to learn - ok, your business. I really don't care. You may have learned wrong math, or actually did not learn it, or forgot it, I don't know. I'm not your teacher. You are on your own.
There are many people here, in this network, that learned a lot during these last 10-15 years. You learned nothing in that area, math, programming, etc. Not my responsibility, really. You had time. You still have time. Get back in 5 years, we will see if you learned something. Now your knowledge is close to zero.
no subject
Date: 2020-08-28 09:27 am (UTC)Мне очевидно, что любое конечное количество моков - это happy path при бесконечном оригинале.
Ну и так же, что все, что придумает конкретный программист, - это тоже happy path, т.к. он уже это придумал, и значит предусмотрел в коде.
Я считаю, что тесты бывают только двух видов: integration - что реально видит наш юзер и regression - настоящий un-happy path из баг репортов. Все остальное - карго культ.