Skip to content

Commit

Permalink
Merge pull request #233 from vitkarpenko/linting
Browse files Browse the repository at this point in the history
ci(lint): added some basic linting and fixed warnings.
  • Loading branch information
vitkarpenko committed Nov 20, 2023
2 parents 6fb54da + 7203919 commit d7a2b27
Show file tree
Hide file tree
Showing 45 changed files with 1,180 additions and 944 deletions.
4 changes: 4 additions & 0 deletions .github/dependabot.yml
Expand Up @@ -5,3 +5,7 @@ updates:
directory: /
schedule:
interval: daily
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
25 changes: 25 additions & 0 deletions .github/workflows/golangci-lint.yml
@@ -0,0 +1,25 @@
name: golangci-lint
on:
push:
branches:
- master
- main
pull_request:

permissions:
contents: read

jobs:
golangci:
name: lint
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-go@v4
with:
go-version: "1.21"
cache: false
- name: golangci-lint
uses: golangci/golangci-lint-action@v3
with:
version: v1.55.1
61 changes: 61 additions & 0 deletions .golangci.yml
@@ -0,0 +1,61 @@
service:
golangci-lint-version: v1.55.1

run:
tests: false
skip-dirs:
- allure
- mocks
skip-files:
- ".*easyjson\\.go$"
output:
print-issued-lines: false

linters-settings:
lll:
line-length: 140
gocritic:
disabled-checks:
- hugeParam
enabled-tags:
- performance
- style
- experimental
gosec:
excludes:
- G204
- G306
stylecheck:
checks: ["all", "-ST1003", "-ST1016", "-ST1020", "-ST1021", "-ST1022"]
revive:
rules:
# Should be enabled after fixing underscore package names.
- name: var-naming
disabled: true

linters:
enable:
- bodyclose
- goconst
- gocritic
- gocyclo
- goimports
- revive
- goprintffuncname
- gosec
- gosimple
- govet
- ineffassign
- lll
- misspell
- nakedret
- nlreturn
- nolintlint
- rowserrcheck
- staticcheck
- stylecheck
- typecheck
- unconvert
- unparam
- unused
- gas
3 changes: 3 additions & 0 deletions Makefile
Expand Up @@ -24,3 +24,6 @@ build: @build

test:
go test ./...

lint:
docker run --rm -v $(PWD):/app -w /app golangci/golangci-lint:v1.55.1 golangci-lint run -v
29 changes: 19 additions & 10 deletions README-ru.md
Expand Up @@ -10,7 +10,7 @@ Gonkey протестирует ваши сервисы, используя их
- моки для имитации внешних сервисов
- можно подключить к проекту как библиотеку и запускать вместе с юнит-тестами
- запись результата тестов в виде отчета [Allure](http://allure.qatools.ru/)
- имеется [JSON-schema](#json-schema) для автодополнения и валидации YAML-файлов Gonkey
- имеется [JSON-schema](#json-schema) для автодополнения и валидации YAML-файлов Gonkey

## Содержание

Expand All @@ -26,6 +26,7 @@ Gonkey протестирует ваши сервисы, используя их
- [Из результатов предыдущего запроса](#из-результатов-предыдущего-запроса)
- [Из результата текущего запроса](#из-результата-текущего-запроса)
- [В переменных окружения или в env-файле](#в-переменных-окружения-или-в-env-файле)
- [В cases](#в-cases)
- [Загрузка файлов](#загрузка-файлов)
- [Фикстуры](#фикстуры)
- [Удаление данных из таблиц](#удаление-данных-из-таблиц)
Expand All @@ -50,6 +51,9 @@ Gonkey протестирует ваши сервисы, используя их
- [Описание ответа на запрос в Базу данных](#описание-ответа-на-запрос-в-базу-данных)
- [Параметризация при запросах в Базу данных](#параметризация-при-запросах-в-базу-данных)
- [Игнорирование порядка записей в ответе на запрос в базу данных](#игнорирование-порядка-записей-в-ответе-на-запрос-в-базу-данных)
- [JSON-schema](#json-schema)
- [Настройка на IDE Jetbrains](#настройка-на-ide-jetbrains)
- [Настройка на IDE VSCode](#настройка-на-ide-vscode)

## Использование консольной утилиты

Expand Down Expand Up @@ -691,6 +695,7 @@ tables:
Для хранилища Aerospike также поддерживается заливка тестовых данных. Для этого важно не забыть при запуске gonkey как CLI-приложение использовать флаг `-db-type aerospike`, а при использовании в качестве библиотеки в конфигурации раннера: `DbType: fixtures.Aerospike`.

Формат файлов с фикстурами для Aerospike отличается, но смысл остаётся прежним:

```yaml
sets:
set1:
Expand All @@ -714,6 +719,7 @@ sets:
```

Также поддерживаются шаблоны:

```yaml
templates:
base_tmpl:
Expand Down Expand Up @@ -1620,6 +1626,7 @@ Example:
### Формат описания запросов

Для описания запросов к БД в тесте, можно использовать legacy-формат:

```yaml
- name: my test
...
Expand All @@ -1631,6 +1638,7 @@ Example:
```

Но, более предпочтительным будет следующий формат:

```yaml
- name: my test
...
Expand Down Expand Up @@ -1759,25 +1767,25 @@ Example:
```

## JSON-schema

Для упрощения написания тестов на Gonkey, используйте [файл со схемой](https://raw.githubusercontent.com/lamoda/gonkey/master/gonkey.json)

Он добавляет in-line документацию и авто-дополнение в IDE которые это поддерживают.


Пример работы в IDE Jetbrains:
![Example Jetbrains](https://i.imgur.com/oYuPuR3.gif)

Пример работы в IDE VSCode:
![Example Jetbrains](https://i.imgur.com/hBIGjP9.gif)


### Настройка на IDE Jetbrains
Скачайте [файл со схемой](https://raw.githubusercontent.com/lamoda/gonkey/master/gonkey.json).

Скачайте [файл со схемой](https://raw.githubusercontent.com/lamoda/gonkey/master/gonkey.json).
В настройках Languages & Frameworks > Schemas and DTDs > JSON Schema Mappings

![Jetbrains IDE Settings](https://i.imgur.com/xkO22by.png)

Добавьте новую схему
Добавьте новую схему

![Add schema](https://i.imgur.com/XHw14GJ.png)

Expand All @@ -1789,7 +1797,7 @@ Example:

![Mapping](https://i.imgur.com/iFjm0Ld.png)

Выберите то что удобно для вас.
Выберите то что удобно для вас.

![Mapping pattern](https://i.imgur.com/WIK6sZW.png)

Expand All @@ -1803,7 +1811,7 @@ Example:

### Настройка на IDE VSCode

Для начала вам нужно установить плагин для работы с YAML
Для начала вам нужно установить плагин для работы с YAML
Откройте меню Code(File)->Preferences->Extensions

![VSCode Preferences](https://i.imgur.com/X7bk5Kh.png)
Expand All @@ -1813,15 +1821,16 @@ Example:
![Yaml Extension](https://i.imgur.com/57onioF.png)

Откройте меню Code(File)->Preferences->Settings
Наберите YAML:Schemas и нажмите на ссылку _Edit in settings.json_
Наберите YAML:Schemas и нажмите на ссылку *Edit in settings.json*
![Yaml link](https://i.imgur.com/IEwxWyG.png)

Добавьте маппинг файла и путь к схеме
Добавьте маппинг файла и путь к схеме

```
"yaml.schemas": {
"C:\\Users\\Leo\\gonkey.json": ["*.gonkey.yaml"]
}
```

В примере выше, схема из файла C:\Users\Leo\gonkey.json будет применяться ко всем файлам
В примере выше, схема из файла C:\Users\Leo\gonkey.json будет применяться ко всем файлам
с расширением .gonkey.yaml
30 changes: 18 additions & 12 deletions README.md
Expand Up @@ -28,6 +28,7 @@ Capabilities:
- [From the response of the previous test](#from-the-response-of-the-previous-test)
- [From the response of currently running test](#from-the-response-of-currently-running-test)
- [From environment variables or from env-file](#from-environment-variables-or-from-env-file)
- [From cases](#from-cases)
- [Files uploading](#files-uploading)
- [Fixtures](#fixtures)
- [Deleting data from tables](#deleting-data-from-tables)
Expand All @@ -52,6 +53,9 @@ Capabilities:
- [Definition of DB request response](#definition-of-db-request-response)
- [DB request parameterization](#db-request-parameterization)
- [Ignoring ordering in DB response](#ignoring-ordering-in-db-response)
- [JSON-schema](#json-schema)
- [Setup in Jetbrains IDE](#setup-in-jetbrains-ide)
- [Setup is VSCode IDE](#setup-is-vscode-ide)

## Using the CLI

Expand Down Expand Up @@ -133,7 +137,7 @@ func TestFuncCases(t *testing.T) {
}
```

Starts from version 1.18.3, externally written fixture loader may be used for loading test data, if gonkey used as a library.
Starts from version 1.18.3, externally written fixture loader may be used for loading test data, if gonkey used as a library.
To start using the custom loader, you need to import the custom module, that contains implementation of fixtures.Loader interface.

Example with a redis fixtures loader:
Expand Down Expand Up @@ -746,11 +750,11 @@ While using gonkey as a CLI application do not forget the flag `-db-type redis`.

List of supported data structures:

- Plain key/value
- Set
- Hash
- List
- ZSet (sorted set)
- Plain key/value
- Set
- Hash
- List
- ZSet (sorted set)

Fixture file example:

Expand Down Expand Up @@ -1622,6 +1626,7 @@ The response can contain several records. Those records are compared to the expe
### Test Format

You can use legacy style for run sql queries, like this:

```yaml
- name: my test
...
Expand All @@ -1633,6 +1638,7 @@ You can use legacy style for run sql queries, like this:
```

But, for now, already acceptable style is:

```yaml
- name: my test
...
Expand Down Expand Up @@ -1760,22 +1766,21 @@ Example:
```

## JSON-schema

Use [file with schema](https://raw.githubusercontent.com/lamoda/gonkey/master/gonkey.json) to add syntax highlight to your favourite IDE and write Gonkey tests more easily.

It adds in-line documentation and auto-completion to any IDE that supports it.



Example in Jetbrains IDE:
![Example Jetbrains](https://i.imgur.com/oYuPuR3.gif)

Example in VSCode IDE:
![Example Jetbrains](https://i.imgur.com/hBIGjP9.gif)


### Setup in Jetbrains IDE

Download [file with schema](https://raw.githubusercontent.com/lamoda/gonkey/master/gonkey.json).
Open preferences File->Preferences
Open preferences File->Preferences
In Languages & Frameworks > Schemas and DTDs > JSON Schema Mappings

![Jetbrains IDE Settings](https://i.imgur.com/xkO22by.png)
Expand Down Expand Up @@ -1817,14 +1822,15 @@ Look for YAML and install YAML Language Support by Red Hat

Open Settings by going to Code(File)->Preferences->Settings

Open Schema Settings by typing YAML:Schemas and click on _Edit in settings.json_
Open Schema Settings by typing YAML:Schemas and click on *Edit in settings.json*
![Yaml link](https://i.imgur.com/IEwxWyG.png)

Add file match to apply the JSON on YAML files.

```
"yaml.schemas": {
"C:\\Users\\Leo\\gonkey.json": ["*.gonkey.yaml"]
}
```

In the example above the JSON schema stored in C:\Users\Leo\gonkey.json will be applied on all the files that ends with .gonkey.yaml
In the example above the JSON schema stored in C:\Users\Leo\gonkey.json will be applied on all the files that ends with .gonkey.yaml
5 changes: 3 additions & 2 deletions checker/response_body/response_body.go
Expand Up @@ -32,13 +32,14 @@ func (c *ResponseBodyChecker) Check(t models.TestInterface, result *models.Resul
errs = append(errs, checkErrs...)
} else {
// compare bodies as leaf nodes
errs = append(errs, compare.Compare(expectedBody, result.ResponseBody, compare.CompareParams{})...)
errs = append(errs, compare.Compare(expectedBody, result.ResponseBody, compare.Params{})...)
}
}
if !foundResponse {
err := fmt.Errorf("server responded with status %d", result.ResponseStatusCode)
errs = append(errs, err)
}

return errs, nil
}

Expand All @@ -60,7 +61,7 @@ func compareJsonBody(t models.TestInterface, expectedBody string, result *models
return []error{errors.New("could not parse response")}, nil
}

params := compare.CompareParams{
params := compare.Params{
IgnoreValues: !t.NeedsCheckingValues(),
IgnoreArraysOrdering: t.IgnoreArraysOrdering(),
DisallowExtraFields: t.DisallowExtraFields(),
Expand Down

0 comments on commit d7a2b27

Please sign in to comment.