HumHub Documentation (unofficial)

REST extends Module
in package
implements DependsOnModule, PartedModule, API, ConflictsWithModule

Module for testing REST WebService.

This module requires either PhpBrowser or a framework module (e.g. Symfony, Laravel) to send the actual HTTP request.

Configuration

  • url optional - the url of api
  • shortDebugResponse optional - number of chars to limit the API response length

Example

modules:
   enabled:
       - REST:
           depends: PhpBrowser
           url: 'https://example.com/api/v1/'
           shortDebugResponse: 300 # only the first 300 characters of the response

In case you need to configure low-level HTTP headers, that's done on the PhpBrowser level like so:

modules:
   enabled:
       - REST:
           depends: PhpBrowser
           url: &url 'https://example.com/api/v1/'
   config:
       PhpBrowser:
           url: *url
           headers:
               Content-Type: application/json

JSONPath

JSONPath is the equivalent to XPath, for querying JSON data structures. Here's an Online JSONPath Expressions Tester

Public Properties

  • headers - array of headers going to be sent.
  • params - array of sent data
  • response - last response (string)

Parts

  • Json - actions for validating Json responses (no Xml responses)
  • Xml - actions for validating XML responses (no Json responses)

Conflicts

Conflicts with SOAP module

Table of Contents

Interfaces

DependsOnModule
PartedModule
Interface PartedModule
API
Modules for API testing
ConflictsWithModule

Constants

QUERY_PARAMS_AWARE_METHODS  = ['GET', 'HEAD', 'OPTIONS']

Properties

$aliases  : array<string|int, mixed>
Allows to rename actions
$client  : HttpKernelBrowser|AbstractBrowser
$excludeActions  : array<string|int, mixed>
Allows to explicitly exclude actions from module.
$includeInheritedActions  : bool
By setting it to false module wan't inherit methods of parent class.
$isFunctional  : mixed
$onlyActions  : array<string|int, mixed>
Allows to explicitly set what methods have this class.
$params  : mixed
$response  : mixed
$backupConfig  : mixed
$config  : mixed
$connectionModule  : InnerBrowser
$DEFAULT_SHORTEN_VALUE  : mixed
$dependencyMessage  : mixed
$moduleContainer  : ModuleContainer
$requiredFields  : mixed
$storage  : mixed

Methods

__construct()  : mixed
Module constructor.
_after()  : mixed
**HOOK** executed after test
_afterStep()  : mixed
**HOOK** executed after step
_afterSuite()  : mixed
**HOOK** executed after suite
_before()  : mixed
**HOOK** executed before test
_beforeStep()  : mixed
**HOOK** executed before step
_beforeSuite()  : mixed
**HOOK** executed before suite
_conflicts()  : string
Returns class name or interface of module which can conflict with current.
_depends()  : mixed
Specifies class or module which is required for current one.
_failed()  : mixed
**HOOK** executed when test fails but before `_after`
_getConfig()  : mixed
Get config values or specific config item.
_getName()  : string
Returns a module name for a Module, a class name for Helper
_hasRequiredFields()  : bool
Checks if a module has required fields
_initialize()  : mixed
**HOOK** triggered after module is created and configuration is loaded
_inject()  : mixed
_parts()  : mixed
_reconfigure()  : mixed
Allows to redefine config for a specific test.
_resetConfig()  : mixed
Reverts config changed by `_reconfigure`
_setConfig()  : mixed
Allows to define initial module config.
amAWSAuthenticated()  : mixed
Allows to send REST request using AWS Authorization
amBearerAuthenticated()  : mixed
Adds Bearer authentication via access token.
amDigestAuthenticated()  : mixed
Adds Digest authentication via username/password.
amHttpAuthenticated()  : mixed
Adds HTTP authentication via username/password.
amNTLMAuthenticated()  : mixed
Adds NTLM authentication via username/password.
deleteHeader()  : mixed
Deletes a HTTP header (that was originally added by [haveHttpHeader()](#haveHttpHeader)), so that subsequent requests will not send it anymore.
dontSeeBinaryResponseEquals()  : mixed
Checks if the hash of a binary response is not the same as provided.
dontSeeHttpHeader()  : mixed
Checks over the given HTTP header and (optionally) its value, asserting that are not there
dontSeeResponseCodeIs()  : mixed
Checks that response code is not equal to provided value.
dontSeeResponseContains()  : mixed
Checks whether last response do not contain text.
dontSeeResponseContainsJson()  : mixed
Opposite to seeResponseContainsJson
dontSeeResponseJsonMatchesJsonPath()  : mixed
See [#jsonpath](#jsonpath) for general info on JSONPath.
dontSeeResponseJsonMatchesXpath()  : mixed
Opposite to seeResponseJsonMatchesXpath
dontSeeResponseMatchesJsonType()  : mixed
Opposite to `seeResponseMatchesJsonType`.
dontSeeXmlResponseEquals()  : mixed
Checks XML response does not equal to provided XML.
dontSeeXmlResponseIncludes()  : mixed
Checks XML response does not include provided XML.
dontSeeXmlResponseMatchesXpath()  : mixed
Checks whether XML response does not match XPath
grabAttributeFromXmlElement()  : string
Finds and returns attribute of element.
grabDataFromResponseByJsonPath()  : array<string|int, mixed>
See [#jsonpath](#jsonpath) for general info on JSONPath.
grabHttpHeader()  : string|array<string|int, mixed>
Returns the value of the specified header name
grabResponse()  : string
Returns current response so that it can be used in next scenario steps.
grabTextContentFromXmlElement()  : string
Finds and returns text contents of element.
haveHttpHeader()  : mixed
Sets a HTTP header to be used for all subsequent requests. Use [`deleteHeader`](#deleteHeader) to unset it.
haveServerParameter()  : mixed
Sets SERVER parameter valid for all next requests.
seeBinaryResponseEquals()  : mixed
Checks if the hash of a binary response is exactly the same as provided.
seeHttpHeader()  : mixed
Checks over the given HTTP header and (optionally) its value, asserting that are there
seeHttpHeaderOnce()  : mixed
Checks that http response header is received only once.
seeResponseCodeIs()  : mixed
Checks response code equals to provided value.
seeResponseCodeIsClientError()  : mixed
Checks that the response code is 4xx
seeResponseCodeIsRedirection()  : mixed
Checks that the response code 3xx
seeResponseCodeIsServerError()  : mixed
Checks that the response code is 5xx
seeResponseCodeIsSuccessful()  : mixed
Checks that the response code is 2xx
seeResponseContains()  : mixed
Checks whether the last response contains text.
seeResponseContainsJson()  : mixed
Checks whether the last JSON response contains provided array.
seeResponseEquals()  : mixed
Checks if response is exactly the same as provided.
seeResponseIsJson()  : mixed
Checks whether last response was valid JSON.
seeResponseIsValidOnJsonSchema()  : mixed
Checks whether last response matches the supplied json schema (https://json-schema.org/) Supply schema as relative file path in your project directory or an absolute path
seeResponseIsValidOnJsonSchemaString()  : mixed
Checks whether last response matches the supplied json schema (https://json-schema.org/) Supply schema as json string.
seeResponseIsXml()  : mixed
Checks whether last response was valid XML.
seeResponseJsonMatchesJsonPath()  : mixed
See [#jsonpath](#jsonpath) for general info on JSONPath.
seeResponseJsonMatchesXpath()  : mixed
Checks if json structure in response matches the xpath provided.
seeResponseMatchesJsonType()  : mixed
Checks that JSON matches provided types.
seeXmlResponseEquals()  : mixed
Checks XML response equals provided XML.
seeXmlResponseIncludes()  : mixed
Checks XML response includes provided XML.
seeXmlResponseMatchesXpath()  : mixed
Checks whether XML response matches XPath
send()  : mixed
Sends a HTTP request.
sendDelete()  : mixed
Sends DELETE request to given uri.
sendGet()  : mixed
Sends a GET request to given uri.
sendHead()  : mixed
Sends a HEAD request to given uri.
sendLink()  : mixed
Sends LINK request to given uri.
sendOptions()  : mixed
Sends an OPTIONS request to given uri.
sendPatch()  : mixed
Sends PATCH request to given uri.
sendPost()  : mixed
Sends a POST request to given uri. Parameters and files can be provided separately.
sendPut()  : mixed
Sends PUT request to given uri.
sendUnlink()  : mixed
Sends UNLINK request to given uri.
setServerParameters()  : mixed
Sets SERVER parameters valid for all next requests.
startFollowingRedirects()  : mixed
Enables automatic redirects to be followed by the client
stopFollowingRedirects()  : mixed
Prevents automatic redirects to be followed by the client
assert()  : mixed
assertFileNotExists()  : mixed
Asserts that a file does not exist.
assertGreaterOrEquals()  : mixed
Asserts that a value is greater than or equal to another value.
assertIsEmpty()  : mixed
Asserts that a variable is empty.
assertLessOrEquals()  : mixed
Asserts that a value is smaller than or equal to another value.
assertNot()  : mixed
assertNotRegExp()  : mixed
Asserts that a string does not match a given regular expression.
assertRegExp()  : mixed
Asserts that a string matches a given regular expression.
assertThatItsNot()  : mixed
Evaluates a PHPUnit\Framework\Constraint matcher object.
binaryToDebugString()  : string
Format a binary string for debug printing
debug()  : mixed
Print debug message to the screen.
debugSection()  : mixed
Print debug message with a title
decodeAndValidateJson()  : mixed
Converts string to json and asserts that no error occured while decoding.
encodeApplicationJson()  : mixed
execute()  : mixed
getModule()  : Module
Get another module by its name:
getModules()  : array<string|int, mixed>
Get all enabled modules
getRunningClient()  : mixed
hasModule()  : bool
Checks that module is enabled.
isBinaryData()  : bool
Check if data has non-printable bytes and it is not a valid unicode string
onReconfigure()  : mixed
HOOK to be executed when config changes with `_reconfigure`.
resetVariables()  : mixed
scalarizeArray()  : mixed
shortenMessage()  : string
Short text message to an amount of chars
validateConfig()  : mixed
Extends the function Module::validateConfig for shorten messages
checkFileBeforeUpload()  : mixed
formatFilesArray()  : mixed
getFileType()  : mixed
setHeaderLink()  : mixed
Sets Headers "Link" as one header "Link" based on linkEntries

Constants

QUERY_PARAMS_AWARE_METHODS

public mixed QUERY_PARAMS_AWARE_METHODS = ['GET', 'HEAD', 'OPTIONS']

Properties

$aliases

Allows to rename actions

public static array<string|int, mixed> $aliases = []

$client

public HttpKernelBrowser|AbstractBrowser $client = null

$excludeActions

Allows to explicitly exclude actions from module.

public static array<string|int, mixed> $excludeActions = []

$includeInheritedActions

By setting it to false module wan't inherit methods of parent class.

public static bool $includeInheritedActions = true

$isFunctional

public mixed $isFunctional = false

$onlyActions

Allows to explicitly set what methods have this class.

public static array<string|int, mixed> $onlyActions = []

$params

public mixed $params = []

$response

public mixed $response = ""

$backupConfig

protected mixed $backupConfig = []

$config

protected mixed $config = ['url' => '', 'aws' => '']

$DEFAULT_SHORTEN_VALUE

protected mixed $DEFAULT_SHORTEN_VALUE = 150

$dependencyMessage

protected mixed $dependencyMessage = <<<EOF Example configuring PhpBrowser as backend for REST module. -- modules: enabled: - REST: depends: PhpBrowser url: http://localhost/api/ shortDebugResponse: 300 -- Framework modules can be used for testing of API as well. EOF

$requiredFields

protected mixed $requiredFields = []

$storage

protected mixed $storage = []

Methods

__construct()

Module constructor.

public __construct(ModuleContainer $moduleContainer[, array<string|int, mixed>|null $config = null ]) : mixed

Requires module container (to provide access between modules of suite) and config.

Parameters
$moduleContainer : ModuleContainer
$config : array<string|int, mixed>|null = null

_afterStep()

**HOOK** executed after step

public _afterStep(Step $step) : mixed
Parameters
$step : Step

_afterSuite()

**HOOK** executed after suite

public _afterSuite() : mixed

_beforeStep()

**HOOK** executed before step

public _beforeStep(Step $step) : mixed
Parameters
$step : Step

_beforeSuite()

**HOOK** executed before suite

public _beforeSuite([array<string|int, mixed> $settings = [] ]) : mixed
Parameters
$settings : array<string|int, mixed> = []

_conflicts()

Returns class name or interface of module which can conflict with current.

public _conflicts() : string
Return values
string

_depends()

Specifies class or module which is required for current one.

public _depends() : mixed

THis method should return array with key as class name and value as error message [className => errorMessage ]

_failed()

**HOOK** executed when test fails but before `_after`

public _failed(TestInterface $test, mixed $fail) : mixed
Parameters
$test : TestInterface
$fail : mixed

_getConfig()

Get config values or specific config item.

public _getConfig([mixed $key = null ]) : mixed
Parameters
$key : mixed = null
Return values
mixed

the config item's value or null if it doesn't exist

_getName()

Returns a module name for a Module, a class name for Helper

public _getName() : string
Return values
string

_hasRequiredFields()

Checks if a module has required fields

public _hasRequiredFields() : bool
Return values
bool

_initialize()

**HOOK** triggered after module is created and configuration is loaded

public _initialize() : mixed

_parts()

public _parts() : mixed

_reconfigure()

Allows to redefine config for a specific test.

public _reconfigure(mixed $config) : mixed

Config is restored at the end of a test.

<?php
// cleanup DB only for specific group of tests
public function _before(Test $test) {
    if (in_array('cleanup', $test->getMetadata()->getGroups()) {
        $this->getModule('Db')->_reconfigure(['cleanup' => true]);
    }
}
Parameters
$config : mixed
Tags
throws
ModuleConfigException
throws
ModuleException

_resetConfig()

Reverts config changed by `_reconfigure`

public _resetConfig() : mixed

_setConfig()

Allows to define initial module config.

public _setConfig(mixed $config) : mixed

Can be used in _beforeSuite hook of Helpers or Extensions

<?php
public function _beforeSuite($settings = []) {
    $this->getModule('otherModule')->_setConfig($this->myOtherConfig);
}
Parameters
$config : mixed
Tags
throws
ModuleConfigException
throws
ModuleException

amAWSAuthenticated()

Allows to send REST request using AWS Authorization

public amAWSAuthenticated([array<string|int, mixed> $additionalAWSConfig = [] ]) : mixed

Only works with PhpBrowser Example Config:

modules:
     enabled:
         - REST:
             aws:
                 key: accessKey
                 secret: accessSecret
                 service: awsService
                 region: awsRegion

Code:

<?php
$I->amAWSAuthenticated();
?>
Parameters
$additionalAWSConfig : array<string|int, mixed> = []
Tags
throws
ConfigurationException

amBearerAuthenticated()

Adds Bearer authentication via access token.

public amBearerAuthenticated(mixed $accessToken) : mixed
Parameters
$accessToken : mixed
Tags
part

json

part

xml

amDigestAuthenticated()

Adds Digest authentication via username/password.

public amDigestAuthenticated(mixed $username, mixed $password) : mixed
Parameters
$username : mixed
$password : mixed
Tags
part

json

part

xml

amHttpAuthenticated()

Adds HTTP authentication via username/password.

public amHttpAuthenticated(mixed $username, mixed $password) : mixed
Parameters
$username : mixed
$password : mixed
Tags
part

json

part

xml

amNTLMAuthenticated()

Adds NTLM authentication via username/password.

public amNTLMAuthenticated(mixed $username, mixed $password) : mixed

Requires client to be Guzzle >=6.3.0 Out of scope for functional modules.

Example:

<?php
$I->amNTLMAuthenticated('jon_snow', 'targaryen');
?>
Parameters
$username : mixed
$password : mixed
Tags
throws
ModuleException
part

json

part

xml

deleteHeader()

Deletes a HTTP header (that was originally added by [haveHttpHeader()](#haveHttpHeader)), so that subsequent requests will not send it anymore.

public deleteHeader(string $name) : mixed

Example:

<?php
$I->haveHttpHeader('X-Requested-With', 'Codeception');
$I->sendGet('test-headers.php');
// ...
$I->deleteHeader('X-Requested-With');
$I->sendPost('some-other-page.php');
?>
Parameters
$name : string

the name of the header to delete.

Tags
part

json

part

xml

dontSeeBinaryResponseEquals()

Checks if the hash of a binary response is not the same as provided.

public dontSeeBinaryResponseEquals(string $hash[, string $algo = 'md5' ]) : mixed
<?php
$I->dontSeeBinaryResponseEquals("8c90748342f19b195b9c6b4eff742ded");
?>

Opposite to seeBinaryResponseEquals

Parameters
$hash : string

the hashed data response expected

$algo : string = 'md5'

the hash algorithm to use. Default md5.

Tags
part

json

part

xml

dontSeeHttpHeader()

Checks over the given HTTP header and (optionally) its value, asserting that are not there

public dontSeeHttpHeader(mixed $name[, mixed $value = null ]) : mixed
Parameters
$name : mixed
$value : mixed = null
Tags
part

json

part

xml

dontSeeResponseCodeIs()

Checks that response code is not equal to provided value.

public dontSeeResponseCodeIs(mixed $code) : mixed
<?php
$I->dontSeeResponseCodeIs(200);

// preferred to use \Codeception\Util\HttpCode
$I->dontSeeResponseCodeIs(\Codeception\Util\HttpCode::OK);
Parameters
$code : mixed
Tags
part

json

part

xml

dontSeeResponseContains()

Checks whether last response do not contain text.

public dontSeeResponseContains(mixed $text) : mixed
Parameters
$text : mixed
Tags
part

json

part

xml

dontSeeResponseContainsJson()

Opposite to seeResponseContainsJson

public dontSeeResponseContainsJson([array<string|int, mixed> $json = [] ]) : mixed
Parameters
$json : array<string|int, mixed> = []
Tags
part

json

dontSeeResponseJsonMatchesJsonPath()

See [#jsonpath](#jsonpath) for general info on JSONPath.

public dontSeeResponseJsonMatchesJsonPath(string $jsonPath) : mixed

Opposite to seeResponseJsonMatchesJsonPath()

Parameters
$jsonPath : string
Tags
part

json

dontSeeResponseJsonMatchesXpath()

Opposite to seeResponseJsonMatchesXpath

public dontSeeResponseJsonMatchesXpath(string $xpath) : mixed
Parameters
$xpath : string
Tags
part

json

dontSeeResponseMatchesJsonType()

Opposite to `seeResponseMatchesJsonType`.

public dontSeeResponseMatchesJsonType(array<string|int, mixed> $jsonType[, string $jsonPath = null ]) : mixed
Parameters
$jsonType : array<string|int, mixed>

JsonType structure

$jsonPath : string = null
Tags
part

json

see
seeResponseMatchesJsonType

dontSeeXmlResponseEquals()

Checks XML response does not equal to provided XML.

public dontSeeXmlResponseEquals(mixed $xml) : mixed

Comparison is done by canonicalizing both xml`s.

Parameter can be passed either as XmlBuilder, DOMDocument, DOMNode, XML string, or array (if no attributes).

Parameters
$xml : mixed
Tags
part

xml

dontSeeXmlResponseIncludes()

Checks XML response does not include provided XML.

public dontSeeXmlResponseIncludes(mixed $xml) : mixed

Comparison is done by canonicalizing both xml`s. Parameter can be passed either as XmlBuilder, DOMDocument, DOMNode, XML string, or array (if no attributes).

Parameters
$xml : mixed
Tags
part

xml

dontSeeXmlResponseMatchesXpath()

Checks whether XML response does not match XPath

public dontSeeXmlResponseMatchesXpath(mixed $xpath) : mixed
<?php
$I->dontSeeXmlResponseMatchesXpath('//root/user[@id=1]');
Parameters
$xpath : mixed
Tags
part

xml

grabAttributeFromXmlElement()

Finds and returns attribute of element.

public grabAttributeFromXmlElement(mixed $cssOrXPath, mixed $attribute) : string

Element is matched by either CSS or XPath

Parameters
$cssOrXPath : mixed
$attribute : mixed
Tags
part

xml

Return values
string

grabDataFromResponseByJsonPath()

See [#jsonpath](#jsonpath) for general info on JSONPath.

public grabDataFromResponseByJsonPath(string $jsonPath) : array<string|int, mixed>

Even for a single value an array is returned. Example:

<?php
// match the first `user.id` in json
$firstUserId = $I->grabDataFromResponseByJsonPath('$..users[0].id');
$I->sendPut('/user', array('id' => $firstUserId[0], 'name' => 'davert'));
?>
Parameters
$jsonPath : string
Tags
throws
Exception
part

json

Return values
array<string|int, mixed>

Array of matching items

grabHttpHeader()

Returns the value of the specified header name

public grabHttpHeader(mixed $name[, bool $first = true ]) : string|array<string|int, mixed>
Parameters
$name : mixed
$first : bool = true

Whether to return the first value or all header values

Tags
part

json

part

xml

Return values
string|array<string|int, mixed>

The first header value if $first is true, an array of values otherwise

grabResponse()

Returns current response so that it can be used in next scenario steps.

public grabResponse() : string

Example:

<?php
$user_id = $I->grabResponse();
$I->sendPut('/user', array('id' => $user_id, 'name' => 'davert'));
?>
Tags
part

json

part

xml

Return values
string

grabTextContentFromXmlElement()

Finds and returns text contents of element.

public grabTextContentFromXmlElement(mixed $cssOrXPath) : string

Element is matched by either CSS or XPath

Parameters
$cssOrXPath : mixed
Tags
part

xml

Return values
string

haveHttpHeader()

Sets a HTTP header to be used for all subsequent requests. Use [`deleteHeader`](#deleteHeader) to unset it.

public haveHttpHeader(mixed $name, mixed $value) : mixed
<?php
$I->haveHttpHeader('Content-Type', 'application/json');
// all next requests will contain this header
?>
Parameters
$name : mixed
$value : mixed
Tags
part

json

part

xml

haveServerParameter()

Sets SERVER parameter valid for all next requests.

public haveServerParameter(mixed $name, mixed $value) : mixed
$I->haveServerParameter('name', 'value');
Parameters
$name : mixed
$value : mixed

seeBinaryResponseEquals()

Checks if the hash of a binary response is exactly the same as provided.

public seeBinaryResponseEquals(string $hash[, string $algo = 'md5' ]) : mixed

Parameter can be passed as any hash string supported by hash(), with an optional second parameter to specify the hash type, which defaults to md5.

Example: Using md5 hash key

<?php
$I->seeBinaryResponseEquals("8c90748342f19b195b9c6b4eff742ded");
?>

Example: Using md5 for a file contents

<?php
$fileData = file_get_contents("test_file.jpg");
$I->seeBinaryResponseEquals(md5($fileData));
?>

Example: Using sha256 hash

<?php
$fileData = '/9j/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8QEBEQCgwSExIQEw8QEBD/yQALCAABAAEBAREA/8wABgAQEAX/2gAIAQEAAD8A0s8g/9k='; // very small jpeg
$I->seeBinaryResponseEquals(hash("sha256", base64_decode($fileData)), 'sha256');
?>
Parameters
$hash : string

the hashed data response expected

$algo : string = 'md5'

the hash algorithm to use. Default md5.

Tags
part

json

part

xml

seeHttpHeader()

Checks over the given HTTP header and (optionally) its value, asserting that are there

public seeHttpHeader(mixed $name[, mixed $value = null ]) : mixed
Parameters
$name : mixed
$value : mixed = null
Tags
part

json

part

xml

seeHttpHeaderOnce()

Checks that http response header is received only once.

public seeHttpHeaderOnce(mixed $name) : mixed

HTTP RFC2616 allows multiple response headers with the same name. You can check that you didn't accidentally sent the same header twice.

<?php
$I->seeHttpHeaderOnce('Cache-Control');
?>>
Parameters
$name : mixed
Tags
part

json

part

xml

seeResponseCodeIs()

Checks response code equals to provided value.

public seeResponseCodeIs(mixed $code) : mixed
<?php
$I->seeResponseCodeIs(200);

// preferred to use \Codeception\Util\HttpCode
$I->seeResponseCodeIs(\Codeception\Util\HttpCode::OK);
Parameters
$code : mixed
Tags
part

json

part

xml

seeResponseCodeIsClientError()

Checks that the response code is 4xx

public seeResponseCodeIsClientError() : mixed
Tags
part

json

part

xml

seeResponseCodeIsRedirection()

Checks that the response code 3xx

public seeResponseCodeIsRedirection() : mixed
Tags
part

json

part

xml

seeResponseCodeIsServerError()

Checks that the response code is 5xx

public seeResponseCodeIsServerError() : mixed
Tags
part

json

part

xml

seeResponseCodeIsSuccessful()

Checks that the response code is 2xx

public seeResponseCodeIsSuccessful() : mixed
Tags
part

json

part

xml

seeResponseContains()

Checks whether the last response contains text.

public seeResponseContains(mixed $text) : mixed
Parameters
$text : mixed
Tags
part

json

part

xml

seeResponseContainsJson()

Checks whether the last JSON response contains provided array.

public seeResponseContainsJson([array<string|int, mixed> $json = [] ]) : mixed

The response is converted to array with json_decode($response, true) Thus, JSON is represented by associative array. This method matches that response array contains provided array.

Examples:

<?php
// response: {name: john, email: john@gmail.com}
$I->seeResponseContainsJson(array('name' => 'john'));

// response {user: john, profile: { email: john@gmail.com }}
$I->seeResponseContainsJson(array('email' => 'john@gmail.com'));

?>

This method recursively checks if one array can be found inside of another.

Parameters
$json : array<string|int, mixed> = []
Tags
part

json

seeResponseEquals()

Checks if response is exactly the same as provided.

public seeResponseEquals(mixed $expected) : mixed
Parameters
$expected : mixed
Tags
part

json

part

xml

seeResponseIsJson()

Checks whether last response was valid JSON.

public seeResponseIsJson() : mixed

This is done with json_last_error function.

Tags
part

json

seeResponseIsValidOnJsonSchema()

Checks whether last response matches the supplied json schema (https://json-schema.org/) Supply schema as relative file path in your project directory or an absolute path

public seeResponseIsValidOnJsonSchema(string $schemaFilename) : mixed
Parameters
$schemaFilename : string
Tags
see
codecept_absolute_path()
part

json

seeResponseIsValidOnJsonSchemaString()

Checks whether last response matches the supplied json schema (https://json-schema.org/) Supply schema as json string.

public seeResponseIsValidOnJsonSchemaString(string $schema) : mixed

Examples:

<?php
// response: {"name": "john", "age": 20}
$I->seeResponseIsValidOnJsonSchemaString('{"type": "object"}');

// response {"name": "john", "age": 20}
$schema = [
 "properties" => [
     "age" => [
         "type" => "integer",
         "minimum" => 18
     ]
 ]
];
$I->seeResponseIsValidOnJsonSchemaString(json_encode($schema));

?>
Parameters
$schema : string
Tags
part

json

seeResponseIsXml()

Checks whether last response was valid XML.

public seeResponseIsXml() : mixed

This is done with libxml_get_last_error function.

Tags
part

xml

seeResponseJsonMatchesJsonPath()

See [#jsonpath](#jsonpath) for general info on JSONPath.

public seeResponseJsonMatchesJsonPath(string $jsonPath) : mixed

Checks if JSON structure in response matches JSONPath.

  { "store": {
      "book": [
        { "category": "reference",
          "author": "Nigel Rees",
          "title": "Sayings of the Century",
          "price": 8.95
        },
        { "category": "fiction",
          "author": "Evelyn Waugh",
          "title": "Sword of Honour",
          "price": 12.99
        }
   ],
      "bicycle": {
        "color": "red",
        "price": 19.95
      }
    }
  }
<?php
// at least one book in store has author
$I->seeResponseJsonMatchesJsonPath('$.store.book[*].author');
// first book in store has author
$I->seeResponseJsonMatchesJsonPath('$.store.book[0].author');
// at least one item in store has price
$I->seeResponseJsonMatchesJsonPath('$.store..price');
?>
Parameters
$jsonPath : string
Tags
part

json

seeResponseJsonMatchesXpath()

Checks if json structure in response matches the xpath provided.

public seeResponseJsonMatchesXpath(string $xpath) : mixed

JSON is not supposed to be checked against XPath, yet it can be converted to xml and used with XPath. This assertion allows you to check the structure of response json. *

  { "store": {
      "book": [
        { "category": "reference",
          "author": "Nigel Rees",
          "title": "Sayings of the Century",
          "price": 8.95
        },
        { "category": "fiction",
          "author": "Evelyn Waugh",
          "title": "Sword of Honour",
          "price": 12.99
        }
   ],
      "bicycle": {
        "color": "red",
        "price": 19.95
      }
    }
  }
<?php
// at least one book in store has author
$I->seeResponseJsonMatchesXpath('//store/book/author');
// first book in store has author
$I->seeResponseJsonMatchesXpath('//store/book[1]/author');
// at least one item in store has price
$I->seeResponseJsonMatchesXpath('/store//price');
?>
Parameters
$xpath : string
Tags
part

json

seeResponseMatchesJsonType()

Checks that JSON matches provided types.

public seeResponseMatchesJsonType(array<string|int, mixed> $jsonType[, string $jsonPath = null ]) : mixed

In case you don't know the actual values of JSON data returned you can match them by type. It starts the check with a root element. If JSON data is an array it will check all elements of it. You can specify the path in the json which should be checked with JsonPath

Basic example:

<?php
// {'user_id': 1, 'name': 'davert', 'is_active': false}
$I->seeResponseMatchesJsonType([
     'user_id' => 'integer',
     'name' => 'string|null',
     'is_active' => 'boolean'
]);

// narrow down matching with JsonPath:
// {"users": [{ "name": "davert"}, {"id": 1}]}
$I->seeResponseMatchesJsonType(['name' => 'string'], '$.users[0]');
?>

You can check if the record contains fields with the data types you expect. The list of possible data types:

  • string
  • integer
  • float
  • array (json object is array as well)
  • boolean
  • null

You can also use nested data type structures, and define multiple types for the same field:

<?php
// {'user_id': 1, 'name': 'davert', 'company': {'name': 'Codegyre'}}
$I->seeResponseMatchesJsonType([
     'user_id' => 'integer|string', // multiple types
     'company' => ['name' => 'string']
]);
?>

You can also apply filters to check values. Filter can be applied with a : char after the type declaration, or after another filter if you need more than one.

Here is the list of possible filters:

  • integer:>{val} - checks that integer is greater than {val} (works with float and string types too).
  • integer:<{val} - checks that integer is lower than {val} (works with float and string types too).
  • string:url - checks that value is valid url.
  • string:date - checks that value is date in JavaScript format: https://weblog.west-wind.com/posts/2014/Jan/06/JavaScript-JSON-Date-Parsing-and-real-Dates
  • string:email - checks that value is a valid email according to http://emailregex.com/
  • string:regex({val}) - checks that string matches a regex provided with {val}

This is how filters can be used:

<?php
// {'user_id': 1, 'email' => 'davert@codeception.com'}
$I->seeResponseMatchesJsonType([
     'user_id' => 'string:>0:<1000', // multiple filters can be used
     'email' => 'string:regex(~\@~)' // we just check that @ char is included
]);

// {'user_id': '1'}
$I->seeResponseMatchesJsonType([
     'user_id' => 'string:>0', // works with strings as well
]);
?>

You can also add custom filters by using [](JsonType::addCustomFilter()). See JsonType reference.

Parameters
$jsonType : array<string|int, mixed>
$jsonPath : string = null
Tags
part

json

see
JsonType

seeXmlResponseEquals()

Checks XML response equals provided XML.

public seeXmlResponseEquals(mixed $xml) : mixed

Comparison is done by canonicalizing both xml`s.

Parameters can be passed either as DOMDocument, DOMNode, XML string, or array (if no attributes).

Parameters
$xml : mixed
Tags
part

xml

seeXmlResponseIncludes()

Checks XML response includes provided XML.

public seeXmlResponseIncludes(mixed $xml) : mixed

Comparison is done by canonicalizing both xml`s. Parameter can be passed either as XmlBuilder, DOMDocument, DOMNode, XML string, or array (if no attributes).

Example:

<?php
$I->seeXmlResponseIncludes("<result>1</result>");
?>
Parameters
$xml : mixed
Tags
part

xml

seeXmlResponseMatchesXpath()

Checks whether XML response matches XPath

public seeXmlResponseMatchesXpath(mixed $xpath) : mixed
<?php
$I->seeXmlResponseMatchesXpath('//root/user[@id=1]');
Parameters
$xpath : mixed
Tags
part

xml

send()

Sends a HTTP request.

public send(mixed $method, mixed $url[, array<string|int, mixed>|string|JsonSerializable $params = [] ][, array<string|int, mixed> $files = [] ]) : mixed
Parameters
$method : mixed
$url : mixed
$params : array<string|int, mixed>|string|JsonSerializable = []
$files : array<string|int, mixed> = []
Tags
part

json

part

xml

sendDelete()

Sends DELETE request to given uri.

public sendDelete(mixed $url[, array<string|int, mixed> $params = [] ][, array<string|int, mixed> $files = [] ]) : mixed
<?php
$I->sendDelete('/message/1');
Parameters
$url : mixed
$params : array<string|int, mixed> = []
$files : array<string|int, mixed> = []
Tags
part

json

part

xml

sendGet()

Sends a GET request to given uri.

public sendGet(mixed $url[, array<string|int, mixed> $params = [] ]) : mixed
<?php
$response = $I->sendGet('/users');

// send get with query params
$I->sendGet('/orders', ['id' => 1])
Parameters
$url : mixed
$params : array<string|int, mixed> = []
Tags
part

json

part

xml

sendHead()

Sends a HEAD request to given uri.

public sendHead(mixed $url[, array<string|int, mixed> $params = [] ]) : mixed
Parameters
$url : mixed
$params : array<string|int, mixed> = []
Tags
part

json

part

xml

Sends LINK request to given uri.

public sendLink(mixed $url, array<string|int, mixed> $linkEntries) : mixed
Parameters
$url : mixed
$linkEntries : array<string|int, mixed>

(entry is array with keys "uri" and "link-param")

Tags
link
http://tools.ietf.org/html/rfc2068#section-19.6.2.4
author

samva.ua@gmail.com

part

json

part

xml

sendOptions()

Sends an OPTIONS request to given uri.

public sendOptions(mixed $url[, array<string|int, mixed> $params = [] ]) : mixed
Parameters
$url : mixed
$params : array<string|int, mixed> = []
Tags
part

json

part

xml

sendPatch()

Sends PATCH request to given uri.

public sendPatch(mixed $url[, array<string|int, mixed>|string|JsonSerializable $params = [] ][, array<string|int, mixed> $files = [] ]) : mixed
<?php
$response = $I->sendPatch('/message/1', ['subject' => 'Read this!']);
Parameters
$url : mixed
$params : array<string|int, mixed>|string|JsonSerializable = []
$files : array<string|int, mixed> = []
Tags
part

json

part

xml

sendPost()

Sends a POST request to given uri. Parameters and files can be provided separately.

public sendPost(mixed $url[, array<string|int, mixed>|string|JsonSerializable $params = [] ][, array<string|int, mixed> $files = [] ]) : mixed

Example:

<?php
//simple POST call
$response = $I->sendPost('/message', ['subject' => 'Read this!', 'to' => 'johndoe@example.com']);
//simple upload method
$I->sendPost('/message/24', ['inline' => 0], ['attachmentFile' => codecept_data_dir('sample_file.pdf')]);
//uploading a file with a custom name and mime-type. This is also useful to simulate upload errors.
$I->sendPost('/message/24', ['inline' => 0], [
    'attachmentFile' => [
         'name' => 'document.pdf',
         'type' => 'application/pdf',
         'error' => UPLOAD_ERR_OK,
         'size' => filesize(codecept_data_dir('sample_file.pdf')),
         'tmp_name' => codecept_data_dir('sample_file.pdf')
    ]
]);
// If your field names contain square brackets (e.g. `<input type="text" name="form[task]">`),
// PHP parses them into an array. In this case you need to pass the fields like this:
$I->sendPost('/add-task', ['form' => [
    'task' => 'lorem ipsum',
    'category' => 'miscellaneous',
]]);
Parameters
$url : mixed
$params : array<string|int, mixed>|string|JsonSerializable = []
$files : array<string|int, mixed> = []

A list of filenames or "mocks" of $_FILES (each entry being an array with the following keys: name, type, error, size, tmp_name (pointing to the real file path). Each key works as the "name" attribute of a file input field.

Tags
see
http://php.net/manual/en/features.file-upload.post-method.php
see
codecept_data_dir()
part

json

part

xml

sendPut()

Sends PUT request to given uri.

public sendPut(mixed $url[, array<string|int, mixed>|string|JsonSerializable $params = [] ][, array<string|int, mixed> $files = [] ]) : mixed
<?php
$response = $I->sendPut('/message/1', ['subject' => 'Read this!']);
Parameters
$url : mixed
$params : array<string|int, mixed>|string|JsonSerializable = []
$files : array<string|int, mixed> = []
Tags
part

json

part

xml

Sends UNLINK request to given uri.

public sendUnlink(mixed $url, array<string|int, mixed> $linkEntries) : mixed
Parameters
$url : mixed
$linkEntries : array<string|int, mixed>

(entry is array with keys "uri" and "link-param")

Tags
link
http://tools.ietf.org/html/rfc2068#section-19.6.2.4
author

samva.ua@gmail.com

part

json

part

xml

setServerParameters()

Sets SERVER parameters valid for all next requests.

public setServerParameters(array<string|int, mixed> $params) : mixed

this will remove old ones.

$I->setServerParameters([]);
Parameters
$params : array<string|int, mixed>

startFollowingRedirects()

Enables automatic redirects to be followed by the client

public startFollowingRedirects() : mixed
<?php
$I->startFollowingRedirects();
Tags
part

xml

part

json

stopFollowingRedirects()

Prevents automatic redirects to be followed by the client

public stopFollowingRedirects() : mixed
<?php
$I->stopFollowingRedirects();
Tags
part

xml

part

json

assert()

protected assert(mixed $arguments[, bool $not = false ]) : mixed
Parameters
$arguments : mixed
$not : bool = false

assertFileNotExists()

Asserts that a file does not exist.

protected assertFileNotExists(string $filename[, string $message = '' ]) : mixed
Parameters
$filename : string
$message : string = ''

assertGreaterOrEquals()

Asserts that a value is greater than or equal to another value.

protected assertGreaterOrEquals(mixed $expected, mixed $actual[, string $message = '' ]) : mixed
Parameters
$expected : mixed
$actual : mixed
$message : string = ''

assertIsEmpty()

Asserts that a variable is empty.

protected assertIsEmpty(mixed $actual[, string $message = '' ]) : mixed
Parameters
$actual : mixed
$message : string = ''

assertLessOrEquals()

Asserts that a value is smaller than or equal to another value.

protected assertLessOrEquals(mixed $expected, mixed $actual[, string $message = '' ]) : mixed
Parameters
$expected : mixed
$actual : mixed
$message : string = ''

assertNot()

protected assertNot(mixed $arguments) : mixed
Parameters
$arguments : mixed

assertNotRegExp()

Asserts that a string does not match a given regular expression.

protected assertNotRegExp(string $pattern, string $string[, string $message = '' ]) : mixed
Parameters
$pattern : string
$string : string
$message : string = ''

assertRegExp()

Asserts that a string matches a given regular expression.

protected assertRegExp(string $pattern, string $string[, string $message = '' ]) : mixed
Parameters
$pattern : string
$string : string
$message : string = ''

assertThatItsNot()

Evaluates a PHPUnit\Framework\Constraint matcher object.

protected assertThatItsNot(mixed $value, Constraint $constraint[, string $message = '' ]) : mixed
Parameters
$value : mixed
$constraint : Constraint
$message : string = ''

binaryToDebugString()

Format a binary string for debug printing

protected binaryToDebugString(string $data) : string
Parameters
$data : string

the binary data string

Return values
string

the debug string

debug()

Print debug message to the screen.

protected debug(mixed $message) : mixed
Parameters
$message : mixed

debugSection()

Print debug message with a title

protected debugSection(mixed $title, mixed $message) : mixed
Parameters
$title : mixed
$message : mixed

decodeAndValidateJson()

Converts string to json and asserts that no error occured while decoding.

protected decodeAndValidateJson(string $jsonString[, string $errorFormat = "Invalid json: %s. System message: %s." ]) : mixed
Parameters
$jsonString : string

the json encoded string

$errorFormat : string = "Invalid json: %s. System message: %s."

optional string for custom sprintf format

encodeApplicationJson()

protected encodeApplicationJson(mixed $method, mixed $parameters) : mixed
Parameters
$method : mixed
$parameters : mixed

execute()

protected execute(mixed $method, mixed $url[, mixed $parameters = [] ][, mixed $files = [] ]) : mixed
Parameters
$method : mixed
$url : mixed
$parameters : mixed = []
$files : mixed = []

getModule()

Get another module by its name:

protected getModule(mixed $name) : Module
<?php
$this->getModule('WebDriver')->_findElements('.items');
Parameters
$name : mixed
Tags
throws
ModuleException
Return values
Module

getModules()

Get all enabled modules

protected getModules() : array<string|int, mixed>
Return values
array<string|int, mixed>

getRunningClient()

protected getRunningClient() : mixed

hasModule()

Checks that module is enabled.

protected hasModule(mixed $name) : bool
Parameters
$name : mixed
Return values
bool

isBinaryData()

Check if data has non-printable bytes and it is not a valid unicode string

protected isBinaryData(string $data) : bool
Parameters
$data : string

the text or binary data string

Return values
bool

onReconfigure()

HOOK to be executed when config changes with `_reconfigure`.

protected onReconfigure() : mixed

resetVariables()

protected resetVariables() : mixed

scalarizeArray()

protected scalarizeArray(mixed $array) : mixed
Parameters
$array : mixed

shortenMessage()

Short text message to an amount of chars

protected shortenMessage(mixed $message[, mixed $chars = 150 ]) : string
Parameters
$message : mixed
$chars : mixed = 150
Return values
string

validateConfig()

Extends the function Module::validateConfig for shorten messages

protected validateConfig() : mixed

checkFileBeforeUpload()

private checkFileBeforeUpload(mixed $file) : mixed
Parameters
$file : mixed

formatFilesArray()

private formatFilesArray(array<string|int, mixed> $files) : mixed
Parameters
$files : array<string|int, mixed>

getFileType()

private getFileType(mixed $file) : mixed
Parameters
$file : mixed

Sets Headers "Link" as one header "Link" based on linkEntries

private setHeaderLink(array<string|int, mixed> $linkEntries) : mixed
Parameters
$linkEntries : array<string|int, mixed>

(entry is array with keys "uri" and "link-param")

Tags
link
http://tools.ietf.org/html/rfc2068#section-19.6.2.4
author

samva.ua@gmail.com


        
On this page

Search results