-
Notifications
You must be signed in to change notification settings - Fork 50
Optimize test-suite #40
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
peresvetjke
wants to merge
8
commits into
hardcode-dev:master
Choose a base branch
from
peresvetjke:better-dx
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| .DS_Store |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,123 @@ | ||
| # Оптимизация | ||
|
|
||
| Будем оптимизировать `test-suite` своего проекта. | ||
|
|
||
| В настоящий момент в `CI` есть две параллельных джобы: | ||
| - в первой запускаются `spec/models/` & `spec/controllers`; | ||
| - во второй все остальные спеки. | ||
|
|
||
| Начнем с анализа текущей ситуации. | ||
|
|
||
| ``` | ||
| # Полный `suite` сейчас. | ||
|
|
||
| Finished in 9 minutes 1 second (files took 14.98 seconds to load) | ||
|
|
||
| [TEST PROF INFO] TagProf report for type | ||
|
|
||
| type time total %total %time avg | ||
|
|
||
| model 02:17.949 1159 30.55 26.51 00:00.119 | ||
| controller 01:29.712 419 11.04 17.24 00:00.214 | ||
| service 01:23.116 701 18.48 15.97 00:00.118 | ||
| serializer 00:52.336 415 10.94 10.06 00:00.126 | ||
| command 00:51.256 126 3.32 9.85 00:00.406 | ||
| query 00:34.382 54 1.42 6.61 00:00.636 | ||
| job 00:21.393 138 3.64 4.11 00:00.155 | ||
| builder 00:11.293 79 2.08 2.17 00:00.142 | ||
| request 00:10.441 76 2.00 2.01 00:00.137 | ||
| decorator 00:09.839 87 2.29 1.89 00:00.113 | ||
| lib 00:08.771 361 9.52 1.69 00:00.024 | ||
| mailer 00:06.753 68 1.79 1.30 00:00.099 | ||
| publishing 00:03.029 34 0.90 0.58 00:00.089 | ||
| validator 00:00.015 8 0.21 0.00 00:00.001 | ||
| concern 00:00.006 4 0.11 0.00 00:00.001 | ||
| apivore 00:00.002 65 1.71 0.00 00:00.000 | ||
| ``` | ||
|
|
||
| ## Этап 1 (`parallel_tests`) | ||
|
|
||
| Потратил много времени на попытки распараллелить тесты с помощью `parallel_tests`. Столкнулся с проблемами: | ||
|
|
||
| ### Ошибки | ||
|
|
||
| Рандомно сыпятся ошибки. Кажется перечитал все `issues` в библиотеке по теме. | ||
|
|
||
| 1. Нашел проблему связанную с обращением к внешнему сервису при загрузке изображений и застабил в тестах. | ||
| 2. Осталась проблема с `requests`, с которой не помогает и `retry-spec` (вероятно, недостаток нужного конфига - где пока не знаю, либо не хватает какого-то сброса состояния перед повторной попыткой прогона теста, но вот какое именно - к сожалению, пока определить не удалось). | ||
|
|
||
| В любом случае не стабильность джоб кажется существенным минусом сейчас. Надеюсь в будущем удастся это добороть. Пока решил отложить. | ||
|
|
||
| ### Долгий `setup` БД для параллельных процессов | ||
|
|
||
| В перспективе хотелось бы найти простой способ осуществлять `setup` для первого процесса, а для остальных просто создавать по `template` - быстрого способа сделать этого в нашей конфигурации не нашел. До тех пор польза распараллеливания в нашей конфигурации в целом осталась для меня под вопросом. | ||
|
|
||
| ## Этап 2 (`test-prof`) | ||
|
|
||
| Провел профилирование самых больших по времени блоков тестов. | ||
|
|
||
| В рамках текущей задачи решил сконцентрироваться на устранении оверхедов при работи с фактори/БД. | ||
|
|
||
| Главным инструментарием для оптимизации тестов стал гем `test-prof`: | ||
| - устранил лишние операции с БД с помощью `let_it_be`/`befor_all`; | ||
| - где применимо, заменил `.create` на `.build` в фактори. | ||
|
|
||
| # Результаты | ||
|
|
||
| Примечание. Бенчмарк по `suite` в целом (см. ниже) отличается от отдельных блоков - в лучшую сторону (вероятно, это связано с тем, что время выполнение в общем скопе занимает больше времени). | ||
|
|
||
| ### spec/services | ||
|
|
||
| Удалось ускорить выполнение: на 10 сек. с 50 до 40 секунд (20%). | ||
|
|
||
| <img src="/screenshots/services.png" width="750" /> | ||
|
|
||
| ### spec/serializers | ||
|
|
||
| Удалось ускорить выполнение: на 10 сек. - с 42 до 32 секунд (23%). | ||
|
|
||
| <img src="/screenshots/serializers.png" width="750" /> | ||
|
|
||
| ### spec/models | ||
|
|
||
| Удалось ускорить выполнение: на 18 сек. - с 131 до 113 секунд (14%). | ||
|
|
||
| <img src="/screenshots/models.png" width="750" /> | ||
|
|
||
| ### spec/queries | ||
|
|
||
| Удалось ускорить выполнение: на 12 сек. - с 32 до 10 секунд (31%). | ||
|
|
||
| <img src="/screenshots/queries.png" width="750" /> | ||
|
|
||
| ### Итого по `suite` | ||
|
|
||
| Удалось ускорить выполнение: на 1 мин. 32 сек. - с 549 до 457 сек (17%). | ||
|
|
||
| С учетом распараллеливания, чистое расчетное время выигрыша (ускорение пайплайна) чуть меньше - 1 мин. 14 сек. | ||
|
|
||
| ``` | ||
| Finished in 7 minutes 46 seconds (files took 15.75 seconds to load) | ||
|
|
||
| [TEST PROF INFO] TagProf report for type | ||
| type time total %total %time avg | ||
|
|
||
| model 01:57.424 1159 30.55 26.76 00:00.101 | ||
| controller 01:31.925 419 11.04 20.95 00:00.219 | ||
| service 01:00.054 701 18.48 13.69 00:00.085 | ||
| command 00:56.223 126 3.32 12.81 00:00.446 | ||
| serializer 00:28.690 415 10.94 6.54 00:00.069 | ||
| job 00:23.340 138 3.64 5.32 00:00.169 | ||
| builder 00:11.340 79 2.08 2.58 00:00.143 | ||
| decorator 00:11.033 87 2.29 2.51 00:00.126 | ||
| request 00:10.625 76 2.00 2.42 00:00.139 | ||
| lib 00:08.514 361 9.52 1.94 00:00.023 | ||
| query 00:07.473 54 1.42 1.70 00:00.138 | ||
| mailer 00:07.130 68 1.79 1.63 00:00.104 | ||
| publishing 00:04.939 34 0.90 1.13 00:00.145 | ||
| validator 00:00.015 8 0.21 0.00 00:00.001 | ||
| concern 00:00.005 4 0.11 0.00 00:00.001 | ||
| apivore 00:00.001 65 1.71 0.00 00:00.000 | ||
| ``` | ||
|
|
||
| <img src="/screenshots/suite.png" width="750" /> | ||
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Алексей, большое спасибо за совет про
AnyFixtureна вебинаре ))Сам я к своему стыду в документации до туда не добрался (🤦 ), что означает что я вообще его не прочитал - ведь это в самом начале в общем (просто видимо Владимир Дементьев пишет код быстрее, чем я читаю документацию к ней :) ).
И получается, я все делал в этом ДЗ не правильно.
Начал применять подход
any_для повторяющихся объектов, тесты задышали! ) перспективы атомные. и решение получается куда более красивым.Спасибо!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Да, Владимир удивительно продуктивный, меня тоже поражает