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

Дз «Тесты» — Шилов Максим #32

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"env": {
"browser": true,
"commonjs": true,
"es6": true,
"jquery": true
},
"rules": {
"no-unused-vars": [
0,
{
"vars": "all",
"args": "after-used"
}
],
"func-names": [
"error",
"never"
],
"no-console": "off",
"no-unused-expressions": [
2,
{
"allowShortCircuit": true,
"allowTernary": true
}
],
"no-undef": "off",
"no-plusplus": "off",
"consistent-return": "off",
"no-underscore-dangle": "off"
},
"extends": "airbnb-base"
}
7 changes: 6 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,6 @@
node_modules
node_modules
/.idea/
*.DS_Store
.nyc_output
coverage
hermione/screens
28 changes: 28 additions & 0 deletions .hermione.conf.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
module.exports = {
baseUrl: 'http://localhost:3000/',
// gridUrl: 'http://0.0.0.0:4444/wb/hub',
compositeImage: true,
sets: {
desktop: {
files: 'hermione/*.hermione.js'
}
},
browsers: {
chrome: {
desiredCapabilities: {
browserName: 'chrome'
}
},
firefox: {
desiredCapabilities: {
browserName: 'firefox'
}
},
},
plugins: {
'html-reporter/hermione': {
path: 'hermione-html-reporter',
},
'hermione-custom-commands': true,
},
};
52 changes: 52 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,57 @@
# Домашнее задание: автотесты
##Запуск
```
npm i
npm start
```
Запуск модульных тестов
```
npm run unit-tests
```
Запуск интеграционных тестов
```
npm run start-selenium
npm run integration-tests
```
##Модульные тесты
* Перед созданимем модульных тестов был произведен рефакторинг файлов git.js и navigation.js — функции были заменены на методы класса, в экспорт передается экземпляр класса и класс для тестов.
* В качестве логических блоков для модульных тестов были взяты:
* Обработка приходящих данных
* Получение истории коммитов — метод возвращает массив
* Получение списка файлов коммита — метод принимает хеш коммита и путь, возвращает массив файлов
* Преобразование строки в объект данных — метод принимает строку из истории коммитов, возвращает объект
* Формирование url навигации.
* Формирование url для файлов коммита — метод принимает хеш, возвращает url для текущего коммита
* Формирование url для директорий и файлов коммита — метод принимает хеш и директории коммита, обрабатывает исключения и возвращает url
* Формирование хлебных крошек — метод принимает хеш и путь, обрабатывает исключения, возвращает массив хлебных крошек

Тесты:
* tests/utils/git.test.js
* tests/utils/navigations.test.js

Для метода executeGit была написана заглушка (stub), т.к. он ссылается на внешнюю зависимость execFile. Метод gitFileContent не был протестирован т.к. он обращается на прямую к методу executeGit без каких-либо преобразований данных.

Для анализа покрытия тестами был использован istanbul

## Интеграционные тесты
* hermione/breadcrumbs.hermione.js
* hermione/layout.hermione.js
* hermione/screenshot.hermione.js
* hermione/url.hermione.js

Интеграционные тесты осуществляют тестирование:
* Вывод основных блоков (layout.hermione.js)
* Правильное отображение выводимых блоков (screenshot.hermione.js)
* Корректная работа хлебных крошек (breadcrumbs.hermione.js)
* Формирование и работа перехода по страницам (url.hermione.js)

Были написано 2 кастомные команды для Гермионы:
* assertExists — проверяет наличие селектора на странице
* assertUrl — проверяет соответствие текущего url с заданным

В .hermione.conf.js закомментировал gridUrl: 'http://0.0.0.0:4444/wb/hub', с ним почему-то сыпались ошибки

---
Вам дано приложение на JavaScript и нужно написать для него автотесты: интеграционные тесты на интерфейс и модульные тесты на серверную часть.

## Предметная область
Expand Down
6 changes: 3 additions & 3 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,14 @@ app.get('/files/:hash/*?', filesController);
app.get('/content/:hash/*?', contentController);

// error handlers
app.use(function(req, res, next) {
var err = new Error('Not Found');
app.use((req, res, next) => {
const err = new Error('Not Found');
err.status = 404;
next(err);
});

// error handler
app.use(function(err, req, res, next) {
app.use((err, req, res, next) => {
const { status = 500, message } = err;

// render the error page
Expand Down
23 changes: 12 additions & 11 deletions controllers/contentController.js
Original file line number Diff line number Diff line change
@@ -1,28 +1,29 @@
const { gitFileContent, gitFileTree } = require('../utils/git');
const { buildFolderUrl, buildBreadcrumbs } = require('../utils/navigation');
const { git } = require('../utils/git');
const { navigation } = require('../utils/navigation');

module.exports = function(req, res, next) {
module.exports = function (req, res, next) {
const { hash } = req.params;
const path = req.params[0].split('/').filter(Boolean);
const path = req.params[0].split('/')
.filter(Boolean);

gitFileTree(hash, path.join('/'))
.then(function([file]) {
git.gitFileTree(hash, path.join('/'))
.then(([file]) => {
if (file && file.type === 'blob') {
return gitFileContent(file.hash);
return git.gitFileContent(file.hash);
}
})
.then(
content => {
(content) => {
if (content) {
res.render('content', {
title: 'content',
breadcrumbs: buildBreadcrumbs(hash, path.join('/')),
content
breadcrumbs: navigation.buildBreadcrumbs(hash, path.join('/')),
content,
});
} else {
next();
}
},
err => next(err)
err => next(err),
);
};
28 changes: 12 additions & 16 deletions controllers/filesController.js
Original file line number Diff line number Diff line change
@@ -1,41 +1,37 @@
const { gitFileTree } = require('../utils/git');
const {
buildFolderUrl,
buildFileUrl,
buildBreadcrumbs
} = require('../utils/navigation');
const { git } = require('../utils/git');
const { navigation } = require('../utils/navigation');

function buildObjectUrl(parentHash, { path, type }) {
switch (type) {
case 'tree':
return buildFolderUrl(parentHash, path);
return navigation.buildFolderUrl(parentHash, path);
case 'blob':
return buildFileUrl(parentHash, path);
return navigation.buildFileUrl(parentHash, path);
default:
return '#';
}
}

module.exports = function(req, res, next) {
module.exports = function (req, res, next) {
const { hash } = req.params;
const pathParam = (req.params[0] || '').split('/').filter(Boolean);

const path = pathParam.length ? pathParam.join('/') + '/' : '';
const path = pathParam.length ? `${pathParam.join('/')}/` : '';

return gitFileTree(hash, path).then(
list => {
return git.gitFileTree(hash, path).then(
(list) => {
const files = list.map(item => ({
...item,
href: buildObjectUrl(hash, item),
name: item.path.split('/').pop()
name: item.path.split('/').pop(),
}));

res.render('files', {
title: 'files',
breadcrumbs: buildBreadcrumbs(hash, pathParam.join('/')),
files
breadcrumbs: navigation.buildBreadcrumbs(hash, pathParam.join('/')),
files,
});
},
err => next(err)
err => next(err),
);
};
18 changes: 9 additions & 9 deletions controllers/indexController.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
const { gitHistory } = require('../utils/git');
const { buildFolderUrl, buildBreadcrumbs } = require('../utils/navigation');
const { git } = require('../utils/git');
const { navigation } = require('../utils/navigation');

module.exports = function(req, res) {
gitHistory(1, 20).then(
history => {
module.exports = function (req, res) {
git.gitHistory(1, 20).then(
(history) => {
const list = history.map(item => ({
...item,
href: buildFolderUrl(item.hash, '')
href: navigation.buildFolderUrl(item.hash, ''),
}));

res.render('index', {
title: 'history',
breadcrumbs: buildBreadcrumbs(),
list
breadcrumbs: navigation.buildBreadcrumbs(),
list,
});
},
err => next(err)
err => next(err),
);
};
14 changes: 14 additions & 0 deletions hermione-custom-commands/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const assert = require('assert');

module.exports = (hermione, opts) => {
hermione.on(hermione.events.NEW_BROWSER, (browser) => {
browser.addCommand('assertExists', (selector, msg) => browser.isExisting(selector)
.then((exists) => {
assert.ok(exists, msg);
}));
browser.addCommand('assertUrl', (actual, message) => browser.getUrl()
.then((url) => {
if (url !== actual) assert.fail(actual, message);
}));
});
};
5 changes: 5 additions & 0 deletions hermione-custom-commands/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"name": "hermione-custom-commands",
"version": "1.0.0",
"main": "index.js"
}
2 changes: 2 additions & 0 deletions hermione-html-reporter/data.js

Large diffs are not rendered by default.

Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
10 changes: 10 additions & 0 deletions hermione-html-reporter/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<!DOCTYPE html>
<html>
<head>
<title>HTML report</title>
<meta charset="utf-8">
<link href="report.min.css" rel="stylesheet"></head>
<body class="report">
<div id="app"></div>
<script type="text/javascript" src="data.js"></script><script type="text/javascript" src="report.min.js"></script></body>
</html>
1 change: 1 addition & 0 deletions hermione-html-reporter/report.min.css

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

54 changes: 54 additions & 0 deletions hermione-html-reporter/report.min.js

Large diffs are not rendered by default.

Loading