cute

package module
v1.1.21 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 17, 2024 License: Apache-2.0 Imports: 22 Imported by: 1

README

cute

CUTE — create your tests easily

HTTP and REST API testing for Go.

Three steps for testing your HTTP service:

  1. Create request and write assets
  2. Run tests
  3. Check allure

Head of contents:

  1. Head of contents
  2. Installation
  3. Features
  4. Demo
  5. Examples
    1. Single test with Allure
    2. Suite tests
    3. Multi-step test
    4. Table tests
      1. Builder
      2. Array
  6. Asserts
    1. JSON asserts
    2. Headers asserts
    3. JSON schema
    4. Custom asserts
      1. Base
      2. T
      3. Errors
  7. Global Environment Keys

Installation

  go get -u github.com/ozontech/cute

Requirements

  • Go 1.17+

Features

  • Full integration with Allure
  • Expressive and intuitive syntax
  • Built-in JSON support
  • Custom asserts
  • One step to BDD

Demo

  1. Install allure
  brew install allure
  1. Run example
 make example
  1. Run allure
  allure serve ./examples/allure-results

Examples

See examples directory for featured examples.

Single test

See an example of creating a single test.
For a result with allure information you can use testing.T or provider.T from allure-go.

import (
    "context"
    "net/http"
    "path"
    "testing"
    "time"

    "github.com/ozontech/cute"
    "github.com/ozontech/cute/asserts/json"
)

func TestExample(t *testing.T) {
    cute.NewTestBuilder().
        Title("Title").
        Description("some_description").
        Create().
        RequestBuilder(
            cute.WithURI("https://jsonplaceholder.typicode.com/posts/1/comments"),
            cute.WithMethod(http.MethodGet),
        ).
        ExpectExecuteTimeout(10*time.Second).
        ExpectStatus(http.StatusOK).
        AssertBody(
            json.Equal("$[0].email", "Eliseo@gardner.biz"),
            json.Present("$[1].name"),
        ).
        ExecuteTest(context.Background(), t)
}

See full example here

Allure:

img.png

Suite

Suite provides a structure in which you can describe tests by grouping them into test suites. This can be useful if you have a lot of different tests and it is difficult to navigate through them without having additional "layers nesting levels" of test calls.

You can read about Allure.Suite here

  1. Declare a structure with suite.Suite and *cute.HTTPTestMaker
import (
    "github.com/ozontech/cute"
    "github.com/ozontech/allure-go/pkg/framework/provider"
    "github.com/ozontech/allure-go/pkg/framework/suite"
)

type ExampleSuite struct {
    suite.Suite
    host *url.URL

    testMaker *cute.HTTPTestMaker
}

func (i *ExampleSuite) BeforeAll(t provider.T) {
    // Prepare http test builder
    i.testMaker = cute.NewHTTPTestMaker()

    // Preparing host
    host, err := url.Parse("https://jsonplaceholder.typicode.com/")
    if err != nil {
        t.Fatalf("could not parse url, error %v", err)
    }

    i.host = host
}

  1. Declare test
import (
    "github.com/ozontech/allure-go/pkg/framework/suite"
)

func TestExampleTest(t *testing.T) {
    suite.RunSuite(t, new(ExampleSuite))
}
  1. Just relax and describe tests
import (
    "github.com/ozontech/cute"
    "github.com/ozontech/cute/asserts/headers"
    "github.com/ozontech/cute/asserts/json"
)

func (i *ExampleSuite) TestExample_OneStep(t provider.T) {
    var (
        testBuilder = i.testMaker.NewTestBuilder()
    )
    
    u, _ := url.Parse(i.host.String())
    u.Path = path.Join(u.Path, "/posts/1/comments")
    
    testBuilder.
        Title("TestExample_OneStep").
        Tags("one_step", "some_local_tag", "json").
        Create().
        StepName("Example GET json request").
        RequestBuilder(
            cute.WithHeaders(map[string][]string{
                "some_header":       []string{"something"},
                "some_array_header": []string{"1", "2", "3", "some_thing"},
            }),
            cute.WithURL(u),
            cute.WithMethod(http.MethodGet),
        ).
        ExpectExecuteTimeout(10*time.Second).
        ExpectJSONSchemaFile("file://./resources/example_valid_request.json").
        ExpectStatus(http.StatusOK).
        AssertBody(
            json.Equal("$[0].email", "Eliseo@gardner.biz"),
            json.Present("$[1].name"),
            json.NotPresent("$[1].some_not_present"),
            json.GreaterThan("$", 3),
            json.Length("$", 5),
            json.LessThan("$", 100),
            json.NotEqual("$[3].name", "kekekekeke"),
        ).
        OptionalAssertBody(
            json.GreaterThan("$", 3),
            json.Length("$", 5),
            json.LessThan("$", 100),
        ).
        AssertHeaders(
            headers.Present("Content-Type"),
        ).
        ExecuteTest(context.Background(), t)
}

See full example here

Allure:

one_step.png

Multi-step test

import (
    "context"
    "fmt"
    "net/http"
    "testing"

    "github.com/ozontech/cute"
)
    
func Test_TwoSteps(t *testing.T) {
    responseCode := 0

    // First step.
    cute.NewTestBuilder().
        Title("Test with two requests and parse body.").
        Tag("two_steps").
        Create().
        RequestBuilder(
            cute.WithURI("https://jsonplaceholder.typicode.com/posts/1/comments"),
            cute.WithMethod(http.MethodGet),
        ).
        ExpectStatus(http.StatusOK).
        NextTest().

        // Execute after first step and parse response code
        AfterTestExecute(func(response *http.Response, errors []error) error { 
            responseCode = response.StatusCode

            return nil
        }).

        // Second step
        Create().
        RequestBuilder(
            cute.WithURI("https://jsonplaceholder.typicode.com/posts/2/comments"),
            cute.WithMethod(http.MethodDelete),
        ).
        ExecuteTest(context.Background(), t)

        fmt.Println("Response code from first request", responseCode)
}

See full example here

Allure:

multistep_test.png

Table tests

One step to table tests...

You have 2 ways to create table test. These ways have same allure reports.

Builder table tests
import (
    "context"
    "fmt"
    "net/http"
    "testing"

    "github.com/ozontech/cute"
)

func Test_Table_Array(t *testing.T) {
    tests := []*cute.Test{
        {
            Name:       "test_1",
            Middleware: nil,
            Request: &cute.Request{
                Builders: []cute.RequestBuilder{
                    cute.WithURI("https://jsonplaceholder.typicode.com/posts/1/comments"),
                    cute.WithMethod(http.MethodPost),
                },
            },
            Expect: &cute.Expect{
                Code: 200,
            },
        },
        {
            Name:       "test_2",
            Middleware: nil,
            Request: &cute.Request{
                Builders: []cute.RequestBuilder{
                    cute.WithURI("https://jsonplaceholder.typicode.com/posts/1/comments"),
                    cute.WithMethod(http.MethodGet),
                },
            },
            Expect: &cute.Expect{
                Code: 200,
                AssertBody: []cute.AssertBody{
                    json.Equal("$[0].email", "Eliseo@gardner.biz"),
                    json.Present("$[1].name"),
                    func(body []byte) error {
                        return errors.NewAssertError("example error", "example message", nil, nil)
                    },
                },
            },
        },
    }

    cute.NewTestBuilder().
        Title("Example table test").
        Tag("table_test").
        Description("Execute array tests").
        CreateTableTest().
        PutTests(tests...).
        ExecuteTest(context.Background(), t)
}
Array tests
func Test_Execute_Array(t *testing.T) {
    tests := []*cute.Test{
        {
            Name:       "test_1",
            Middleware: nil,
            Request: &cute.Request{
                Builders: []cute.RequestBuilder{
                    cute.WithURI("https://jsonplaceholder.typicode.com/posts/1/comments"),
                    cute.WithMethod(http.MethodPost),
                },
            },
            Expect: &cute.Expect{
                Code: 200,
            },
        },
        {
            Name:       "test_2",
            Middleware: nil,
            Request: &cute.Request{
                Builders: []cute.RequestBuilder{
                    cute.WithURI("https://jsonplaceholder.typicode.com/posts/1/comments"),
                    cute.WithMethod(http.MethodGet),
                },
            },
            Expect: &cute.Expect{
                Code: 200,
                AssertBody: []cute.AssertBody{
                    json.Equal("$[0].email", "Eliseo@gardner.biz"),
                    json.Present("$[1].name"),
                    func(body []byte) error {
                        return errors.NewAssertError("example error", "example message", nil, nil)
                    },
                },
            },
        },
    }

    for _, test := range tests {
        test.Execute(context.Background(), t)
    }
}

See full example here

Common allure for all table tests:

Report has 2 different tests/suites:

table_tests_execute_array.png

Main report:

table_tests_execute_array_test_1.png

Asserts

You can create your own asserts or use ready-made asserts from the package asserts

JSON asserts:

You can find implementation here

  • 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
  • GreaterOrEqualThan is a function to assert that value is greater or equal than the given length
  • LessThan is a function to assert that value is less than the given length
  • LessOrEqualThan is a function to assert that value is less or equal 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
Headers asserts:

See implementation here

  • Present is a function to assert that header is present
  • NotPresent is a function to assert that header is not present
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

Custom asserts

You can implement 3 type of asserts:

Base

Types for creating custom assertions.

    type AssertBody func(body []byte) error
    type AssertHeaders func(headers http.Header) error
    type AssertResponse func(response *http.Response) error

Example:

func customAssertBody() cute.AssertBody {
    return func(bytes []byte) error {
        if len(bytes) == 0 {
            return errors.New("response body is empty")
        }
        
        return nil
    }
}
T

Types for creating custom assertions using Allure Actions and testing.TB.
You can log some information to Allure.
Also you can log error on Allure yourself or just return error.

    type AssertBodyT func(t cute.T, body []byte) error
    type AssertHeadersT func(t cute.T, headers http.Header) error
    type AssertResponseT func(t cute.T, response *http.Response) error

Example with T:

func customAssertBodyT() cute.AssertBodyT {
    return func(t cute.T, bytes []byte) error {
        require.GreaterOrEqual(t, len(bytes), 100)
        return nil
    }
}

Example with step creations:

func customAssertBodySuite() cute.AssertBodyT {
    return func(t cute.T, bytes []byte) error {
        step := allure.NewSimpleStep("Custom assert step")
        defer func() {
            t.Step(step)
        }()

        if len(bytes) == 0 {
            step.Status = allure.Failed
            step.Attachment(allure.NewAttachment("Error", allure.Text, []byte("response body is empty")))

            return nil
        }

        return nil
    }
}

Allure:

custom_assert.png

Assert errors

You can use method errors.NewAssertError from package errors:

Example:

import (
    "github.com/ozontech/cute"
    "github.com/ozontech/cute/errors"
)

func customAssertBodyWithCustomError() cute.AssertBody {
    return func(bytes []byte) error {
        if len(bytes) == 0 {
            return errors.NewAssertError("customAssertBodyWithCustomError", "body must be not empty", "len is 0", "len more 0")
        }

        return nil
    }
}

If you'd like to create a pretty error in your custom assert you should implement error with interfaces:

With name
type WithNameError interface {
    GetName() string
    SetName(string)
}
With parameters for allure step
type WithFields interface {
    GetFields() map[string]interface{}
    PutFields(map[string]interface{})
}

Allure:

assert_error.png

Optional assert

If assert returns optional error step will be failed but test will be success.

You can use method errors.NewOptionalError(error) from package errors:

import (
    "github.com/ozontech/cute"
    "github.com/ozontech/cute/errors"
)

func customAssertBodyWithCustomError() cute.AssertBody {
    return func(bytes []byte) error {
        if len(bytes) == 0 {
            return errors.NewOptionalError("body is empty")
        }

        return nil
    }
}

To create optional error you should implement error with interface

type OptionalError interface {
    IsOptional() bool
    SetOptional(bool)
}

Allure:

optional_error.png

Global Environment Keys

Key Meaning Default
ALLURE_OUTPUT_PATH Path to output allure results . (Folder with tests)
ALLURE_OUTPUT_FOLDER Name result folder /allure-results
ALLURE_ISSUE_PATTERN Url pattepn to issue. Must contain %s
ALLURE_TESTCASE_PATTERN URL pattern to TestCase. Must contain %s.
ALLURE_LAUNCH_TAGS Default tags for all tests. Tags must be separated by commas.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func WithBody

func WithBody(body []byte) func(o *requestOptions)

WithBody is a function for set body in request

func WithFileForm added in v0.1.10

func WithFileForm(fileForms map[string]*File) func(o *requestOptions)

WithFileForm is a function for set file form in request

func WithFileFormKV added in v0.1.10

func WithFileFormKV(name string, file *File) func(o *requestOptions)

WithFileFormKV is a function for set file form in request

func WithForm added in v0.1.10

func WithForm(forms map[string][]byte) func(o *requestOptions)

WithForm is a function for set body in form request

func WithFormKV added in v0.1.10

func WithFormKV(name string, body []byte) func(o *requestOptions)

WithFormKV is a function for set body in form request

func WithHeaders

func WithHeaders(headers map[string][]string) func(o *requestOptions)

WithHeaders is a function for set or merge headers in request

func WithHeadersKV added in v0.1.10

func WithHeadersKV(name string, value string) func(o *requestOptions)

WithHeadersKV is a function for set headers in request

func WithMarshalBody

func WithMarshalBody(body interface{}) func(o *requestOptions)

WithMarshalBody is a function for marshal body and set body in request

func WithMethod

func WithMethod(method string) func(o *requestOptions)

WithMethod is a function for set method (GET, POST ...) in request

func WithQuery added in v0.1.11

func WithQuery(queries map[string][]string) func(o *requestOptions)

WithQuery is a function for set or merge query parameters in request

func WithQueryKV added in v0.1.11

func WithQueryKV(name string, value string) func(o *requestOptions)

WithQueryKV is a function for set query in request

func WithURI

func WithURI(uri string) func(o *requestOptions)

WithURI is a function for set url in request

func WithURL

func WithURL(url *url.URL) func(o *requestOptions)

WithURL is a function for set url in request

Types

type After added in v0.1.9

type After interface {
	// After is function for processing response after test execution
	After(...AfterExecute) ExpectHTTPBuilder
	// AfterT is function for processing response after test execution
	AfterT(...AfterExecuteT) ExpectHTTPBuilder
}

After are functions for processing response after test execution Same functions: AfterText AfterTestExecute

type AfterExecute

type AfterExecute func(*http.Response, []error) error

AfterExecute is a function for processing response after test execution

type AfterExecuteT

type AfterExecuteT func(T, *http.Response, []error) error

AfterExecuteT is a function for processing response after test execution

type AfterTest added in v0.1.6

type AfterTest interface {
	// AfterExecute is function for processing response after test execution
	AfterExecute(...AfterExecute) MiddlewareRequest
	// AfterExecuteT is function for processing response after test execution
	AfterExecuteT(...AfterExecuteT) MiddlewareRequest
}

AfterTest are functions for processing response after test execution Same functions: After AfterTestExecute

type AfterTestExecute added in v0.1.9

type AfterTestExecute interface {
	// AfterTestExecute is function for processing response after test execution
	AfterTestExecute(...AfterExecute) NextTestBuilder
	// AfterTestExecuteT is function for processing response after test execution
	AfterTestExecuteT(...AfterExecuteT) NextTestBuilder
}

AfterTestExecute are functions for processing response after test execution Same functions: After AfterText

type AllureBuilder

type AllureBuilder interface {
	AllureInfoBuilder
	AllureLabelsBuilder
	AllureLinksBuilder

	CreateBuilder

	// Parallel signals that this Test is to be run in parallel with (and only with) other parallel tests.
	// This function is not thread save. If you use multiply parallel with one T Test will panic.
	Parallel() AllureBuilder
}

AllureBuilder is a scope of methods for create allure information (Title, Tags, etc.)

func NewTestBuilder

func NewTestBuilder() AllureBuilder

NewTestBuilder is function for create base test builder, For create custom test builder use NewHTTPTestMaker()

type AllureInfoBuilder

type AllureInfoBuilder interface {
	// Title is a function for set title in allure information
	Title(title string) AllureBuilder
	Titlef(format string, args ...interface{}) AllureBuilder
	// Description is a function for set description in allure information
	Description(description string) AllureBuilder
	Descriptionf(format string, args ...interface{}) AllureBuilder
	Stage(stage string) AllureBuilder
	Stagef(format string, args ...interface{}) AllureBuilder
}

AllureInfoBuilder is a scope of methods for create allure information (Title, Tags, etc.)

type AllureLabelsBuilder

type AllureLabelsBuilder interface {
	Feature(feature string) AllureBuilder
	Epic(epic string) AllureBuilder
	AllureID(value string) AllureBuilder
	Tags(tags ...string) AllureBuilder
	ID(value string) AllureBuilder
	AddSuiteLabel(value string) AllureBuilder
	AddSubSuite(value string) AllureBuilder
	AddParentSuite(value string) AllureBuilder
	Story(value string) AllureBuilder
	Tag(value string) AllureBuilder
	Severity(value allure.SeverityType) AllureBuilder
	Owner(value string) AllureBuilder
	Lead(value string) AllureBuilder
	Label(label *allure.Label) AllureBuilder
	Labels(labels ...*allure.Label) AllureBuilder
	Layer(value string) AllureBuilder
	Stagef(format string, args ...interface{}) AllureBuilder
	Stage(stage string) AllureBuilder
}

AllureLabelsBuilder is a scope of methods to set allure labels

type AllureLinksBuilder

type AllureLinksBuilder interface {
	SetIssue(issue string) AllureBuilder
	SetTestCase(testCase string) AllureBuilder
	Link(link *allure.Link) AllureBuilder
	TmsLink(tmsLink string) AllureBuilder
	TmsLinks(tmsLinks ...string) AllureBuilder
}

AllureLinksBuilder is a scope of methods to set allure links

type AllureStep added in v0.1.6

type AllureStep struct {
	Name string
}

AllureStep is struct with test name

type AssertBody

type AssertBody func(body []byte) error

AssertBody is type for create custom assertions for body Example asserts: - json.LengthGreaterThan - json.LengthGreaterOrEqualThan - json.LengthLessThan - json.LengthLessOrEqualThan - json.Present - json.NotEmpty - json.NotPresent

type AssertBodyT

type AssertBodyT func(t T, body []byte) error

AssertBodyT is type for create custom assertions for body with TB Check example in AssertBody TB is testing.T and it can be used for require ore assert from testify or another packages

type AssertHeaders

type AssertHeaders func(headers http.Header) error

AssertHeaders is type for create custom assertions for headers Example asserts: - headers.Present - headers.NotPresent

type AssertHeadersT

type AssertHeadersT func(t T, headers http.Header) error

AssertHeadersT is type for create custom assertions for headers with TB Check example in AssertHeaders TB is testing.T and it can be used for require ore assert from testify or another packages

type AssertResponse

type AssertResponse func(response *http.Response) error

AssertResponse is type for create custom assertions for response

type AssertResponseT

type AssertResponseT func(t T, response *http.Response) error

AssertResponseT is type for create custom assertions for response with TB Check example in AssertResponse TB is testing.T and it can be used for require ore assert from testify or another packages

type BeforeExecute

type BeforeExecute func(*http.Request) error

BeforeExecute is a function for processing request before test execution

type BeforeExecuteT

type BeforeExecuteT func(T, *http.Request) error

BeforeExecuteT is a function for processing request before test execution

type BeforeTest added in v0.1.6

type BeforeTest interface {
	// BeforeExecute is function for processing request before test execution
	BeforeExecute(...BeforeExecute) MiddlewareRequest
	// BeforeExecuteT is function for processing request before test execution
	BeforeExecuteT(...BeforeExecuteT) MiddlewareRequest
}

BeforeTest are functions for processing request before test execution Same functions: Before

type ControlTest added in v0.1.6

type ControlTest interface {
	NextTest() NextTestBuilder

	// ExecuteTest is a function for execute Test
	ExecuteTest(ctx context.Context, t tProvider) []ResultsHTTPBuilder
}

ControlTest is function for manipulating tests

type CreateBuilder added in v0.1.6

type CreateBuilder interface {
	// Create is a function for save main information about allure and start write tests
	Create() MiddlewareRequest

	// CreateStep is a function for create step inside suite for Test
	CreateStep(string) MiddlewareRequest

	// CreateTableTest is function for create table Test
	CreateTableTest() MiddlewareTable
}

CreateBuilder is functions for create Test or table tests

type Expect added in v0.1.6

type Expect struct {
	ExecuteTime time.Duration

	Code       int
	JSONSchema *ExpectJSONSchema

	AssertBody     []AssertBody
	AssertHeaders  []AssertHeaders
	AssertResponse []AssertResponse

	AssertBodyT     []AssertBodyT
	AssertHeadersT  []AssertHeadersT
	AssertResponseT []AssertResponseT
}

Expect is structs with validate politics for response

type ExpectHTTPBuilder

type ExpectHTTPBuilder interface {
	// ExpectExecuteTimeout is function for validate time of execution
	// Default value - 10 seconds
	ExpectExecuteTimeout(t time.Duration) ExpectHTTPBuilder

	// ExpectStatus is function for validate response status code
	ExpectStatus(code int) ExpectHTTPBuilder

	// ExpectJSONSchemaString is function for validate response by json schema from string
	ExpectJSONSchemaString(schema string) ExpectHTTPBuilder
	// ExpectJSONSchemaByte is function for validate response by json schema from byte
	ExpectJSONSchemaByte(schema []byte) ExpectHTTPBuilder
	// ExpectJSONSchemaFile is function for validate response by json schema from file
	// For get file from network use:
	// "http://www.some_host.com/schema.json"
	// For get local file use:
	// "file://./project/me/schema.json"
	ExpectJSONSchemaFile(path string) ExpectHTTPBuilder

	// AssertBody is function for validate response body.
	// Available asserts from asserts/json/json.go:
	// Contains is a function to assert that a jsonpath expression extracts a value in an array
	// Equal is a function to assert that a jsonpath expression matches the given value
	// NotEqual is a function to check jsonpath expression value is not equal to given value
	// Length is a function to asserts that jsonpath expression value is the expected length
	// GreaterThan is a function to asserts that jsonpath expression value is greater than the given length
	// LessThan is a function to asserts that jsonpath expression value is less than the given length
	// Present is a function to asserts that jsonpath expression value is present
	// NotPresent is a function to asserts that jsonpath expression value is not present
	// Also you can write you assert.
	AssertBody(asserts ...AssertBody) ExpectHTTPBuilder
	// RequireBody implements the same assertions as the `AssertBody`, but stops test execution when a test fails.
	RequireBody(asserts ...AssertBody) ExpectHTTPBuilder
	// OptionalAssertBody is not a mandatory assert.
	// Mark in allure as Skipped
	OptionalAssertBody(asserts ...AssertBody) ExpectHTTPBuilder
	// BrokenAssertBody  is function for validate response, if it's failed, then test will be Broken.
	// Mark in allure as Broken
	BrokenAssertBody(asserts ...AssertBody) ExpectHTTPBuilder
	// AssertBodyT is function for validate response body with help testing.TB and allure allureProvider.
	// You may create allure step inside assert, add attachment, log information, etc.
	AssertBodyT(asserts ...AssertBodyT) ExpectHTTPBuilder
	// RequireBodyT implements the same assertions as the `AssertBodyT`, but stops test execution when a test fails.
	RequireBodyT(asserts ...AssertBodyT) ExpectHTTPBuilder
	// OptionalAssertBodyT is not a mandatory assert.
	// Mark in allure as Skipped
	OptionalAssertBodyT(asserts ...AssertBodyT) ExpectHTTPBuilder
	// BrokenAssertBodyT  is function for validate response, if it's failed, then test will be Broken.
	// Mark in allure as Broken
	BrokenAssertBodyT(asserts ...AssertBodyT) ExpectHTTPBuilder

	// AssertHeaders is function for validate response headers
	// Available asserts from asserts/headers/headers.go:
	// Present is a function to asserts header is present
	// NotPresent is a function to asserts header is present
	// Also you can write you assert.
	AssertHeaders(asserts ...AssertHeaders) ExpectHTTPBuilder
	// RequireHeaders implements the same assertions as the `AssertHeaders`, but stops test execution when a test fails.
	RequireHeaders(asserts ...AssertHeaders) ExpectHTTPBuilder
	// OptionalAssertHeaders is not a mandatory assert.
	// Mark in allure as Skipped
	OptionalAssertHeaders(asserts ...AssertHeaders) ExpectHTTPBuilder
	// BrokenAssertHeaders  is function for validate response, if it's failed, then test will be Broken.
	// Mark in allure as Broken
	BrokenAssertHeaders(asserts ...AssertHeaders) ExpectHTTPBuilder
	// AssertHeadersT is function for validate headers body with help testing.TB and allure allureProvider.
	// You may create allure step inside assert, add attachment, log information, etc.
	AssertHeadersT(asserts ...AssertHeadersT) ExpectHTTPBuilder
	// RequireHeadersT implements the same assertions as the `AssertHeadersT`, but stops test execution when a test fails.
	RequireHeadersT(asserts ...AssertHeadersT) ExpectHTTPBuilder
	// OptionalAssertHeadersT is not a mandatory assert.
	// Mark in allure as Skipped
	OptionalAssertHeadersT(asserts ...AssertHeadersT) ExpectHTTPBuilder
	// BrokenAssertHeadersT is function for validate response, if it's failed, then test will be Broken.
	// Mark in allure as Broken
	BrokenAssertHeadersT(asserts ...AssertHeadersT) ExpectHTTPBuilder

	// AssertResponse is function for validate response.
	AssertResponse(asserts ...AssertResponse) ExpectHTTPBuilder
	// RequireResponse implements the same assertions as the `AssertResponse`, but stops test execution when a test fails.
	RequireResponse(asserts ...AssertResponse) ExpectHTTPBuilder
	// OptionalAssertResponse is not a mandatory assert.
	// Mark in allure as Skipped
	OptionalAssertResponse(asserts ...AssertResponse) ExpectHTTPBuilder
	// BrokenAssertResponse  is function for validate response, if it's failed, then test will be Broken.
	// Mark in allure as Broken
	BrokenAssertResponse(asserts ...AssertResponse) ExpectHTTPBuilder
	// AssertResponseT is function for validate response with help testing.TB.
	// You may create allure step inside assert, add attachment, log information, etc.
	AssertResponseT(asserts ...AssertResponseT) ExpectHTTPBuilder
	// RequireResponseT implements the same assertions as the `AssertResponseT`, but stops test execution when a test fails.
	RequireResponseT(asserts ...AssertResponseT) ExpectHTTPBuilder
	// OptionalAssertResponseT is not a mandatory assert.
	// Mark in allure as Skipped
	OptionalAssertResponseT(asserts ...AssertResponseT) ExpectHTTPBuilder
	// BrokenAssertResponseT is function for validate response, if it's failed, then test will be Broken.
	// Mark in allure as Broken
	BrokenAssertResponseT(asserts ...AssertResponseT) ExpectHTTPBuilder

	After
	ControlTest
}

ExpectHTTPBuilder is a scope of methods for validate http response

type ExpectJSONSchema added in v0.1.6

type ExpectJSONSchema struct {
	String string
	Byte   []byte
	File   string
}

ExpectJSONSchema is structs with JSON politics for response

type File added in v0.1.10

type File struct {
	Path string
	Name string
	Body []byte
}

File is struct for upload file in form field If you set Path, file will read from file system If you set Name and Body, file will set from this fields

type HTTPTestMaker

type HTTPTestMaker struct {
	// contains filtered or unexported fields
}

HTTPTestMaker is a creator tests

func NewHTTPTestMaker

func NewHTTPTestMaker(opts ...Option) *HTTPTestMaker

NewHTTPTestMaker is function for set options for all cute. For example, you can set timeout for all requests or set custom http client Options: - WithCustomHTTPTimeout - set timeout for all requests - WithHTTPClient - set custom http client - WithCustomHTTPRoundTripper - set custom http round tripper - WithJSONMarshaler - set custom json marshaler - WithMiddlewareAfter - set function which will run AFTER test execution - WithMiddlewareAfterT - set function which will run AFTER test execution with TB - WithMiddlewareBefore - set function which will run BEFORE test execution - WithMiddlewareBeforeT - set function which will run BEFORE test execution with TB

func (*HTTPTestMaker) NewTestBuilder

func (m *HTTPTestMaker) NewTestBuilder() AllureBuilder

NewTestBuilder is a function for initialization foundation for cute

type JSONMarshaler added in v0.1.17

type JSONMarshaler interface {
	Marshal(v any) ([]byte, error)
	Unmarshal(data []byte, v any) error
}

JSONMarshaler is marshaler which use for marshal/unmarshal JSON to/from struct

type Middleware

type Middleware struct {
	After   []AfterExecute
	AfterT  []AfterExecuteT
	Before  []BeforeExecute
	BeforeT []BeforeExecuteT
}

Middleware is struct for executeInsideAllure something before or after test

type MiddlewareRequest added in v0.1.6

type MiddlewareRequest interface {
	RequestHTTPBuilder

	BeforeTest
	AfterTest
}

MiddlewareRequest is function for create requests or add After/Before functions

type MiddlewareTable added in v0.1.6

type MiddlewareTable interface {
	TableTest

	BeforeTest
	AfterTest
}

MiddlewareTable is functions for create table Test

type NextTestBuilder added in v0.1.6

type NextTestBuilder interface {
	AfterTestExecute

	CreateBuilder
}

NextTestBuilder is a scope of methods for processing response, after Test.

type Option

type Option func(*options)

Option ...

func WithCustomHTTPRoundTripper

func WithCustomHTTPRoundTripper(r http.RoundTripper) Option

WithCustomHTTPRoundTripper is a function for set custom http round tripper

func WithCustomHTTPTimeout

func WithCustomHTTPTimeout(t time.Duration) Option

WithCustomHTTPTimeout is a function for set custom http client timeout

func WithHTTPClient

func WithHTTPClient(client *http.Client) Option

WithHTTPClient is a function for set custom http client

func WithJSONMarshaler added in v0.1.17

func WithJSONMarshaler(m JSONMarshaler) Option

WithJSONMarshaler is a function for set custom json marshaler

func WithMiddlewareAfter added in v0.1.10

func WithMiddlewareAfter(after ...AfterExecute) Option

WithMiddlewareAfter is function for set function which will run AFTER test execution

func WithMiddlewareAfterT added in v0.1.10

func WithMiddlewareAfterT(after ...AfterExecuteT) Option

WithMiddlewareAfterT is function for set function which will run AFTER test execution

func WithMiddlewareBefore added in v0.1.10

func WithMiddlewareBefore(before ...BeforeExecute) Option

WithMiddlewareBefore is function for set function which will run BEFORE test execution

func WithMiddlewareBeforeT added in v0.1.10

func WithMiddlewareBeforeT(beforeT ...BeforeExecuteT) Option

WithMiddlewareBeforeT is function for set function which will run BEFORE test execution

type Request added in v0.1.6

type Request struct {
	Base     *http.Request
	Builders []RequestBuilder
	Repeat   *RequestRepeatPolitic
}

Request is struct with HTTP request. You may use your *http.Request or create new with help Builders

type RequestBuilder added in v0.1.6

type RequestBuilder func(o *requestOptions)

RequestBuilder is a function for set options in request

type RequestHTTPBuilder

type RequestHTTPBuilder interface {
	// Request is function for set http.Request
	Request(r *http.Request) ExpectHTTPBuilder
	// RequestBuilder is function for set http.Request with builders
	// Available builders:
	// WithMethod
	// WithURL
	// WithHeaders
	// WithHeadersKV
	// WithBody
	// WithMarshalBody
	// WithBody
	// WithURI
	// WithQuery
	// WithQueryKV
	// WithFileForm
	// WithFileFormKV
	// WithForm
	// WithFormKV
	RequestBuilder(r ...RequestBuilder) ExpectHTTPBuilder

	RequestParams
}

RequestHTTPBuilder is a scope of methods to create HTTP requests

type RequestParams added in v0.1.6

type RequestParams interface {
	// RequestRepeat is a function for set options in request
	// if response.Code != Expect.Code, than request will repeat counts with delay.
	// Default delay is 1 second.
	RequestRepeat(count int) RequestHTTPBuilder

	// RequestRepeatDelay set delay for request repeat.
	// if response.Code != Expect.Code, than request will repeat counts with delay.
	// Default delay is 1 second.
	RequestRepeatDelay(delay time.Duration) RequestHTTPBuilder

	// RequestRepeatPolitic is a politic for repeat request.
	// if response.Code != Expect.Code, than request will repeat counts with delay.
	// if Optional is true and request is failed, than test step allure will be skipped, and t.Fail() will not execute.
	// If Broken is true and request is failed, than test step allure will be broken, and t.Fail() will execute.
	RequestRepeatPolitic(politic *RequestRepeatPolitic) RequestHTTPBuilder

	// RequestRepeatOptional is a option politic for repeat request.
	// if Optional is true and request is failed, than test step allure will be skipped, and t.Fail() will not execute.
	RequestRepeatOptional(optional bool) RequestHTTPBuilder

	// RequestRepeatBroken is a broken politic for repeat request.
	// If Broken is true and request is failed, than test step allure will be broken, and t.Fail() will execute.
	RequestRepeatBroken(broken bool) RequestHTTPBuilder
}

RequestParams is a scope of methods to configure request

type RequestRepeatPolitic added in v0.1.6

type RequestRepeatPolitic struct {
	Count    int
	Delay    time.Duration
	Optional bool
	Broken   bool
}

RequestRepeatPolitic is struct for repeat politic if Optional is true and request is failed, than test step allure will be skip, and t.Fail() will not execute. If Broken is true and request is failed, than test step allure will be broken, and t.Fail() will not execute. If Optional and Broken is false, than test step will be failed, and t.Fail() will execute. If response.Code != Expect.Code, than request will repeat Count counts with Delay delay.

type ResultState added in v0.1.17

type ResultState int

ResultState is state of test

const (
	ResultStateSuccess ResultState = iota
	ResultStateBroken
	ResultStateFail
)

ResultState is state of test

type ResultsHTTPBuilder

type ResultsHTTPBuilder interface {
	// GetHTTPResponse is a function, which returns http response
	GetHTTPResponse() *http.Response
	// GetErrors is a function, which returns all errors from test
	GetErrors() []error
	// GetName is a function, which returns name of Test
	GetName() string
	// GetResultState is a function, which returns state of test
	// State could be ResultStateSuccess, ResultStateBroken, ResultStateFail
	GetResultState() ResultState
}

ResultsHTTPBuilder is a scope of methods for processing results

type T

type T interface {
	// contains filtered or unexported methods
}

T is internal testing.T provider

type TableTest added in v0.1.6

type TableTest interface {
	// PutNewTest is function for put request and assert for table Test
	PutNewTest(name string, r *http.Request, expect *Expect) TableTest
	// PutTests is function for put requests and asserts for table Test
	PutTests(params ...*Test) TableTest
	ControlTest
}

TableTest is function for put request and assert for table tests

type Test added in v0.1.6

type Test struct {
	Name string

	AllureStep *AllureStep
	Middleware *Middleware
	Request    *Request
	Expect     *Expect
	// contains filtered or unexported fields
}

Test is a main struct of test. You may field Request and Expect for create simple test

func (*Test) Debug added in v0.1.19

func (it *Test) Debug(t tlogger, format string, args ...interface{})

Debug is a function to log debug message

func (*Test) Error added in v0.1.19

func (it *Test) Error(t tlogger, format string, args ...interface{})

Error is a function to log error message

func (*Test) Execute added in v0.1.6

func (it *Test) Execute(ctx context.Context, t tProvider) ResultsHTTPBuilder

Execute is common method for run test from builder

func (*Test) Info added in v0.1.19

func (it *Test) Info(t tlogger, format string, args ...interface{})

Info is a function to log info message

Directories

Path Synopsis
asserts
internal

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL