Skip to content
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

IOS-6610 add a mechanism for automatic indexation of wallets #3322

Draft
wants to merge 7 commits into
base: develop
Choose a base branch
from

Conversation

megakoko
Copy link
Contributor

Прошлый МР: #3204

Утилитка работает в двух режимах — миграция существующих кошельков и предложение нового имени. Пытался совместить в одно, но не получилось. Разделять на две утилиты не хочется.

Тесты с рандомайзером на всякий случай, 10 прогонов. Оба режима

@megakoko megakoko requested a review from Andoran90 May 22, 2024 12:44
@megakoko megakoko marked this pull request as ready for review May 22, 2024 12:44
@megakoko megakoko requested review from tureck1y and a team as code owners May 22, 2024 12:44
class UserWalletNameIndexationTests: XCTestCase {
private var existingNameTestCases: [(String, String)] {
[
("Wallet 2", /* -> */ "Wallet 2"),
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Показывал Лехе результат миграции, он одобрил

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wallet, Wallet, Wallet2 превратятся в Wallet2, Wallet3, Wallet2 ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wallet -> Wallet (потому что такого нет)
Wallet -> Wallet 3 (потому что 2 уже есть)
Wallet2 -> Wallet 2 (потому что пользователь задал имя)

В первом куске тестов есть подобное

private var indexesByNameTemplate: [String: [Int]] = [:]
private let nameComponentsRegex = try! NSRegularExpression(pattern: "^(.+)(\\s+\\d+)$")

init(mode: Mode, names: [String]) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Давай сделаем утилиту stateless, без mode. Просто набор методов и немного подрефачим для простоты

публичные методы

  • миграция
    Миграция пусть работает сразу с моделями кошельков, тогда эта логика переедет из репозитория сюда и позже будет удалена.
  1. получили словари с занятыми индексами распарсив кошельки
  2. пошли в цикле по кошелькам, ищем пустые,
  • находим ближайший свободный индекс
  • конструируем имя и обновляем у кошелька
  • обновляем локальный словарь индексов (может сет заюзать?)
  • продолжаем, пока кошельки не кончатся
  1. возвращаем новые кошельки, если была миграция. Если не было, возвращаем nil или пустой массив, это хорошая оптимизация
  • поиск нового имени
  1. получили словари с занятыми индексами распарсив кошельки
  2. взяли ближайший свободный
  3. сконструировали имя и вернули

Приватные

  • Парсинг кошельков
  • поиск следующего индекса
  • конструктор имени

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

это комментарий не к тестам же

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Мой тоже

import Foundation

class UserWalletNameIndexationHelper {
private var indexesByNameTemplate: [String: [Int]] = [:]
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

indexes -> indices

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Что не так с indexes?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Чаще используется форма indices, в том числе Apple, это не крит в этой задаче

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

]
}

func testUserWalletNameIndexation() {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Давай еще пожалуйста тесты упростим, чтобы было в стиле

  1. тесты индексации нового кошелька
  • дано имя и пользовательский набор кошельков
  • ожидаемый результат такой-то
  • запустили, сравнили ассертом
  1. тесты миграции
  • дано: пользовательский массив
  • ожидаемый результат
  • сравнение

Все на хардкодах, без рандомных числе и тп

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тесты фактически на хардкодах, там рандом с сидом

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

тесты чем тупее написаны, тем лучше)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В этих тестах ничего особо умного нет. Это тоже самое что 10 захардкоженных тесткейсов. Если так сильно режет глаза могу на 10 массивов заменить

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Дело не в режет. Беглого взгляда на тесты недостаточно, чтобы понять что тестируется и какой ожидаемый результат. Не хочется тратить время на ревью еще и тестов

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Отрефакторил

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants