Add unit tests

Some small first unit tests for the common, module, at least.
This commit is contained in:
rugk 2018-09-01 13:48:43 +02:00
parent ba4b781c31
commit 6ea5a42819
No known key found for this signature in database
GPG key ID: 05D40A636AFAB34D
16 changed files with 394 additions and 28 deletions

View file

@ -41,6 +41,11 @@
}],
"no-var": 1,
"prefer-arrow-callback": 1,
"implicit-arrow-linebreak": 1,
"arrow-body-style": 1,
"arrow-parens": 1,
"arrow-spacing": 1,
"no-confusing-arrow": 1,
"prefer-rest-params": 2,
"prefer-spread": 2,
"prefer-template": 1,
@ -49,12 +54,13 @@
"object-shorthand": ["warn", "consistent-as-needed"],
"prefer-promise-reject-errors": 2,
/* "prefer-destructuring": 1, */ // https://github.com/eslint/eslint/issues/10250
"prefer-numeric-literals": 1,
// additional rules
"no-new-object": 2,
"eqeqeq": ["error", "smart"],
"curly": ["error", "all"],
"dot-location": 1,
"dot-location": ["error", "property"],
"dot-notation": 2,
"no-array-constructor": 2,
"no-throw-literal": 2,

1
.gitignore vendored
View file

@ -1 +1,2 @@
build/
node_modules/

12
.vscode/launch.json vendored Normal file
View file

@ -0,0 +1,12 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch addon",
"type": "firefox",
"request": "attach",
"addonType": "webExtension",
"addonPath": "${workspaceFolder}/src"
},
],
}

View file

@ -34,11 +34,9 @@ Developing/improving a WebExtension add-on is easy! **If you have ever made some
* **Debug extension:** Just visit `about:debugging` and load the extension by selecting any file from the Web Extensions' dir. In our case, e.g. select `manifest.json` from the `src` dir. [See a video here.](https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Your_first_WebExtension#Installing).
* **Change code:** When it is loaded you can just change the code (and press "Reload", if needed) and you'll see the result. That is it!
### Coding guidelines
If you use Visual Studio Code, you can use [the Firefox debugger](https://marketplace.visualstudio.com/items?itemName=hbenl.vscode-firefox-debug) to run it. Follow the instructions there, and start it with `F5`.
As for simple indentation issues, please refer to the [editorconfig file](.editorconfig). Just use a [plugin](http://editorconfig.org/#download), if needed, for your editor.
Apart from that, there are some simple rules.
If you have made your changes, please ensure that the unit tests still run. See [the section on testing](#tests) for the (easy) way to run them.
### General
* Do not introduce new unnecessary permissions. The add-on should require as few permissions as possible.
@ -47,7 +45,7 @@ Apart from that, there are some simple rules.
#### JS
* Use EcmaScript 2017. (so e.g. `await`/`async` are fine) Basically everything, which is supported by Firefox >= 57 can also be used.
* We use [ESLint](https://eslint.org/). Please do use it to lint your files. It specifies all coding guidelines.
* We use [ESLint](https://eslint.org/). Please do use it to lint your files. It specifies all coding guidelines. If you use NodeJS, you can install the packages `eslint` and (if you want to write unit tests) `eslint-plugin-mocha` (see [writing tests](#writing-tests)).
When something is not specified just use common sense and look at how other code in the project is written.
* Especially, as we use a [CSP](src/manifest.json), please do _not_:
* use inline JavaScript
@ -69,3 +67,29 @@ Apart from that, there are some simple rules.
### CSS
* Remember that [WebExtensions automatically](https://discourse.mozilla.org/t/add-ons-have-box-sizing-border-box-by-default/28359) have the CSS property [`box-sizing`](https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing) set to `border-box` instead of `content-box` as on the web.
### Tests
We use _Mocha_, _Chai_ and _Sinon_ for unit tests. However, you do not need to care for these insides if you just want to run them, as they are really easy to run:
* When your add-on is loaded in [`about:debugging`], click on "Manifest URL" next to the "Internal UUID".
* You'll see the `manifest.json`. Now change the address in the address bar to `moz-extension://<uuid here>/tests/index.html`. This is the test site, which then runs the tests automatically!
* You do not need to install anything, test libraries are downloaded from the web, automatically. If that does not work, you may have the wrong `manifest.json`, which does not allow loading of these test frameworks. Make sure you have the dev version ([`dev.json`](scripts/manifests/dev.json) in `scripts/manifests/`) loaded in the `src` dir of this add-on.
Tests are defined in the [`src/tests/`](src/tests/) dir.
Due to the fact that we use ES6 modules, [Mocha cannot yet run the tests on the command line](https://github.com/mochajs/mocha/issues/3006) though.
#### Writing tests
As for the Mocha tests, we do have [another EsLint config](src/tests/.eslintrc). To be able to use them, you should install the [EsLint mocha plugin](https://github.com/lo1tuma/eslint-plugin-mocha).
Here some simple rules:
* Do not describe tests as "should". This is superfluous, as we know that tests may behave correct or not. Just use the third-person present tense (e.g. `.it("does something useful")`). Describe the working test, not the error, if it fails.
* Use messages (often third parameter) in the assertions of chai, if useful. Here, describe the case, if it fails (e.g. "failed to do XY"), as these strings are only shown in case of an error.
* As for chai, write them [in the assert syntax](http://www.chaijs.com/api/assert/).
* Always use `.chai.assert.strictEqual` and not only `.equal` for comparison in tests, unless there is a specific reason, not to do so. This way, you also do not need to check for the variable type, yet again. Similarly usually prefer `.calledWithExactly` instead of `.calledWith`.
* If you need to attach/inject HTML code for your test into the HTML page, please use the `htmlMock.js` module provided in the test directory.
### Various stuff
* It is possible to use [symbolic links on Windows with git](https://stackoverflow.com/a/49913019/5008962). You have to make sure to enable that option at the installation of git for Windows and maybe need to re-clone the repo with `git clone -c core.symlinks=true <URL>`.

15
make.sh
View file

@ -1,15 +0,0 @@
#!/bin/sh
EXTENSION_NAME="mastodon-auto-remote-follow@rugk.github.io"
mkdir -p "build"
# license should be in add-on
mv LICENSE.md src/LICENSE.md
# create XPI
cd src || exit
zip -r -FS "../build/$EXTENSION_NAME.xpi" ./*
mv LICENSE.md ../LICENSE.md
cd ..

22
scripts/make.sh Executable file
View file

@ -0,0 +1,22 @@
#!/bin/sh
EXTENSION_NAME="mastodon-auto-remote-follow@rugk.github.io"
mkdir -p "build"
# license should be in add-on
mv LICENSE.md src/LICENSE.md
# make sure we are using the stable manifest
# as the dev edition manifest.json allows mocha.css and mocha.js in the CSP
cp "./scripts/manifests/firefox.json" "./src/manifest.json" || exit
# create zip
cd src || exit
zip -r -FS "../build/$EXTENSION_NAME.zip" ./* --exclude "tests/*"
# revert changes
mv LICENSE.md ../LICENSE.md
cp "../scripts/manifests/dev.json" "../src/manifest.json"
cd ..

View file

@ -0,0 +1,44 @@
{
"manifest_version": 2,
"name": "__MSG_extensionName__",
"short_name": "__MSG_extensionNameShort__",
"version": "0.7",
"author": "rugk",
"description": "__MSG_extensionDescription__",
"homepage_url": "https://github.com/rugk/mastodon-simplified-federation",
// testing version allows loading unit test libraries from CDNs
"content_security_policy": "default-src 'self'; connect-src https:; style-src 'self' https://unpkg.com; script-src 'self' https://unpkg.com",
"icons": {
"16": "icons/icon.svg",
"32": "icons/icon.svg",
"48": "icons/icon.svg",
"96": "icons/icon.svg"
},
"default_locale": "en",
"options_ui": {
"page": "options/options.html",
"browser_style": true
},
"background": {
"page": "background/background.html"
},
"permissions": [
"storage",
"tabs",
"webRequest",
"http://*/*",
"https://*/*"
],
"applications": {
"gecko": {
"id": "mastodon-auto-remote-follow@rugk.github.io",
"strict_min_version": "61.0"
}
}
}

View file

@ -0,0 +1,43 @@
{
"manifest_version": 2,
"name": "__MSG_extensionName__",
"short_name": "__MSG_extensionNameShort__",
"version": "0.7",
"author": "rugk",
"description": "__MSG_extensionDescription__",
"homepage_url": "https://github.com/rugk/mastodon-simplified-federation",
"content_security_policy": "default-src 'self'; connect-src https:",
"icons": {
"16": "icons/icon.svg",
"32": "icons/icon.svg",
"48": "icons/icon.svg",
"96": "icons/icon.svg"
},
"default_locale": "en",
"options_ui": {
"page": "options/options.html",
"browser_style": true
},
"background": {
"page": "background/background.html"
},
"permissions": [
"storage",
"tabs",
"webRequest",
"http://*/*",
"https://*/*"
],
"applications": {
"gecko": {
"id": "mastodon-auto-remote-follow@rugk.github.io",
"strict_min_version": "61.0"
}
}
}

View file

@ -1,5 +1,5 @@
// https://regex101.com/r/tZjwx7/1
const MASTODON_HANDLE_SPLIT = /^@?(.+)@(.*)$/;
// https://regex101.com/r/dlnnSq/1
const MASTODON_HANDLE_SPLIT = /^@?(.+)@(.+)$/;
/**
* Do a webfinger request for Mastodon account at server.
@ -12,9 +12,9 @@ const MASTODON_HANDLE_SPLIT = /^@?(.+)@(.*)$/;
*/
function getWebfinger(mastodonServer, mastodonHandle) {
// protcol specified HTTPS must be used
return fetch(new URL(`https://${mastodonServer}/.well-known/webfinger?resource=acct:${mastodonHandle}`)).then((response) => {
return response.json();
});
return fetch(new URL(`https://${mastodonServer}/.well-known/webfinger?resource=acct:${mastodonHandle}`)).then(
(response) => response.json()
);
}
/**
@ -22,11 +22,16 @@ function getWebfinger(mastodonServer, mastodonHandle) {
*
* @function
* @param {string} mastodonHandle
* @throws {TypeError}
* @returns {{username: string, server: string}} username/server
*/
export function splitUserHandle(mastodonHandle) {
const matches = MASTODON_HANDLE_SPLIT.exec(mastodonHandle);
if (matches === null) {
throw new TypeError("invalid Mastodon handle");
}
return {
username: matches[1],
server: matches[2]
@ -41,7 +46,7 @@ export function splitUserHandle(mastodonHandle) {
* @function
* @see https://github.com/tootsuite/mastodon/pull/8202
* @param {{username: string, server: string}} mastodon User handle split by splitUserHandle
* @param {string} uri a Mastodon hanlde (user account) to follow or toot URL
* @param {string} uri a Mastodon handle (user account) to follow or toot URL
* @param {boolean} [skipCache=false] set to true to ignore the cache
* @returns {Promise} resulting in String (URL)
*/

View file

@ -8,7 +8,8 @@
"description": "__MSG_extensionDescription__",
"homepage_url": "https://github.com/rugk/mastodon-simplified-federation",
"content_security_policy": "default-src 'self'; connect-src https:",
// testing version allows loading unit test libraries from CDNs
"content_security_policy": "default-src 'self'; connect-src https:; style-src 'self' https://unpkg.com; script-src 'self' https://unpkg.com",
"icons": {
"16": "icons/icon.svg",
"32": "icons/icon.svg",

51
src/tests/.eslintrc Normal file
View file

@ -0,0 +1,51 @@
{
// EsLint config for mocha tests
// requires EsLint mocha plugin: https://github.com/lo1tuma/eslint-plugin-mocha
"root": false,
"env": {
"browser": true,
"webextensions": true,
"es6": true,
"mocha": true
},
"plugins": [
"mocha"
],
"rules": {
// arrows are not allowed
"prefer-arrow-callback": 0,
// "mocha/prefer-arrow-callback": 2,
"mocha/no-mocha-arrows": 2,
// style
"mocha/max-top-level-suites": 1,
"mocha/valid-suite-description": ["warn", "^([a-zA-Z]+\\(.*\\)|[[A-Z0-9_]+|[\\w\\s:]+)( .*)?$", ["describe", "context", "suite"]], // function name or function call or header with :
// RegEx:for "valid-suite-description": https://regex101.com/r/MKJw59/6
"mocha/valid-test-description": ["warn", "^((?!should).)*$", ["it", "specify", "test"]], // must not contain "should", but should be third-person present tense
// RegEx for "valid-test-description": https://regex101.com/r/9gYH8f/1, thanks to https://stackoverflow.com/a/406408/5008962
// hooks
"mocha/no-hooks-for-single-case": 1,
// "mocha/no-hooks": 2,
// assyncronous tests
// "mocha/no-synchronous-tests": 2, // only
// common errors when writing tests
"mocha/no-global-tests": 2,
"mocha/handle-done-callback": 2,
"mocha/no-identical-title": 2,
"mocha/no-nested-tests": 2,
"mocha/no-return-and-callback": 2,
"mocha/no-setup-in-describe": 2,
"mocha/no-sibling-hooks": 2,
"mocha/no-top-level-hooks": 2,
// warnings to remind devs that there is something to do (debugging/…)
"mocha/no-skipped-tests": 1,
"mocha/no-exclusive-tests": 1,
// "mocha/no-pending-tests": 1,
}
}

View file

@ -0,0 +1,142 @@
import "https://unpkg.com/mocha@5.2.0/mocha.js"; /* globals mocha */
import "https://unpkg.com/chai@4.1.2/chai.js"; /* globals chai */
import "https://unpkg.com/sinon@6.1.5/pkg/sinon.js"; /* globals sinon */
import * as Mastodon from "/common/modules/Mastodon.js";
describe("common module: Mastodon", function () {
describe("splitUserHandle()", function () {
it('correctly splits "usual" valid handles', function () {
chai.assert.deepEqual(Mastodon.splitUserHandle("rugk_testing@mastodon.social"), {
username: "rugk_testing",
server: "mastodon.social"
}, 'does not handle correctly: "rugk_testing@mastodon.social"');
chai.assert.deepEqual(Mastodon.splitUserHandle("rugk@social.wiuwiu.de"), {
username: "rugk",
server: "social.wiuwiu.de"
}, 'does not handle correctly: "rugk@social.wiuwiu.de"');
chai.assert.deepEqual(Mastodon.splitUserHandle("FakeUser123Name@fake.example"), {
username: "FakeUser123Name",
server: "fake.example"
}, 'does not handle correctly: "FakeUser123Name@fake.example"');
});
it("correctly splits handles with @-prefix", function () {
chai.assert.deepEqual(Mastodon.splitUserHandle("@rugk_testing@mastodon.social"), {
username: "rugk_testing",
server: "mastodon.social"
}, 'does not handle correctly: "@rugk_testing@mastodon.social"');
chai.assert.deepEqual(Mastodon.splitUserHandle("@rugk@social.wiuwiu.de"), {
username: "rugk",
server: "social.wiuwiu.de"
}, 'does not handle correctly: "@rugk@social.wiuwiu.de"');
chai.assert.deepEqual(Mastodon.splitUserHandle("@FakeUser123Name@fake.example"), {
username: "FakeUser123Name",
server: "fake.example"
}, 'does not handle correctly: "FakeUser123Name@fake.example"');
});
it("correctly splits handles with Emoji", function () {
chai.assert.deepEqual(Mastodon.splitUserHandle("thinking🤔user@whatis🤔.great.app"), {
username: "thinking🤔user",
server: "whatis🤔.great.app"
}, 'does not handle correctly: "thinking🤔user@whatis🤔.great.app"');
chai.assert.deepEqual(Mastodon.splitUserHandle("@thinking🤔user@whatis🤔.great.app"), {
username: "thinking🤔user",
server: "whatis🤔.great.app"
}, 'does not handle correctly: "@thinking🤔user@whatis🤔.great.app"');
});
it("correctly rejects incorrect handles", function () {
chai.assert.throws(
Mastodon.splitUserHandle.bind(null, "rugk_testingmastodon.social"),
TypeError,
"invalid Mastodon handle",
'does not handle correctly: "rugk_testingmastodon.social"'
);
chai.assert.throws(
Mastodon.splitUserHandle.bind(null, "@rugk_testingmastodon.social"),
TypeError,
"invalid Mastodon handle",
'does not handle correctly: "@rugk_testingmastodon.social"'
);
chai.assert.throws(
Mastodon.splitUserHandle.bind(null, "rugk_testing@"),
TypeError,
"invalid Mastodon handle",
'does not handle correctly: "rugk_testing@"'
);
});
});
describe("getSubscribeApiUrl()", function () {
beforeEach(function() {
// TODO: mock settings API to prevent savings
});
afterEach(function() {
sinon.restore();
});
it("correctly queries webfinger", async function () {
const URI_STRING = "UNIQUE_URI_STRING@321478";
const windowMock = sinon.mock(window);
windowMock.expects("fetch")
.once()
.withArgs(new URL("https://mastodon.social/.well-known/webfinger?resource=acct:rugk_testing@mastodon.social"))
.resolves(new Response(JSON.stringify({
links: [
{
rel: "http://ostatus.org/schema/1.0/subscribe",
template: "https://mastodon.social/authorize_interaction?uri={uri}"
}
]
})));
await Mastodon.getSubscribeApiUrl({
username: "rugk_testing",
server: "mastodon.social"
}, URI_STRING, true);
windowMock.verify();
});
it("correctly returns OStatus subscribe URL with authorize_interaction", async function () {
const URI_STRING = "UNIQUE_URI_STRING@876876";
sinon.stub(window, "fetch").resolves(new Response(JSON.stringify({
links: [
{
rel: "http://ostatus.org/schema/1.0/subscribe",
template: "https://mastodon.social/authorize_interaction?uri={uri}"
}
]
})));
const returnedUrl = await Mastodon.getSubscribeApiUrl({
username: "rugk_testing",
server: "mastodon.social"
}, URI_STRING, true);
chai.assert.strictEqual(returnedUrl, `https://mastodon.social/authorize_interaction?uri=${URI_STRING}`);
});
it("correctly returns OStatus subscribe URL with authorize_follow", async function () {
const URI_STRING = "UNIQUE_URI_STRING@876876";
sinon.stub(window, "fetch").resolves(new Response(JSON.stringify({
links: [
{
rel: "http://ostatus.org/schema/1.0/subscribe",
template: "https://mastodon.social/authorize_follow?acct={uri}"
}
]
})));
const returnedUrl = await Mastodon.getSubscribeApiUrl({
username: "rugk_testing",
server: "mastodon.social"
}, URI_STRING, true);
chai.assert.strictEqual(returnedUrl, `https://mastodon.social/authorize_follow?acct=${URI_STRING}`);
});
});
});

18
src/tests/index.html Normal file
View file

@ -0,0 +1,18 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Mastodon Simplified Federation! Mocha Tests</title>
<link href="https://unpkg.com/mocha@5.2.0/mocha.css" rel="stylesheet" />
<link href="./index.css" rel="stylesheet" />
</head>
<body>
<div id="mocha"></div>
<div id="testArea">
</div>
<script type="module" src="setup.js"></script>
<script type="module" src="run.js"></script>
</body>
</html>

7
src/tests/run.js Normal file
View file

@ -0,0 +1,7 @@
import "https://unpkg.com/mocha@5.2.0/mocha.js"; /* globals mocha */
/* tests */
import "./CommonMastodon.test.js";
mocha.checkLeaks();
mocha.run();

4
src/tests/setup.js Normal file
View file

@ -0,0 +1,4 @@
import "https://unpkg.com/mocha@5.2.0/mocha.js"; /* globals mocha */
// import "./node_modules/sinon/pkg/sinon.js";
mocha.setup("bdd");

1
tests Symbolic link
View file

@ -0,0 +1 @@
src/tests