-
Notifications
You must be signed in to change notification settings - Fork 33
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
base: develop
Are you sure you want to change the base?
IOS-6610 add a mechanism for automatic indexation of wallets #3322
Conversation
…add-a-mechanism-for-automatic-indexation-of-wallets-3
class UserWalletNameIndexationTests: XCTestCase { | ||
private var existingNameTestCases: [(String, String)] { | ||
[ | ||
("Wallet 2", /* -> */ "Wallet 2"), |
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.
если уже есть индекс его пропускаем, на дублирование не обращаем внимания? Может обсуждали где-то? в описании задачи не нашел
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.
Показывал Лехе результат миграции, он одобрил
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.
Wallet, Wallet, Wallet2 превратятся в Wallet2, Wallet3, Wallet2 ?
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.
Wallet -> Wallet (потому что такого нет)
Wallet -> Wallet 3 (потому что 2 уже есть)
Wallet2 -> Wallet 2 (потому что пользователь задал имя)
В первом куске тестов есть подобное
Tangem/App/Services/UserWalletRepository/CommonUserWalletRepository.swift
Outdated
Show resolved
Hide resolved
private var indexesByNameTemplate: [String: [Int]] = [:] | ||
private let nameComponentsRegex = try! NSRegularExpression(pattern: "^(.+)(\\s+\\d+)$") | ||
|
||
init(mode: Mode, names: [String]) { |
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.
Давай сделаем утилиту stateless, без mode. Просто набор методов и немного подрефачим для простоты
публичные методы
- миграция
Миграция пусть работает сразу с моделями кошельков, тогда эта логика переедет из репозитория сюда и позже будет удалена.
- получили словари с занятыми индексами распарсив кошельки
- пошли в цикле по кошелькам, ищем пустые,
- находим ближайший свободный индекс
- конструируем имя и обновляем у кошелька
- обновляем локальный словарь индексов (может сет заюзать?)
- продолжаем, пока кошельки не кончатся
- возвращаем новые кошельки, если была миграция. Если не было, возвращаем nil или пустой массив, это хорошая оптимизация
- поиск нового имени
- получили словари с занятыми индексами распарсив кошельки
- взяли ближайший свободный
- сконструировали имя и вернули
Приватные
- Парсинг кошельков
- поиск следующего индекса
- конструктор имени
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.
Ради простоты и тестов не хочется передавать сюда модели, поэтому сделал на строках. Передавать массив строк, получать его обратно и задавать имена массиву моделей выглядело ненадежно, поэтому сделал на скалярах
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.
это комментарий не к тестам же
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.
Мой тоже
import Foundation | ||
|
||
class UserWalletNameIndexationHelper { | ||
private var indexesByNameTemplate: [String: [Int]] = [:] |
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.
indexes -> indices
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.
Что не так с indexes?
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.
Чаще используется форма indices, в том числе Apple, это не крит в этой задаче
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.
Я бы предложил оставить как есть чтобы не переусложнять
] | ||
} | ||
|
||
func testUserWalletNameIndexation() { |
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.
Давай еще пожалуйста тесты упростим, чтобы было в стиле
- тесты индексации нового кошелька
- дано имя и пользовательский набор кошельков
- ожидаемый результат такой-то
- запустили, сравнили ассертом
- тесты миграции
- дано: пользовательский массив
- ожидаемый результат
- сравнение
Все на хардкодах, без рандомных числе и тп
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.
Тесты фактически на хардкодах, там рандом с сидом
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.
тесты чем тупее написаны, тем лучше)
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.
В этих тестах ничего особо умного нет. Это тоже самое что 10 захардкоженных тесткейсов. Если так сильно режет глаза могу на 10 массивов заменить
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.
Дело не в режет. Беглого взгляда на тесты недостаточно, чтобы понять что тестируется и какой ожидаемый результат. Не хочется тратить время на ревью еще и тестов
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.
Отрефакторил
…add-a-mechanism-for-automatic-indexation-of-wallets-3
…add-a-mechanism-for-automatic-indexation-of-wallets-3
Прошлый МР: #3204
Утилитка работает в двух режимах — миграция существующих кошельков и предложение нового имени. Пытался совместить в одно, но не получилось. Разделять на две утилиты не хочется.
Тесты с рандомайзером на всякий случай, 10 прогонов. Оба режима