Discourse 플러그인 개발 - 파트 6 - 인수 테스트 추가

이전 튜토리얼: Developing Discourse Plugins - Part 5 - Add an admin interface


Discourse에는 코드베이스를 위한 두 개의 대규모 테스트 스위트가 있다는 사실을 알고 계셨습니까? 서버 측에서는 Ruby 코드가 rspec를 사용하는 테스트 스위트를 갖추고 있습니다. 브라우저 애플리케이션의 경우, ember-testing을 포함하는 qunit 스위트를 가지고 있습니다.

개발 환경을 설정했다고 가정하면, http://localhost:3000/tests URL을 방문하면 브라우저에서 JavaScript 테스트 스위트가 실행됩니다. 재미있는 점은 화면 오른쪽 하단의 축소된 창에서 애플리케이션을 테스트하는 모습을 볼 수 있다는 것입니다:

Discourse 애플리케이션은 매우 많은 테스트로 구축되어 있으며, /tests URL을 방문하면 테스트가 실행됩니다. 따라서 작업 중인 플러그인으로 테스트를 필터링하면 유용할 수 있습니다. 인터페이스에서 Plugin 드롭다운을 클릭하고 플러그인을 선택하여 필터링할 수 있습니다:

플러그인에 인수 테스트 추가하기

먼저, Discourse의 최신 버전이 체크아웃되었는지 확인하세요. 플러그인에서 인수 테스트를 실행할 수 있는 기능은 비교적 새로운 기능이며, 최신 버전을 체크아웃하지 않으면 테스트가 표시되지 않습니다.

이 기사에서는 이 시리즈의 5부에서 작성한 purple-tentacle 플러그인에 대한 인수 테스트를 작성합니다.

인수 테스트를 추가하는 것은 플러그인에 파일을 하나 추가하는 것만큼 간단합니다. 다음 파일을 생성하세요:

test/javascripts/acceptance/purple-tentacle-test.js

import { acceptance, exists } from "discourse/tests/helpers/qunit-helpers";
import { click, visit } from "@ember/test-helpers";
import { test } from "qunit";

acceptance("Purple Tentacle", function (needs) {
  needs.settings({ purple_tentacle_enabled: true });
  needs.user();

  test("Purple tentacle button works", async function (assert) {
    await visit("/admin/plugins/purple-tentacle");
    assert.ok(exists("#show-tentacle"), "it shows the purple tentacle button");
    assert.ok(!exists(".tentacle"), "the tentacle is not shown yet");
    await click("#show-tentacle");
    assert.ok(exists(".tentacle"), "the tentacle wants to rule the world!");
  });
});

테스트를 명확하게 작성하려고 노력했지만, 인수 테스트를 이전에 작성해 본 적이 없다면 약간 혼란스러울 수 있습니다. 인수 테스트에 대한 훌륭한 정보가 많으므로 Ember 문서를 강력히 권장합니다.

작성하는 각 테스트에서는 assert를 통해 무언가를 검증해야 합니다. 우리 테스트에서는 tentacle이 처음에 숨겨져 있고 버튼을 클릭한 후에만 표시되는지 확인하기 위해 몇 가지 단언을 하고자 합니다.

단언이 이루어지기 전에 수행할 작업 세트를 정의해야 합니다. 이를 위해 await 키워드를 사용합니다. 이 키워드를 사용하면 각 비동기 헬퍼의 실행이 먼저 완료되도록 대기합니다.

중요한 첫 번째 작업은 await visit("/admin/plugins/purple-tentacle");입니다. 이는 테스트가 애플리케이션 내 해당 URL로 이동하도록 지시합니다. 해당 URL은 tentacle이 표시되는 URL이었습니다.

purple tentacle 버튼이 나타나는 페이지를 방문한 후, 페이지에 버튼이 존재하는지 확인하고 tentacle 이미지가 아직 존재하지 않는지 확인하고 싶습니다.

이는 다음 단언으로 수행됩니다:

assert.ok(exists("#show-tentacle"), "it shows the purple tentacle button");
assert.ok(!exists(".tentacle"), "the tentacle is not shown yet");

P.S. 이전 버전의 purple-tentacle 플러그인에는 handlebars 템플릿에 #show-tentacle 요소 id가 없었습니다. 따라 하기 위해 최신 버전을 확인하세요!

이러한 테스트가 통과되면 인터랙션을 테스트할 시간입니다.

다음 명령어는 await click('#show-tentacle');로, 테스트 프레임워크에게 버튼을 클릭하여 tentacle을 표시하고 싶다고 알립니다.

버튼을 클릭한 것을 시뮬레이션한 후, 다음을 단언하여 tentacle이 나타났는지 확인할 수 있습니다:

assert.ok(exists(".tentacle"), "the tentacle wants to rule the world!");

나쁘지 않죠? 개발 머신에서 http://localhost:3000/tests?target=purple-tentacle에 방문하여 직접 테스트를 실행해 볼 수 있습니다. 보라색 tentacle이 매우 빠르게 나타나고 모든 테스트가 통과하는 것을 볼 수 있습니다.

명령줄에서 플러그인 qunit 테스트를 실행하려면 다음을 실행하세요:

bin/qunit --target purple-tentacle

(개발 서버가 실행 중이 아닌 경우 --standalone 추가)

(purple-tentacle은 플러그인의 폴더 이름)

테스트 디버깅하기

플러그인을 작성하면서 테스트는 플러그인의 문제를 식별하는 데 도움이 될 수 있습니다. 테스트를 개발하거나 플러그인 코드를 변경하는 경우 테스트가 실패할 수 있습니다. 원인을 파악하기 위해 Ember에는 pauseTest() 및 resumeTest()라는 유용한 헬퍼가 있습니다.

이를 사용하려면 테스트가 일시 중지되기를 원하는 테스트 코드 내에서 await pauseTest()를 추가하세요. 이제 브라우저에서 테스트를 실행하면 pauseTest()를 추가한 지점에서 테스트가 자동으로 일시 중지됩니다. 이를 통해 페이지를 검사하거나 오류를 보고 문제를 디버깅할 수 있는 기회를 얻을 수 있습니다.

이제 어디로 가야 할까요?

반복되는 말처럼 들리는 것을 싫어하지만 Ember 문서의 테스트에 관한 내용은 훌륭합니다. Discourse가 다양한 기능을 어떻게 테스트하는지 보고 싶다면 javascript 테스트 디렉터리의 테스트를 탐색해 보세요. 그곳에서 배울 수 있는 매우 많은 예제가 있습니다.

즐거운 테스트 되세요!


시리즈의 나머지 부분

1부: 플러그인 기본
2부: 플러그인 아웃렛
3부: 사이트 설정
4부: git 설정
5부: 관리자 인터페이스
6부: 이 주제
7부: 플러그인 게시하기


이 문서는 버전 관리되고 있습니다 - github에서 변경 사항을 제안하세요.

30개의 좋아요

OMG, have I put off writing tests for this long?!

A few things
I noticed you put an “id” into the template file that wasn’t there in the previous tutorial
I added 3 more tests to deal with the “Hide Tentacle” button I added
I needed to be logged in it is an Admin page
I needed to use port 4000 for my VirtualBox Vagrant set-up

Happily, quick success !

5개의 좋아요

I’ve noticed a push to implement testing for plugins lately and I completely agree that this is important. I’ve been terrible at writing these in the past and want to get caught up.

I was considering the setup of Travis CI on a plugin repo as I noticed the ability to use Docker with Travis. But having never touched Travis before, is it possible to do this with a plugin? It would be nice to submit PRs to my own repo and have the tests run automatically.

5개의 좋아요

how can I run single ember tests on the browser?

http://localhost:3000/qunit?module=Acceptance%3A%20Purple%20Tentacle

I mean, if I have another acceptance test called “another test”, how would I run it? Thank you!

If you click “rerun” beside a test, you’ll get a URL that is just for that particular test that you can refresh over and over.

You can also run by module by clicking in the “All Module” box and checking off just the modules you want to run.

2개의 좋아요

This tutorial needs updating to replace ok(...) with assert.ok(...).

Have put the necessary changes in a PR - I’m happy to edit the OP if it’s made into a wiki :slight_smile:

https://github.com/eviltrout/purple-tentacle/pull/2

2개의 좋아요

OK it is wikified! PM me if anything else needs this treatment any time.

1개의 좋아요

A note after writing some basic acceptance tests for the Elections Plugin:

  • If you use the default loggedIn option, you’re logged in as eviltrout with the properties in this session fixture

  • You can login as a custom user (necessary if you’ve added custom user properties) by defining your own session fixture and setting it as the current user using the beforeEach hook. See here for an example.

@eviltrout is there a better way of using a custom user for acceptance tests?

5개의 좋아요

What we should probably do is change the acceptance method in discourse to take an argument for the user to log in as. Then your test could say { loggedIn: true, logInAs: angus }

If you’ve got time for that PR we’d accept it!

4개의 좋아요

q: how to run the ruby tests tests for a plugin?

i am trying to run the tests for discourse-github-linkback, but i have no idea how.

After some stackoverflow i tried this (and i got some errors):

~/discourse$ bundle exec rspec ./plugins/discourse-github-linkback/spec/lib/github_linkback_spec.rb 

An error occurred while loading ./plugins/discourse-github-linkback/spec/lib/github_linkback_spec.rb.
Failure/Error: CoreExt::ActiveSupport.without_bootsnap_cache { super }

NameError:
  uninitialized constant GithubLinkback
# ./plugins/discourse-github-linkback/spec/lib/github_linkback_spec.rb:3:in `<top (required)>'
# ------------------
# --- Caused by: ---
# NameError:
#   uninitialized constant GithubLinkback
#   ./plugins/discourse-github-linkback/spec/lib/github_linkback_spec.rb:3:in `<top (required)>'
No examples found.

Randomized with seed 60987


Finished in 0.02025 seconds (files took 3.36 seconds to load)
0 examples, 0 failures, 1 error occurred outside of examples

Randomized with seed 60987

Note that i see the plugin in the local discourse dev admin page, so i hope it is correctly installed (into ~discourse/plugins/

Simplest way, run bin/rake autospec, and save the file

1개의 좋아요

From what i see, doing cd ~/discourse and then running

runs all the tests for discourse.

On my ubuntu 18.04 VM with i5 6500, this has been running for half an hour already.
It feels wrong to run the whole tests suite when i only want to run the tests in that one plugin.
(this is especially so when i probably will modify my tests again, at least a few times)

Did i do something wrong?

Let me guess, you are symlinking your plugin vs checking out directly to the path under plugins

no,

tbp@tbp-linux-dev:~$ cd ~/discourse/plugins/
git clone -b allow-all-user-repositories-wildcard https://github.com/TheBestPessimist/discourse-github-linkback
tbp@tbp-linux-dev:~/discourse/plugins$ ll
total 40
drwxr-xr-x 10 tbp tbp 4096 May 13 21:48 ./
drwxr-xr-x 20 tbp tbp 4096 May 13 21:18 ../
drwxr-xr-x  6 tbp tbp 4096 May 13 20:29 discourse-details/
drwxr-xr-x  6 tbp tbp 4096 May 13 21:48 discourse-github-linkback/
drwxr-xr-x  6 tbp tbp 4096 May 13 20:29 discourse-local-dates/
drwxr-xr-x  9 tbp tbp 4096 May 13 20:29 discourse-narrative-bot/
drwxr-xr-x  7 tbp tbp 4096 May 13 20:29 discourse-nginx-performance-report/
drwxr-xr-x  5 tbp tbp 4096 May 13 20:29 discourse-presence/
drwxr-xr-x  3 tbp tbp 4096 May 13 20:29 lazyYT/
drwxr-xr-x  9 tbp tbp 4096 May 13 20:29 poll/
tbp@tbp-linux-dev:~/discourse/plugins$ 

Can you confirm you tried saving the spec file once it was running, cause it is meant to interrupt stuff and start running the plugin spec?

since the initial bin/rake autospec is still running, there was/is no “save spec file” message yet.
also, by running bin/rake autospec --help, i saw no --save option.

I didn’t understand what save the file meant, so my full command was bin/rake autospec > spec.rb ← probably this is wrong

I meant in Vim or whatever you use, save the spec file, there is a watcher on it that will invoke the spec runner once it is saved.

Also see: How do I run only discourse/plugins/poll/spec? - #6 by tgxworld

1개의 좋아요

Finally i did it :^).

With the help of that link, i ran the tests by using this command:
bundle exec rake plugin:spec["discourse-github-linkback"]
and, ofc, i was in ~/discourse when doing that.

Thanks for all your help @sam!

(1st PR for discourse-plugin babyyyyy :tada:)

8개의 좋아요

My Qunit-Tests aren’t executed or at least they don’t show me any output.
They finish with the following:

No output has been received in the last 10m0s, this potentially indicates a stalled build or something wrong with the build itself.
Check the details on how to adjust your build configuration on: https://docs.travis-ci.com/user/common-build-problems/#Build-times-out-because-no-output-was-received

Travis.CI Result - Travis CI
Test-File - GitHub - kokoro-ko/discourse-humble-box: humble-bundle onebox · GitHub

I am not that skilled with CI yet and haven’t found my mistake by now.

Do your tests pass if you visit /qunit on your development environment? How about if you run rake plugin:qunit[discouse-humble-box]?

2개의 좋아요