Skip to content

UserActivationServiceImpl.findOlderThan() unit tests #558

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

Closed

Conversation

Shagbark
Copy link
Contributor

Addressed to #337

@@ -17,6 +17,7 @@
*/
package ru.mystamps.web.service

import org.apache.commons.lang3.time.DateUtils
Copy link
Owner

Choose a reason for hiding this comment

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

Откати эту часть с импортом, тут уже был правильный импорт, а это, видимо, IDEA постаралась.

// Tests for findOlderThan()
//

def "findOlderThan() should throw exception when passed days are less zero"() {
Copy link
Owner

Choose a reason for hiding this comment

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

s/less zero/less than zero/

Copy link
Owner

Choose a reason for hiding this comment

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

s/passed days/days/


def "findOlderThan() should invoke dao, pass changed date and return the result "() {
given:
def days = 4
Copy link
Owner

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
Owner

@php-coder php-coder Mar 30, 2017

Choose a reason for hiding this comment

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

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

given:
def days = 4
and:
def expectedDate = DateUtils.addDays(new Date(), -days)
Copy link
Owner

Choose a reason for hiding this comment

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

Date expectedDate = new Date() + days

thrown IllegalArgumentException
}

def "findOlderThan() should invoke dao, pass changed date and return the result "() {
Copy link
Owner

Choose a reason for hiding this comment

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

Ты не проверяешь, что метод возвращает значение от дао. Добавишь проверку?

@@ -264,5 +264,30 @@ class UsersActivationServiceImplTest extends Specification {
then:
1 * usersActivationDao.removeByActivationKey(activationKey)
}

//
// Tests for findOlderThan()
Copy link
Owner

Choose a reason for hiding this comment

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

Передвинь эти тесты повыше, так чтобы порядок тестируемых методов в тестах совпадал с их порядком объявления этих методов в самом сервисе.

@Shagbark
Copy link
Contributor Author

Да, сейчас добавлю.
И, наверное, там будет
Date expectedDate = new Date() - days? Не, плюс?

@php-coder
Copy link
Owner

Date expectedDate = new Date() - days? Не, плюс?

Да, разумеется.

@php-coder
Copy link
Owner

P.S. Там на код CodeNarc ругается, так что надо добавить пару аннотаций (как и в других тестах), чтобы отключить эту ругань. В отчете трэвиса можешь посмотреть подробности.

@Shagbark
Copy link
Contributor Author

Я так понимаю, что CodeNarc ругается на то, что мы делаем замыкание, а он хочет, чтобы в метод передали параметр?
А что если мы уберем круглые скобки при вызове метода?
1* userActivationDao.findOlderThan{ Date date -> .... }

@php-coder
Copy link
Owner

Ты можешь запустить его локально и проверить: https://github.com/php-coder/mystamps/wiki/codenarc

@Shagbark
Copy link
Contributor Author

Хм, странно.
При убранной аннотации @SuppressWarnings и с оставленными круглыми скобками, он мне выдает
Build Success.
И тоже самое с аннотацией, и даже если не стоят круглые скобки.

@php-coder
Copy link
Owner

Я спать 😴 Если останутся вопросы -- задавай, как будет время, посмотрю.

@Shagbark
Copy link
Contributor Author

Спокойной ночи :)

@php-coder php-coder changed the title Gh337 findOlderThan utests UserActivationServiceImpl.findOlderThan() unit tests Mar 31, 2017
@Shagbark
Copy link
Contributor Author

Shagbark commented Apr 3, 2017

Вячеслав, а можно запустить проверку на Travisе без коммита?

@php-coder
Copy link
Owner

Вячеслав, а можно запустить проверку на Travisе без коммита?

Можно. Все команды, которые выполняются в Travis описаны в его конфигурационном файле:

mystamps/.travis.yml

Lines 11 to 35 in 88979cd

before_script:
- if [ "$SPRING_PROFILES_ACTIVE" = 'travis' ]; then
mysql -u travis -e 'CREATE DATABASE mystamps CHARACTER SET utf8;';
if [ "$TRAVIS_BRANCH" = 'prod' ]; then
pip install --user ansible==2.1.1.0;
fi;
npm install -g bootlint;
pip install --user html5validator;
pip install --user robotframework-lint;
if [ "$TRAVIS_PULL_REQUEST" != 'false' ]; then
gem install danger nokogiri --no-ri --no-rdoc;
fi;
fi
script:
- if [ "$SPRING_PROFILES_ACTIVE" = 'travis' ]; then
./src/main/scripts/ci/check-build-and-verify.sh;
else
./src/main/scripts/ci/check-build-and-verify.sh --only-integration-tests;
fi
after_success:
- if [ "$SPRING_PROFILES_ACTIVE" = 'travis' ]; then
./src/main/scripts/ci/publish-code-coverage.sh;
fi

Но у тебя падает сейчас только CodeNarc и запустить только его локально довольно просто: https://github.com/php-coder/mystamps/wiki/codenarc

@php-coder
Copy link
Owner

P.S. Недочитал, видио. На трэвисе без коммита, наверное, могу только я, перезапустив задачу. В твоем случае придется делать коммит. Либо переписывать существующий. А зачем тебе это, к слову?

@Shagbark
Copy link
Contributor Author

Shagbark commented Apr 3, 2017

Да у меня, просто, CodeNar всегда выдает на консоли Build Success (а в отчете пусто). А также кидает такой exception:
java.lang.AssertionError: Invalid argument format: [Stamps]. Expression: matcher. Values: matcher = java.util.regex.Matcher[pattern=\-(.*)\=(.*) region=0,6 lastmatch=]

А в Travise он пишет, что именно не так. Как вот сейчас, что лучше использовать [], вместо new ArrayList<>(). Вот и спросил.

@php-coder
Copy link
Owner

А также кидает такой exception:
java.lang.AssertionError: Invalid argument format: [Stamps]. Expression: matcher. Values: matcher = java.util.regex.Matcher[pattern=-(.)=(.) region=0,6 lastmatch=]

Не удивляюсь, если это баг в самом плагине :( А можешь полное сообщение об ошибке привести (например, сделать скриншот)?

@Shagbark
Copy link
Contributor Author

Shagbark commented Apr 3, 2017

image

@Shagbark
Copy link
Contributor Author

Shagbark commented Apr 3, 2017

Вот окончание ошибки
image

@php-coder
Copy link
Owner

Похоже на багу либо в плагине либо в самом CodeNarc, который не может корректно обрабатывать пути с пробелами. Попробуй скопировать проект в каталог в пути к которому нет пробелов и запустить проверку там.

@Shagbark
Copy link
Contributor Author

Shagbark commented Apr 3, 2017

Неа, такую же ошибку выдает :(

@php-coder
Copy link
Owner

Тогда делай любые коммиты, все равно потом сквошить в один нужно будет :)

P.S. git commit --allow-empty -m 'Tada'

@Shagbark
Copy link
Contributor Author

Shagbark commented Apr 3, 2017

Хорошо :)

@Shagbark
Copy link
Contributor Author

Shagbark commented Apr 3, 2017

Хм, странно, а почему сейчас не проходит build?
Из-за этого?
image

@php-coder
Copy link
Owner

Нет, из-за бага в danger который я как раз с разработчиками обсуждаю.

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

@Shagbark
Copy link
Contributor Author

Shagbark commented Apr 4, 2017

Я попробую :)
Никогда не сквошил коммиты в один.
Почитаю и вечером попробую сделать.

@Shagbark Shagbark force-pushed the gh337_findOlderThan_utests branch from 35534f9 to cd354e4 Compare April 4, 2017 20:20
@@ -264,5 +295,5 @@ class UsersActivationServiceImplTest extends Specification {
then:
1 * usersActivationDao.removeByActivationKey(activationKey)
}

Copy link
Owner

Choose a reason for hiding this comment

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

Please, remove this useless modification.

@@ -17,6 +17,8 @@
*/
package ru.mystamps.web.service

import ru.mystamps.web.dao.dto.UsersActivationFullDto
import ru.mystamps.web.tests.DateUtils
Copy link
Owner

@php-coder php-coder Apr 5, 2017

Choose a reason for hiding this comment

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

Please, move these imports below, to other import from ru.mystamps package.

and:
Date expectedDate = new Date() - days
and:
List<UsersActivationFullDto> expectedResult = []
Copy link
Owner

Choose a reason for hiding this comment

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

Let's compare with non-empty list:

List<UsersActivationFullDto> expectedResult = [ TestObjects.createUsersActivationFullDto() ]

}

@SuppressWarnings(['ClosureAsLastMethodParameter', 'UnnecessaryReturnKeyword'])
def "findOlderThan() should invoke dao, pass changed date and return the result "() {
Copy link
Owner

Choose a reason for hiding this comment

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

and return the result "

Please, remove trailing space at the end of the method name.

@php-coder
Copy link
Owner

и желательно в авторстве указать имя с фамилией, а не просто имя или нет. Впрочем, если ты не хочешь раскрывать свою фамилию, то это не обязательно.

What did you decide on that?

@Shagbark
Copy link
Contributor Author

Shagbark commented Apr 5, 2017

Я указал в commit message имя и фамилию :)
Дмитрий Процко (Dmitry Protsko).

@php-coder
Copy link
Owner

php-coder commented Apr 5, 2017

It's shouldn't be in the message itself but in the author's info:

$ git config --global user.name "Your Name"
$ git commit --am --reset-author

@Shagbark
Copy link
Contributor Author

Shagbark commented Apr 5, 2017

Аа, понял, сделаю тогда сегодня.

@php-coder
Copy link
Owner

Thanks! And the last thing, please, set the following commit message:

UsersActivationService.findOlderThan(): add unit tests.

Fix #337

@Shagbark
Copy link
Contributor Author

Shagbark commented Apr 5, 2017

Хорошо.
А коммиты также сквошить?

@php-coder
Copy link
Owner

Yes, I'm expecting a single commit with the provided message.

@mystamps-bot
Copy link

mystamps-bot commented Apr 6, 2017

1 Message
📖 @Shagbark thank you for the PR! All quality checks have been passed! Next step is to wait when @php-coder will review this code

Generated by 🚫 Danger

@coveralls
Copy link

Coverage Status

Changes Unknown when pulling 21f6580 on Shagbark:gh337_findOlderThan_utests into ** on php-coder:master**.

@Shagbark
Copy link
Contributor Author

Shagbark commented Apr 6, 2017

Блин, я же поменял user.name в git config :(

@php-coder
Copy link
Owner

@Shagbark Еще не поздно :)

import ru.mystamps.web.validation.ValidationRules
import ru.mystamps.web.dao.dto.UsersActivationFullDto
import ru.mystamps.web.tests.DateUtils
Copy link
Owner

Choose a reason for hiding this comment

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

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

В данном случае, верни, пожалуйста, импорт ru.mystamps.web.tests.DateUtils туда где он был. А импорт ru.mystamps.web.dao.dto.UsersActivationFullDto должен быть после импорта import ru.mystamps.web.dao.dto.UsersActivationDto

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Я так понимаю, мне нужно сделать git checkout --UserActivationServiceImpl.java до определенного коммита, в котором не было изменений, которые не относятся к диффу (либо до начала ветвления)?
А потом добавить 2 теста, с учетом поправок?

Я ни разу не отменял коммит, поэтому спрашиваю :)

Copy link
Owner

Choose a reason for hiding this comment

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

It's good that you're asking because I'm expecting that you will edit a file and will execute git commit -a --amend to add your modifications to the existing commit. Note that existing commit will be overwritten and to push it to the server you will have to use git push -f.

@@ -264,5 +295,4 @@ class UsersActivationServiceImplTest extends Specification {
then:
1 * usersActivationDao.removeByActivationKey(activationKey)
}

Copy link
Owner

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.

А как можно убрать вот эту строку?
Я сделал git commit -a --amend, убрал изменения с импортами, а здесь изменения остались?

Copy link
Owner

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.

Аа, дурак, понял.
Слушай, а такой вопрос: я сделал git commit -a --amend -am --reset-author, а все равно запушилось как Shagbark?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

image

Copy link
Owner

Choose a reason for hiding this comment

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

Я вижу, что запушилось все ок. Спасибо!

Copy link
Owner

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
Contributor Author

Choose a reason for hiding this comment

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

Ура! Я победил :)

@Shagbark Shagbark force-pushed the gh337_findOlderThan_utests branch from 21f6580 to 22972d0 Compare April 16, 2017 14:48
@Shagbark Shagbark force-pushed the gh337_findOlderThan_utests branch from 22972d0 to d59208f Compare April 16, 2017 18:16
@php-coder
Copy link
Owner

Отлично! Спасибо!

@php-coder
Copy link
Owner

Merged in 15e0625 commit.

@coveralls
Copy link

Coverage Status

Changes Unknown when pulling d59208f on Shagbark:gh337_findOlderThan_utests into ** on php-coder:master**.

@php-coder
Copy link
Owner

Looks like I forgot to give you this link: https://github.com/php-coder/mystamps/wiki/after_merge_steps

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

Successfully merging this pull request may close these issues.

4 participants