Skip to content

Commit

Permalink
Merge pull request #15 from ozontech/issue-12
Browse files Browse the repository at this point in the history
[v0.1.13] new release
  • Loading branch information
siller174 authored Jul 24, 2022
2 parents 4d7c1f6 + dd9d950 commit dbbed9e
Show file tree
Hide file tree
Showing 29 changed files with 543 additions and 261 deletions.
Binary file added .images/json_schema.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified .images/optional_error.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
54 changes: 35 additions & 19 deletions README.MD
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ Three steps for testing your HTTP service:
6. [Asserts](#asserts)
1. [JSON asserts](#asserts_json)
2. [Headers asserts](#asserts_headers)
3. [Custom asserts](#asserts_custom)
3. [JSON schema](#assert_json_schema)
4. [Custom asserts](#asserts_custom)
1. [Base](#asserts_custom_base)
2. [T](#asserts_custom_t)
3. [Errors](#assert_errors)
Expand Down Expand Up @@ -122,7 +123,6 @@ You can read about `Allure.Suite` [here](https://github.com/ozontech/allure-go/b
```go
import (
"github.com/ozontech/allure-go/pkg/framework/provider"

"github.com/ozontech/cute"
)

Expand Down Expand Up @@ -155,7 +155,6 @@ import (
)

func TestExampleTest(t *testing.T) {
t.Parallel()
suite.RunSuite(t, new(ExampleSuite))
}
```
Expand Down Expand Up @@ -227,20 +226,33 @@ You can create your own asserts or use ready-made asserts from the package asser

You can find implementation [here](asserts/json/json.go)

- **Equal** is a function to assert that a jsonpath expression matches the given value
- **NotEqual** is a function to check that jsonpath expression value is not equal to the given value
- **Length** is a function to assert that value is the expected length
- **GreaterThan** is a function to assert that value is greater than the given length
- **LessThan** is a function to assert that value is less than the given length
- **Present** is a function to assert that value is present
- **NotPresent** is a function to assert that value is not present
- `Equal` is a function to assert that a jsonpath expression matches the given value
- `NotEqual` is a function to check that jsonpath expression value is not equal to the given value
- `Length` is a function to assert that value is the expected length
- `GreaterThan` is a function to assert that value is greater than the given length
- `LessThan` is a function to assert that value is less than the given length
- `Present` is a function to assert that value is present (value can be 0 or null)
- `NotEmpty` is a function to assert that value is present and not empty (value can't be 0 or null)
- `NotPresent` is a function to assert that value is not present

### <a name="asserts_headers"/>Headers asserts:

See implementation [here](asserts/headers/headers.go)

- **Present** is a function to assert that header is present
- **NotPresent** is a function to assert that header is not present
- `Present` is a function to assert that header is present
- `NotPresent` is a function to assert that header is not present

### <a name="assert_json_schema"/>JSON schema validations:

There are three ways to validate a JSON Schema. It all depends on where you have it.

- `ExpectJSONSchemaString(string)` - is a function for compares a JSON schema from a string.
- `ExpectJSONSchemaByte([]byte)` - is a function for compares a JSON schema from an array of bytes.
- `ExpectJSONSchemaFile(string)` - is a function for compares a JSON schema from a file or remote resource.

**Allure:**

![img.png](.images/json_schema.png)

## <a name="asserts_custom"/>Custom asserts

Expand Down Expand Up @@ -285,7 +297,7 @@ type AssertResponseT func(t cute.T, response *http.Response) error
**Example with T:**

```go
func customAssertBodyTB() cute.AssertBodyT {
func customAssertBodyT() cute.AssertBodyT {
return func(t cute.T, bytes []byte) error {
require.GreaterOrEqual(t, len(bytes), 100)
return nil
Expand Down Expand Up @@ -343,17 +355,20 @@ func customAssertBodyWithCustomError() cute.AssertBody {
If you'd like to create a pretty **error in your custom** assert you should implement error with [interfaces](errors/error.go):

##### With name

```go
type WithNameError interface {
GetName() string
SetName(string)
}
```

#### With actual and expected values
#### With parameters for allure step

```go
type ExpectedError interface {
GetActual() interface{}
GetExpected() interface{}
type WithFields interface {
GetFields() map[string]interface{}
PutFields(map[string]interface{})
}
```

Expand All @@ -375,7 +390,7 @@ import (
func customAssertBodyWithCustomError() cute.AssertBody {
return func(bytes []byte) error {
if len(bytes) == 0 {
return errors.NewOptionalError(fmt.Errorf("body is empty"))
return errors.NewOptionalError("body is empty")
}

return nil
Expand All @@ -388,11 +403,12 @@ To create optional error you should implement error with interface
```go
type OptionalError interface {
IsOptional() bool
SetOptional()
SetOptional(bool)
}
```

**Allure:**

![optional_error.png](.images/optional_error.png)

## <a name="global_env_keys"/>Global Environment Keys
Expand Down
6 changes: 3 additions & 3 deletions assert.go
Original file line number Diff line number Diff line change
Expand Up @@ -163,10 +163,10 @@ func wrapOptionalError(err error) error {
}

if tErr, ok := err.(errors.OptionalError); ok {
tErr.SetOptional()
tErr.SetOptional(true)

return err
return tErr.(error)
}

return errors.NewOptionalError(err)
return errors.NewOptionalError(err.Error())
}
10 changes: 10 additions & 0 deletions asserts/json/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,23 @@ func LessThan(expression string, maximumLength int) cute.AssertBody {
}

// Present is a function to asserts that value is present
// value can be nil or 0
// About expression - https://goessner.net/articles/JsonPath/
func Present(expression string) cute.AssertBody {
return func(body []byte) error {
return present(body, expression)
}
}

// NotEmpty is a function to asserts that value is present
// value can't be nil or 0
// About expression - https://goessner.net/articles/JsonPath/
func NotEmpty(expression string) cute.AssertBody {
return func(body []byte) error {
return notEmpty(body, expression)
}
}

// NotPresent is a function to asserts that value is not present
// About expression - https://goessner.net/articles/JsonPath/
func NotPresent(expression string) cute.AssertBody {
Expand Down
76 changes: 76 additions & 0 deletions asserts/json/json_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,24 @@ func TestPresent(t *testing.T) {
data: `{"o":["a", "b", "c"]}`,
expression: "$.not_correct",
},
{
caseName: "empty integer",
data: `{"o":0}`,
expression: "$.o",
IsNilErr: true,
},
{
caseName: "empty object",
data: `{"o":null}`,
expression: "$.o",
IsNilErr: true,
},
{
caseName: "empty string",
data: `{"o":null, "b":""}`,
expression: "$.b",
IsNilErr: true,
},
}

for _, test := range tests {
Expand All @@ -93,6 +111,64 @@ func TestPresent(t *testing.T) {
}
}

func TestNotEmpty(t *testing.T) {
tests := []jsonTest{
{
caseName: "correct check array",
data: `{"o":["a", "b", "c"]}`,
expression: "$.o",
IsNilErr: true,
},
{
caseName: "not present check",
data: `{"o":["a", "b", "c"]}`,
expression: "$.b",
},
{
caseName: "correct present check array",
data: `{"o":["a", "b", "c"]}`,
expression: "$.o[0]",
IsNilErr: true,
},
{
caseName: "correct check map",
data: `{"o":[{"1":"a"}, {"2":"b"}, {"3":"c"}]}`,
expression: "$.o[0][1]",
IsNilErr: true,
},
{
caseName: "check not correct path",
data: `{"o":["a", "b", "c"]}`,
expression: "$.not_correct",
},
{
caseName: "empty integer",
data: `{"o":0}`,
expression: "$.o",
},
{
caseName: "empty object",
data: `{"o":null}`,
expression: "$.o",
},
{
caseName: "empty string",
data: `{"o":null, "b":""}`,
expression: "$.b",
},
}

for _, test := range tests {
err := NotEmpty(test.expression)([]byte(test.data))

if test.IsNilErr {
require.NoError(t, err, "failed test %v", test.caseName)
} else {
require.Error(t, err, "failed test %v", test.caseName)
}
}
}

func TestLength(t *testing.T) {
tests := []jsonTest{
{
Expand Down
17 changes: 15 additions & 2 deletions asserts/json/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,12 +107,25 @@ func lessThan(data []byte, expression string, maximumLength int) error {
return nil
}

// Present is a function to asserts that value is present
// notEmpty is a function to asserts that value is not empty (!= 0, != null)
// About expression - https://goessner.net/articles/JsonPath/
func present(data []byte, expression string) error {
func notEmpty(data []byte, expression string) error {
value, _ := GetValueFromJSON(data, expression)
if isEmpty(value) {
return errors.NewAssertError("NotEmpty", fmt.Sprintf("on path %v. value is not present", expression), nil, nil)
}

return nil
}

// Present is a function to asserts that value is present
// value can be 0 or null
// About expression - https://goessner.net/articles/JsonPath/
func present(data []byte, expression string) error {
_, err := GetValueFromJSON(data, expression)
if err != nil {
return errors.NewAssertError("Present", fmt.Sprintf("on path %v. value not present", expression), nil, nil)

}

return nil
Expand Down
22 changes: 18 additions & 4 deletions builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ func NewHTTPTestMaker(opts ...Option) *HTTPTestMaker {
}

httpClient := &http.Client{
Transport: newAllureRoundTripper(roundTripper),
Transport: roundTripper,
Timeout: timeout,
}

Expand All @@ -89,9 +89,11 @@ func (m *HTTPTestMaker) NewTestBuilder() AllureBuilder {
allureLinks: new(allureLinks),
allureLabels: new(allureLabels),
middleware: new(middleware),
request: new(request),
expect: new(expect),
parallel: false,
request: &request{
repeat: new(requestRepeatPolitic),
},
expect: new(expect),
parallel: false,
}
}

Expand Down Expand Up @@ -257,6 +259,18 @@ func (it *test) AfterExecuteT(fs ...AfterExecuteT) Middleware {
return it
}

func (it *test) RequestRepeat(count int) RequestHTTPBuilder {
it.request.repeat.count = count

return it
}

func (it *test) RequestRepeatDelay(delay time.Duration) RequestHTTPBuilder {
it.request.repeat.delay = delay

return it
}

func (it *test) Request(r *http.Request) ExpectHTTPBuilder {
it.request.base = r

Expand Down
16 changes: 16 additions & 0 deletions builder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ func TestHTTPTestMaker(t *testing.T) {
label = allure.Label{"kek", "lol"}
setIssue = "SetIssue"
setTestCase = "SetTestCase"
repeatCount = 10
repeatDelay = time.Duration(10)
link = allure.Link{
Name: "link",
Type: "type",
Expand Down Expand Up @@ -131,6 +133,8 @@ func TestHTTPTestMaker(t *testing.T) {
Description(desc).
CreateWithStep().
StepName(stepName).
RequestRepeat(repeatCount).
RequestRepeatDelay(repeatDelay).
Request(req).
ExpectExecuteTimeout(executeTime).
ExpectStatus(status).
Expand Down Expand Up @@ -170,6 +174,8 @@ func TestHTTPTestMaker(t *testing.T) {
require.Equal(t, setIssue, resHt.allureLinks.issue)
require.Equal(t, setTestCase, resHt.allureLinks.testCase)
require.Equal(t, link, resHt.allureLinks.link)
require.Equal(t, repeatCount, resHt.request.repeat.count)
require.Equal(t, repeatDelay, resHt.request.repeat.delay)

require.Equal(t, len(assertHeaders), len(resHt.expect.assertHeaders))
require.Equal(t, len(assertHeadersT), len(resHt.expect.assertHeadersT))
Expand All @@ -195,12 +201,22 @@ func TestCreateHTTPTestMakerWithHttpClient(t *testing.T) {
require.Equal(t, time.Duration(100), maker.httpClient.Timeout)
}

type rt struct {
}

func (r *rt) RoundTrip(*http.Request) (*http.Response, error) {
return nil, nil
}

func TestCreateHTTPMakerOps(t *testing.T) {
timeout := time.Second * 100
roundTripper := &rt{}

maker := NewHTTPTestMaker(
WithCustomHTTPTimeout(timeout),
WithCustomHTTPRoundTripper(roundTripper),
)

require.Equal(t, timeout, maker.httpClient.Timeout)
require.Equal(t, roundTripper, maker.httpClient.Transport)
}
Loading

0 comments on commit dbbed9e

Please sign in to comment.