This commit is contained in:
2020-10-06 14:27:47 +07:00
commit 586be80cf6
16613 changed files with 3274099 additions and 0 deletions

View File

@@ -0,0 +1,202 @@
# AMQP
This module interacts with message broker software that implements
the Advanced Message Queuing Protocol (AMQP) standard. For example, RabbitMQ (tested).
<div class="alert alert-info">
To use this module with Composer you need <em>"php-amqplib/php-amqplib": "~2.4"</em> package.
</div>
## Config
* host: localhost - host to connect
* username: guest - username to connect
* password: guest - password to connect
* vhost: '/' - vhost to connect
* cleanup: true - defined queues will be purged before running every test.
* queues: [mail, twitter] - queues to cleanup
* single_channel - create and use only one channel during test execution
### Example
modules:
enabled:
- AMQP:
host: 'localhost'
port: '5672'
username: 'guest'
password: 'guest'
vhost: '/'
queues: [queue1, queue2]
single_channel: false
## Public Properties
* connection - AMQPStreamConnection - current connection
## Actions
### bindQueueToExchange
Binds a queue to an exchange
This is an alias of method `queue_bind` of `PhpAmqpLib\Channel\AMQPChannel`.
```php
<?php
$I->bindQueueToExchange(
'nameOfMyQueueToBind', // name of the queue
'transactionTracking.transaction', // exchange name to bind to
'your.routing.key' // Optionally, provide a binding key
)
```
* `param string` $queue
* `param string` $exchange
* `param string` $routing_key
* `param bool` $nowait
* `param array` $arguments
* `param int` $ticket
* `return` mixed|null
### declareExchange
Declares an exchange
This is an alias of method `exchange_declare` of `PhpAmqpLib\Channel\AMQPChannel`.
```php
<?php
$I->declareExchange(
'nameOfMyExchange', // exchange name
'topic' // exchange type
)
```
* `param string` $exchange
* `param string` $type
* `param bool` $passive
* `param bool` $durable
* `param bool` $auto_delete
* `param bool` $internal
* `param bool` $nowait
* `param array` $arguments
* `param int` $ticket
* `return` mixed|null
### declareQueue
Declares queue, creates if needed
This is an alias of method `queue_declare` of `PhpAmqpLib\Channel\AMQPChannel`.
```php
<?php
$I->declareQueue(
'nameOfMyQueue', // exchange name
)
```
* `param string` $queue
* `param bool` $passive
* `param bool` $durable
* `param bool` $exclusive
* `param bool` $auto_delete
* `param bool` $nowait
* `param array` $arguments
* `param int` $ticket
* `return` mixed|null
### grabMessageFromQueue
Takes last message from queue.
``` php
<?php
$message = $I->grabMessageFromQueue('queue.emails');
?>
```
* `param string` $queue
* `return` \PhpAmqpLib\Message\AMQPMessage
### purgeAllQueues
Purge all queues defined in config.
``` php
<?php
$I->purgeAllQueues();
?>
```
### purgeQueue
Purge a specific queue defined in config.
``` php
<?php
$I->purgeQueue('queue.emails');
?>
```
* `param string` $queueName
### pushToExchange
Sends message to exchange by sending exchange name, message
and (optionally) a routing key
``` php
<?php
$I->pushToExchange('exchange.emails', 'thanks');
$I->pushToExchange('exchange.emails', new AMQPMessage('Thanks!'));
$I->pushToExchange('exchange.emails', new AMQPMessage('Thanks!'), 'severity');
?>
```
* `param string` $exchange
* `param string|\PhpAmqpLib\Message\AMQPMessage` $message
* `param string` $routing_key
### pushToQueue
Sends message to queue
``` php
<?php
$I->pushToQueue('queue.jobs', 'create user');
$I->pushToQueue('queue.jobs', new AMQPMessage('create'));
?>
```
* `param string` $queue
* `param string|\PhpAmqpLib\Message\AMQPMessage` $message
### seeMessageInQueueContainsText
Checks if message containing text received.
**This method drops message from queue**
**This method will wait for message. If none is sent the script will stuck**.
``` php
<?php
$I->pushToQueue('queue.emails', 'Hello, davert');
$I->seeMessageInQueueContainsText('queue.emails','davert');
?>
```
* `param string` $queue
* `param string` $text
<p>&nbsp;</p><div class="alert alert-warning">Module reference is taken from the source code. <a href="https://github.com/Codeception/Codeception/tree/2.4/src/Codeception/Module/AMQP.php">Help us to improve documentation. Edit module reference</a></div>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,115 @@
# Apc
This module interacts with the [Alternative PHP Cache (APC)](http://php.net/manual/en/intro.apcu.php)
using either _APCu_ or _APC_ extension.
Performs a cleanup by flushing all values after each test run.
## Status
* Maintainer: **Serghei Iakovlev**
* Stability: **stable**
* Contact: serghei@phalconphp.com
### Example (`unit.suite.yml`)
```yaml
modules:
- Apc
```
Be sure you don't use the production server to connect.
## Actions
### dontSeeInApc
Checks item in APC(u) doesn't exist or is the same as expected.
Examples:
``` php
<?php
// With only one argument, only checks the key does not exist
$I->dontSeeInApc('users_count');
// Checks a 'users_count' exists does not exist or its value is not the one provided
$I->dontSeeInApc('users_count', 200);
?>
```
* `param string|string[]` $key
* `param mixed` $value
### flushApc
Clears the APC(u) cache
### grabValueFromApc
Grabs value from APC(u) by key.
Example:
``` php
<?php
$users_count = $I->grabValueFromApc('users_count');
?>
```
* `param string|string[]` $key
### haveInApc
Stores an item `$value` with `$key` on the APC(u).
Examples:
```php
<?php
// Array
$I->haveInApc('users', ['name' => 'miles', 'email' => 'miles@davis.com']);
// Object
$I->haveInApc('user', UserRepository::findFirst());
// Key as array of 'key => value'
$entries = [];
$entries['key1'] = 'value1';
$entries['key2'] = 'value2';
$entries['key3'] = ['value3a','value3b'];
$entries['key4'] = 4;
$I->haveInApc($entries, null);
?>
```
* `param string|array` $key
* `param mixed` $value
* `param int` $expiration
### seeInApc
Checks item in APC(u) exists and the same as expected.
Examples:
``` php
<?php
// With only one argument, only checks the key exists
$I->seeInApc('users_count');
// Checks a 'users_count' exists and has the value 200
$I->seeInApc('users_count', 200);
?>
```
* `param string|string[]` $key
* `param mixed` $value
<p>&nbsp;</p><div class="alert alert-warning">Module reference is taken from the source code. <a href="https://github.com/Codeception/Codeception/tree/2.4/src/Codeception/Module/Apc.php">Help us to improve documentation. Edit module reference</a></div>

View File

@@ -0,0 +1,350 @@
# Asserts
Special module for using asserts in your tests.
## Actions
### assertArrayHasKey
* `param` $key
* `param` $actual
* `param` $description
### assertArrayNotHasKey
* `param` $key
* `param` $actual
* `param` $description
### assertArraySubset
Checks that array contains subset.
* `param array` $subset
* `param array` $array
* `param bool` $strict
* `param string` $message
### assertContains
Checks that haystack contains needle
* `param` $needle
* `param` $haystack
* `param string` $message
### assertCount
* `param` $expectedCount
* `param` $actual
* `param` $description
### assertEmpty
Checks that variable is empty.
* `param` $actual
* `param string` $message
### assertEquals
Checks that two variables are equal. If you're comparing floating-point values,
you can specify the optional "delta" parameter which dictates how great of a precision
error are you willing to tolerate in order to consider the two values equal.
Regular example:
```php
<?php
$I->assertEquals($element->getChildrenCount(), 5);
```
Floating-point example:
```php
<?php
$I->assertEquals($calculator->add(0.1, 0.2), 0.3, 'Calculator should add the two numbers correctly.', 0.01);
```
* `param` $expected
* `param` $actual
* `param string` $message
* `param float` $delta
### assertFalse
Checks that condition is negative.
* `param` $condition
* `param string` $message
### assertFileExists
Checks if file exists
* `param string` $filename
* `param string` $message
### assertFileNotExists
Checks if file doesn't exist
* `param string` $filename
* `param string` $message
### assertGreaterOrEquals
* `param` $expected
* `param` $actual
* `param` $description
### assertGreaterThan
Checks that actual is greater than expected
* `param` $expected
* `param` $actual
* `param string` $message
### assertGreaterThanOrEqual
Checks that actual is greater or equal than expected
* `param` $expected
* `param` $actual
* `param string` $message
### assertInstanceOf
* `param` $class
* `param` $actual
* `param` $description
### assertInternalType
* `param` $type
* `param` $actual
* `param` $description
### assertIsEmpty
* `param` $actual
* `param` $description
### assertLessOrEquals
* `param` $expected
* `param` $actual
* `param` $description
### assertLessThan
Checks that actual is less than expected
* `param` $expected
* `param` $actual
* `param string` $message
### assertLessThanOrEqual
Checks that actual is less or equal than expected
* `param` $expected
* `param` $actual
* `param string` $message
### assertNotContains
Checks that haystack doesn't contain needle.
* `param` $needle
* `param` $haystack
* `param string` $message
### assertNotEmpty
Checks that variable is not empty.
* `param` $actual
* `param string` $message
### assertNotEquals
Checks that two variables are not equal. If you're comparing floating-point values,
you can specify the optional "delta" parameter which dictates how great of a precision
error are you willing to tolerate in order to consider the two values not equal.
Regular example:
```php
<?php
$I->assertNotEquals($element->getChildrenCount(), 0);
```
Floating-point example:
```php
<?php
$I->assertNotEquals($calculator->add(0.1, 0.2), 0.4, 'Calculator should add the two numbers correctly.', 0.01);
```
* `param` $expected
* `param` $actual
* `param string` $message
* `param float` $delta
### assertNotFalse
Checks that the condition is NOT false (everything but false)
* `param` $condition
* `param string` $message
### assertNotInstanceOf
* `param` $class
* `param` $actual
* `param` $description
### assertNotNull
Checks that variable is not NULL
* `param` $actual
* `param string` $message
### assertNotRegExp
Checks that string not match with pattern
* `param string` $pattern
* `param string` $string
* `param string` $message
### assertNotSame
Checks that two variables are not same
* `param` $expected
* `param` $actual
* `param string` $message
### assertNotTrue
Checks that the condition is NOT true (everything but true)
* `param` $condition
* `param string` $message
### assertNull
Checks that variable is NULL
* `param` $actual
* `param string` $message
### assertRegExp
Checks that string match with pattern
* `param string` $pattern
* `param string` $string
* `param string` $message
### assertSame
Checks that two variables are same
* `param` $expected
* `param` $actual
* `param string` $message
### assertStringStartsNotWith
Checks that a string doesn't start with the given prefix.
* `param string` $prefix
* `param string` $string
* `param string` $message
### assertStringStartsWith
Checks that a string starts with the given prefix.
* `param string` $prefix
* `param string` $string
* `param string` $message
### assertTrue
Checks that condition is positive.
* `param` $condition
* `param string` $message
### expectException
Handles and checks exception called inside callback function.
Either exception class name or exception instance should be provided.
```php
<?php
$I->expectException(MyException::class, function() {
$this->doSomethingBad();
});
$I->expectException(new MyException(), function() {
$this->doSomethingBad();
});
```
If you want to check message or exception code, you can pass them with exception instance:
```php
<?php
// will check that exception MyException is thrown with "Don't do bad things" message
$I->expectException(new MyException("Don't do bad things"), function() {
$this->doSomethingBad();
});
```
* `param` $exception string or \Exception
* `param` $callback
### fail
Fails the test with message.
* `param` $message
<p>&nbsp;</p><div class="alert alert-warning">Module reference is taken from the source code. <a href="https://github.com/Codeception/Codeception/tree/2.4/src/Codeception/Module/Asserts.php">Help us to improve documentation. Edit module reference</a></div>

View File

@@ -0,0 +1,75 @@
# Cli
Wrapper for basic shell commands and shell output
## Responsibility
* Maintainer: **davert**
* Status: **stable**
* Contact: codecept@davert.mail.ua
*Please review the code of non-stable modules and provide patches if you have issues.*
## Actions
### dontSeeInShellOutput
Checks that output from latest command doesn't contain text
* `param` $text
### runShellCommand
Executes a shell command.
Fails If exit code is > 0. You can disable this by setting second parameter to false
```php
<?php
$I->runShellCommand('phpunit');
// do not fail test when command fails
$I->runShellCommand('phpunit', false);
```
* `param` $command
* `param bool` $failNonZero
### seeInShellOutput
Checks that output from last executed command contains text
* `param` $text
### seeResultCodeIs
Checks result code
```php
<?php
$I->seeResultCodeIs(0);
```
* `param` $code
### seeResultCodeIsNot
Checks result code
```php
<?php
$I->seeResultCodeIsNot(0);
```
* `param` $code
### seeShellOutputMatches
* `param` $regex
<p>&nbsp;</p><div class="alert alert-warning">Module reference is taken from the source code. <a href="https://github.com/Codeception/Codeception/tree/2.4/src/Codeception/Module/Cli.php">Help us to improve documentation. Edit module reference</a></div>

View File

@@ -0,0 +1,166 @@
# DataFactory
DataFactory allows you to easily generate and create test data using [**FactoryMuffin**](https://github.com/thephpleague/factory-muffin).
DataFactory uses an ORM of your application to define, save and cleanup data. Thus, should be used with ORM or Framework modules.
This module requires packages installed:
```json
{
"league/factory-muffin": "^3.0",
}
```
Generation rules can be defined in a factories file. You will need to create `factories.php` (it is recommended to store it in `_support` dir)
Follow [FactoryMuffin documentation](https://github.com/thephpleague/factory-muffin) to set valid rules.
Random data provided by [Faker](https://github.com/fzaninotto/Faker) library.
```php
<?php
use League\FactoryMuffin\Faker\Facade as Faker;
$fm->define(User::class)->setDefinitions([
'name' => Faker::name(),
// generate email
'email' => Faker::email(),
'body' => Faker::text(),
// generate a profile and return its Id
'profile_id' => 'factory|Profile'
]);
```
Configure this module to load factory definitions from a directory.
You should also specify a module with an ORM as a dependency.
```yaml
modules:
enabled:
- Yii2:
configFile: path/to/config.php
- DataFactory:
factories: tests/_support/factories
depends: Yii2
```
(you can also use Laravel5 and Phalcon).
In this example factories are loaded from `tests/_support/factories` directory. Please note that this directory is relative from the codeception.yml file (so for Yii2 it would be codeception/_support/factories).
You should create this directory manually and create PHP files in it with factories definitions following [official documentation](https://github.com/thephpleague/factory-muffin#usage).
In cases you want to use data from database inside your factory definitions you can define them in Helper.
For instance, if you use Doctrine, this allows you to access `EntityManager` inside a definition.
To proceed you should create Factories helper via `generate:helper` command and enable it:
```
modules:
enabled:
- DataFactory:
depends: Doctrine2
- \Helper\Factories
```
In this case you can define factories from a Helper class with `_define` method.
```php
<?php
public function _beforeSuite()
{
$factory = $this->getModule('DataFactory');
// let us get EntityManager from Doctrine
$em = $this->getModule('Doctrine2')->_getEntityManager();
$factory->_define(User::class, [
// generate random user name
// use League\FactoryMuffin\Faker\Facade as Faker;
'name' => Faker::name(),
// get real company from database
'company' => $em->getRepository(Company::class)->find(),
// let's generate a profile for each created user
// receive an entity and set it via `setProfile` method
// UserProfile factory should be defined as well
'profile' => 'entity|'.UserProfile::class
]);
}
```
Factory Definitions are described in official [Factory Muffin Documentation](https://github.com/thephpleague/factory-muffin)
### Related Models Generators
If your module relies on other model you can generate them both.
To create a related module you can use either `factory` or `entity` prefix, depending on ORM you use.
In case your ORM expects an Id of a related record (Eloquent) to be set use `factory` prefix:
```php
'user_id' => 'factory|User'
```
In case your ORM expects a related record itself (Doctrine) then you should use `entity` prefix:
```php
'user' => 'entity|User'
```
## Actions
### have
Generates and saves a record,.
```php
$I->have('User'); // creates user
$I->have('User', ['is_active' => true]); // creates active user
```
Returns an instance of created user.
* `param string` $name
* `param array` $extraAttrs
* `return` object
### haveMultiple
Generates and saves a record multiple times.
```php
$I->haveMultiple('User', 10); // create 10 users
$I->haveMultiple('User', 10, ['is_active' => true]); // create 10 active users
```
* `param string` $name
* `param int` $times
* `param array` $extraAttrs
* `return` \object[]
### make
Generates a record instance.
This does not save it in the database. Use `have` for that.
```php
$user = $I->make('User'); // return User instance
$activeUser = $I->make('User', ['is_active' => true]); // return active user instance
```
Returns an instance of created user without creating a record in database.
* `param string` $name
* `param array` $extraAttrs
* `return` object
<p>&nbsp;</p><div class="alert alert-warning">Module reference is taken from the source code. <a href="https://github.com/Codeception/Codeception/tree/2.4/src/Codeception/Module/DataFactory.php">Help us to improve documentation. Edit module reference</a></div>

View File

@@ -0,0 +1,327 @@
# Db
Access a database.
The most important function of this module is to clean a database before each test.
This module also provides actions to perform checks in a database, e.g. [seeInDatabase()](http://codeception.com/docs/modules/Db#seeInDatabase)
In order to have your database populated with data you need a raw SQL dump.
Simply put the dump in the `tests/_data` directory (by default) and specify the path in the config.
The next time after the database is cleared, all your data will be restored from the dump.
Don't forget to include `CREATE TABLE` statements in the dump.
Supported and tested databases are:
* MySQL
* SQLite (i.e. just one file)
* PostgreSQL
Also available:
* MS SQL
* Oracle
Connection is done by database Drivers, which are stored in the `Codeception\Lib\Driver` namespace.
[Check out the drivers](https://github.com/Codeception/Codeception/tree/2.3/src/Codeception/Lib/Driver)
if you run into problems loading dumps and cleaning databases.
## Config
* dsn *required* - PDO DSN
* user *required* - username to access database
* password *required* - password
* dump - path to database dump
* populate: false - whether the the dump should be loaded before the test suite is started
* cleanup: false - whether the dump should be reloaded before each test
* reconnect: false - whether the module should reconnect to the database before each test
* waitlock: 0 - wait lock (in seconds) that the database session should use for DDL statements
* ssl_key - path to the SSL key (MySQL specific, @see http://php.net/manual/de/ref.pdo-mysql.php#pdo.constants.mysql-attr-key)
* ssl_cert - path to the SSL certificate (MySQL specific, @see http://php.net/manual/de/ref.pdo-mysql.php#pdo.constants.mysql-attr-ssl-cert)
* ssl_ca - path to the SSL certificate authority (MySQL specific, @see http://php.net/manual/de/ref.pdo-mysql.php#pdo.constants.mysql-attr-ssl-ca)
* ssl_verify_server_cert - disables certificate CN verification (MySQL specific, @see http://php.net/manual/de/ref.pdo-mysql.php)
* ssl_cipher - list of one or more permissible ciphers to use for SSL encryption (MySQL specific, @see http://php.net/manual/de/ref.pdo-mysql.php#pdo.constants.mysql-attr-cipher)
## Example
modules:
enabled:
- Db:
dsn: 'mysql:host=localhost;dbname=testdb'
user: 'root'
password: ''
dump: 'tests/_data/dump.sql'
populate: true
cleanup: true
reconnect: true
waitlock: 10
ssl_key: '/path/to/client-key.pem'
ssl_cert: '/path/to/client-cert.pem'
ssl_ca: '/path/to/ca-cert.pem'
ssl_verify_server_cert: false
ssl_cipher: 'AES256-SHA'
## SQL data dump
There are two ways of loading the dump into your database:
### Populator
The recommended approach is to configure a `populator`, an external command to load a dump. Command parameters like host, username, password, database
can be obtained from the config and inserted into placeholders:
For MySQL:
```yaml
modules:
enabled:
- Db:
dsn: 'mysql:host=localhost;dbname=testdb'
user: 'root'
password: ''
dump: 'tests/_data/dump.sql'
populate: true # run populator before all tests
cleanup: true # run populator before each test
populator: 'mysql -u $user -h $host $dbname < $dump'
```
For PostgreSQL (using pg_restore)
```
modules:
enabled:
- Db:
dsn: 'pgsql:host=localhost;dbname=testdb'
user: 'root'
password: ''
dump: 'tests/_data/db_backup.dump'
populate: true # run populator before all tests
cleanup: true # run populator before each test
populator: 'pg_restore -u $user -h $host -D $dbname < $dump'
```
Variable names are being taken from config and DSN which has a `keyword=value` format, so you should expect to have a variable named as the
keyword with the full value inside it.
PDO dsn elements for the supported drivers:
* MySQL: [PDO_MYSQL DSN](https://secure.php.net/manual/en/ref.pdo-mysql.connection.php)
* SQLite: [PDO_SQLITE DSN](https://secure.php.net/manual/en/ref.pdo-sqlite.connection.php)
* PostgreSQL: [PDO_PGSQL DSN](https://secure.php.net/manual/en/ref.pdo-pgsql.connection.php)
* MSSQL: [PDO_SQLSRV DSN](https://secure.php.net/manual/en/ref.pdo-sqlsrv.connection.php)
* Oracle: [PDO_OCI DSN](https://secure.php.net/manual/en/ref.pdo-oci.connection.php)
### Dump
Db module by itself can load SQL dump without external tools by using current database connection.
This approach is system-independent, however, it is slower than using a populator and may have parsing issues (see below).
Provide a path to SQL file in `dump` config option:
```yaml
modules:
enabled:
- Db:
dsn: 'mysql:host=localhost;dbname=testdb'
user: 'root'
password: ''
populate: true # load dump before all tests
cleanup: true # load dump for each test
dump: 'tests/_data/dump.sql'
```
To parse SQL Db file, it should follow this specification:
* Comments are permitted.
* The `dump.sql` may contain multiline statements.
* The delimiter, a semi-colon in this case, must be on the same line as the last statement:
```sql
-- Add a few contacts to the table.
REPLACE INTO `Contacts` (`created`, `modified`, `status`, `contact`, `first`, `last`) VALUES
(NOW(), NOW(), 1, 'Bob Ross', 'Bob', 'Ross'),
(NOW(), NOW(), 1, 'Fred Flintstone', 'Fred', 'Flintstone');
-- Remove existing orders for testing.
DELETE FROM `Order`;
```
## Query generation
`seeInDatabase`, `dontSeeInDatabase`, `seeNumRecords`, `grabFromDatabase` and `grabNumRecords` methods
accept arrays as criteria. WHERE condition is generated using item key as a field name and
item value as a field value.
Example:
```php
<?php
$I->seeInDatabase('users', array('name' => 'Davert', 'email' => 'davert@mail.com'));
```
Will generate:
```sql
SELECT COUNT(*) FROM `users` WHERE `name` = 'Davert' AND `email` = 'davert@mail.com'
```
Since version 2.1.9 it's possible to use LIKE in a condition, as shown here:
```php
<?php
$I->seeInDatabase('users', array('name' => 'Davert', 'email like' => 'davert%'));
```
Will generate:
```sql
SELECT COUNT(*) FROM `users` WHERE `name` = 'Davert' AND `email` LIKE 'davert%'
```
## Public Properties
* dbh - contains the PDO connection
* driver - contains the Connection Driver
## Actions
### dontSeeInDatabase
Effect is opposite to ->seeInDatabase
Asserts that there is no record with the given column values in a database.
Provide table name and column values.
``` php
<?php
$I->dontSeeInDatabase('users', ['name' => 'Davert', 'email' => 'davert@mail.com']);
```
Fails if such user was found.
Comparison expressions can be used as well:
```php
<?php
$I->dontSeeInDatabase('posts', ['num_comments >=' => '0']);
$I->dontSeeInDatabase('users', ['email like' => 'miles%']);
```
Supported operators: `<`, `>`, `>=`, `<=`, `!=`, `like`.
* `param string` $table
* `param array` $criteria
### grabColumnFromDatabase
Fetches all values from the column in database.
Provide table name, desired column and criteria.
``` php
<?php
$mails = $I->grabColumnFromDatabase('users', 'email', array('name' => 'RebOOter'));
```
* `param string` $table
* `param string` $column
* `param array` $criteria
* `return` array
### grabFromDatabase
Fetches all values from the column in database.
Provide table name, desired column and criteria.
``` php
<?php
$mails = $I->grabFromDatabase('users', 'email', array('name' => 'RebOOter'));
```
* `param string` $table
* `param string` $column
* `param array` $criteria
* `return` array
### grabNumRecords
Returns the number of rows in a database
* `param string` $table Table name
* `param array` $criteria Search criteria [Optional]
* `return` int
### haveInDatabase
Inserts an SQL record into a database. This record will be erased after the test.
```php
<?php
$I->haveInDatabase('users', array('name' => 'miles', 'email' => 'miles@davis.com'));
?>
```
* `param string` $table
* `param array` $data
* `return integer` $id
### isPopulated
__not documented__
### seeInDatabase
Asserts that a row with the given column values exists.
Provide table name and column values.
```php
<?php
$I->seeInDatabase('users', ['name' => 'Davert', 'email' => 'davert@mail.com']);
```
Fails if no such user found.
Comparison expressions can be used as well:
```php
<?php
$I->seeInDatabase('posts', ['num_comments >=' => '0']);
$I->seeInDatabase('users', ['email like' => 'miles@davis.com']);
```
Supported operators: `<`, `>`, `>=`, `<=`, `!=`, `like`.
* `param string` $table
* `param array` $criteria
### seeNumRecords
Asserts that the given number of records were found in the database.
```php
<?php
$I->seeNumRecords(1, 'users', ['name' => 'davert'])
?>
```
* `param int` $expectedNumber Expected number
* `param string` $table Table name
* `param array` $criteria Search criteria [Optional]
### updateInDatabase
Update an SQL record into a database.
```php
<?php
$I->updateInDatabase('users', array('isAdmin' => true), array('email' => 'miles@davis.com'));
?>
```
* `param string` $table
* `param array` $data
* `param array` $criteria
<p>&nbsp;</p><div class="alert alert-warning">Module reference is taken from the source code. <a href="https://github.com/Codeception/Codeception/tree/2.4/src/Codeception/Module/Db.php">Help us to improve documentation. Edit module reference</a></div>

View File

@@ -0,0 +1,193 @@
# Doctrine2
Access the database using [Doctrine2 ORM](http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/).
When used with Zend Framework 2 or Symfony2, Doctrine's Entity Manager is automatically retrieved from Service Locator.
Set up your `functional.suite.yml` like this:
```
modules:
enabled:
- Symfony # 'ZF2' or 'Symfony'
- Doctrine2:
depends: Symfony
cleanup: true # All doctrine queries will be wrapped in a transaction, which will be rolled back at the end of each test
```
If you don't use Symfony or Zend Framework, you need to specify a callback function to retrieve the Entity Manager:
```
modules:
enabled:
- Doctrine2:
connection_callback: ['MyDb', 'createEntityManager']
cleanup: true # All doctrine queries will be wrapped in a transaction, which will be rolled back at the end of each test
```
This will use static method of `MyDb::createEntityManager()` to establish the Entity Manager.
By default, the module will wrap everything into a transaction for each test and roll it back afterwards. By doing this
tests will run much faster and will be isolated from each other.
## Status
* Maintainer: **davert**
* Stability: **stable**
* Contact: codecept@davert.mail.ua
## Config
## Public Properties
* `em` - Entity Manager
## Actions
### dontSeeInRepository
Flushes changes to database and performs `findOneBy()` call for current repository.
* `param` $entity
* `param array` $params
### flushToDatabase
Performs $em->flush();
### grabEntitiesFromRepository
Selects entities from repository.
It builds query based on array of parameters.
You can use entity associations to build complex queries.
Example:
``` php
<?php
$users = $I->grabEntitiesFromRepository('AppBundle:User', array('name' => 'davert'));
?>
```
* `Available since` 1.1
* `param` $entity
* `param array` $params
* `return` array
### grabEntityFromRepository
Selects a single entity from repository.
It builds query based on array of parameters.
You can use entity associations to build complex queries.
Example:
``` php
<?php
$user = $I->grabEntityFromRepository('User', array('id' => '1234'));
?>
```
* `Available since` 1.1
* `param` $entity
* `param array` $params
* `return` object
### grabFromRepository
Selects field value from repository.
It builds query based on array of parameters.
You can use entity associations to build complex queries.
Example:
``` php
<?php
$email = $I->grabFromRepository('User', 'email', array('name' => 'davert'));
?>
```
* `Available since` 1.1
* `param` $entity
* `param` $field
* `param array` $params
* `return` array
### haveFakeRepository
Mocks the repository.
With this action you can redefine any method of any repository.
Please, note: this fake repositories will be accessible through entity manager till the end of test.
Example:
``` php
<?php
$I->haveFakeRepository('Entity\User', array('findByUsername' => function($username) { return null; }));
```
This creates a stub class for Entity\User repository with redefined method findByUsername,
which will always return the NULL value.
* `param` $classname
* `param array` $methods
### haveInRepository
Persists record into repository.
This method creates an entity, and sets its properties directly (via reflection).
Setters of entity won't be executed, but you can create almost any entity and save it to database.
Returns id using `getId` of newly created entity.
```php
$I->haveInRepository('Entity\User', array('name' => 'davert'));
```
### persistEntity
Adds entity to repository and flushes. You can redefine it's properties with the second parameter.
Example:
``` php
<?php
$I->persistEntity(new \Entity\User, array('name' => 'Miles'));
$I->persistEntity($user, array('name' => 'Miles'));
```
* `param` $obj
* `param array` $values
### seeInRepository
Flushes changes to database, and executes a query with parameters defined in an array.
You can use entity associations to build complex queries.
Example:
``` php
<?php
$I->seeInRepository('AppBundle:User', array('name' => 'davert'));
$I->seeInRepository('User', array('name' => 'davert', 'Company' => array('name' => 'Codegyre')));
$I->seeInRepository('Client', array('User' => array('Company' => array('name' => 'Codegyre')));
?>
```
Fails if record for given criteria can\'t be found,
* `param` $entity
* `param array` $params
<p>&nbsp;</p><div class="alert alert-warning">Module reference is taken from the source code. <a href="https://github.com/Codeception/Codeception/tree/2.4/src/Codeception/Module/Doctrine2.php">Help us to improve documentation. Edit module reference</a></div>

View File

@@ -0,0 +1,429 @@
# FTP
Works with SFTP/FTP servers.
In order to test the contents of a specific file stored on any remote FTP/SFTP system
this module downloads a temporary file to the local system. The temporary directory is
defined by default as ```tests/_data``` to specify a different directory set the tmp config
option to your chosen path.
Don't forget to create the folder and ensure its writable.
Supported and tested FTP types are:
* FTP
* SFTP
Connection uses php build in FTP client for FTP,
connection to SFTP uses [phpseclib](http://phpseclib.sourceforge.net/) pulled in using composer.
For SFTP, add [phpseclib](http://phpseclib.sourceforge.net/) to require list.
```
"require": {
"phpseclib/phpseclib": "0.3.6"
}
```
## Status
* Maintainer: **nathanmac**
* Stability:
- FTP: **stable**
- SFTP: **stable**
* Contact: nathan.macnamara@outlook.com
## Config
* type: ftp - type of connection ftp/sftp (defaults to ftp).
* host *required* - hostname/ip address of the ftp server.
* port: 21 - port number for the ftp server
* timeout: 90 - timeout settings for connecting the ftp server.
* user: anonymous - user to access ftp server, defaults to anonymous authentication.
* password - password, defaults to empty for anonymous.
* key - path to RSA key for sftp.
* tmp - path to local directory for storing tmp files.
* passive: true - Turns on or off passive mode (FTP only)
* cleanup: true - remove tmp files from local directory on completion.
### Example
#### Example (FTP)
modules:
enabled: [FTP]
config:
FTP:
type: ftp
host: '127.0.0.1'
port: 21
timeout: 120
user: 'root'
password: 'root'
key: ~/.ssh/id_rsa
tmp: 'tests/_data/ftp'
passive: true
cleanup: false
#### Example (SFTP)
modules:
enabled: [FTP]
config:
FTP:
type: sftp
host: '127.0.0.1'
port: 22
timeout: 120
user: 'root'
password: 'root'
key: ''
tmp: 'tests/_data/ftp'
cleanup: false
This module extends the Filesystem module, file contents methods are inherited from this module.
## Actions
### amInPath
Enters a directory on the ftp system - FTP root directory is used by default
* `param` $path
### cleanDir
Erases directory contents on the FTP/SFTP server
``` php
<?php
$I->cleanDir('logs');
?>
```
* `param` $dirname
### copyDir
Currently not supported in this module, overwrite inherited method
* `param` $src
* `param` $dst
### deleteDir
Deletes directory with all subdirectories on the remote FTP/SFTP server
``` php
<?php
$I->deleteDir('vendor');
?>
```
* `param` $dirname
### deleteFile
Deletes a file on the remote FTP/SFTP system
``` php
<?php
$I->deleteFile('composer.lock');
?>
```
* `param` $filename
### deleteThisFile
Deletes a file
### dontSeeFileFound
Checks if file does not exist in path on the remote FTP/SFTP system
* `param` $filename
* `param string` $path
### dontSeeFileFoundMatches
Checks if file does not exist in path on the remote FTP/SFTP system, using regular expression as filename.
DOES NOT OPEN the file when it's exists
* `param` $regex
* `param string` $path
### dontSeeInThisFile
Checks If opened file doesn't contain `text` in it
``` php
<?php
$I->openFile('composer.json');
$I->dontSeeInThisFile('codeception/codeception');
?>
```
* `param string` $text
### grabDirectory
Grabber method to return current working directory
```php
<?php
$pwd = $I->grabDirectory();
?>
```
* `return` string
### grabFileCount
Grabber method for returning file/folders count in directory
```php
<?php
$count = $I->grabFileCount();
$count = $I->grabFileCount('TEST', false); // Include . .. .thumbs.db
?>
```
* `param string` $path
* `param bool` $ignore - suppress '.', '..' and '.thumbs.db'
* `return` int
### grabFileList
Grabber method for returning file/folders listing in an array
```php
<?php
$files = $I->grabFileList();
$count = $I->grabFileList('TEST', false); // Include . .. .thumbs.db
?>
```
* `param string` $path
* `param bool` $ignore - suppress '.', '..' and '.thumbs.db'
* `return` array
### grabFileModified
Grabber method to return last modified timestamp
```php
<?php
$time = $I->grabFileModified('test.txt');
?>
```
* `param` $filename
* `return` bool
### grabFileSize
Grabber method to return file size
```php
<?php
$size = $I->grabFileSize('test.txt');
?>
```
* `param` $filename
* `return` bool
### loginAs
Change the logged in user mid-way through your test, this closes the
current connection to the server and initialises and new connection.
On initiation of this modules you are automatically logged into
the server using the specified config options or defaulted
to anonymous user if not provided.
``` php
<?php
$I->loginAs('user','password');
?>
```
* `param String` $user
* `param String` $password
### makeDir
Create a directory on the server
``` php
<?php
$I->makeDir('vendor');
?>
```
* `param` $dirname
### openFile
Opens a file (downloads from the remote FTP/SFTP system to a tmp directory for processing)
and stores it's content.
Usage:
``` php
<?php
$I->openFile('composer.json');
$I->seeInThisFile('codeception/codeception');
?>
```
* `param` $filename
### renameDir
Rename/Move directory on the FTP/SFTP server
``` php
<?php
$I->renameDir('vendor', 'vendor_old');
?>
```
* `param` $dirname
* `param` $rename
### renameFile
Rename/Move file on the FTP/SFTP server
``` php
<?php
$I->renameFile('composer.lock', 'composer_old.lock');
?>
```
* `param` $filename
* `param` $rename
### seeFileContentsEqual
Checks the strict matching of file contents.
Unlike `seeInThisFile` will fail if file has something more than expected lines.
Better to use with HEREDOC strings.
Matching is done after removing "\r" chars from file content.
``` php
<?php
$I->openFile('process.pid');
$I->seeFileContentsEqual('3192');
?>
```
* `param string` $text
### seeFileFound
Checks if file exists in path on the remote FTP/SFTP system.
DOES NOT OPEN the file when it's exists
``` php
<?php
$I->seeFileFound('UserModel.php','app/models');
?>
```
* `param` $filename
* `param string` $path
### seeFileFoundMatches
Checks if file exists in path on the remote FTP/SFTP system, using regular expression as filename.
DOES NOT OPEN the file when it's exists
``` php
<?php
$I->seeFileFoundMatches('/^UserModel_([0-9]{6}).php$/','app/models');
?>
```
* `param` $regex
* `param string` $path
### seeInThisFile
Checks If opened file has `text` in it.
Usage:
``` php
<?php
$I->openFile('composer.json');
$I->seeInThisFile('codeception/codeception');
?>
```
* `param string` $text
### seeNumberNewLines
Checks If opened file has the `number` of new lines.
Usage:
``` php
<?php
$I->openFile('composer.json');
$I->seeNumberNewLines(5);
?>
```
* `param int` $number New lines
### seeThisFileMatches
Checks that contents of currently opened file matches $regex
* `param string` $regex
### writeToFile
Saves contents to tmp file and uploads the FTP/SFTP system.
Overwrites current file on server if exists.
``` php
<?php
$I->writeToFile('composer.json', 'some data here');
?>
```
* `param` $filename
* `param` $contents
<p>&nbsp;</p><div class="alert alert-warning">Module reference is taken from the source code. <a href="https://github.com/Codeception/Codeception/tree/2.4/src/Codeception/Module/FTP.php">Help us to improve documentation. Edit module reference</a></div>

View File

@@ -0,0 +1,153 @@
# Facebook
Provides testing for projects integrated with Facebook API.
Relies on Facebook's tool Test User API.
<div class="alert alert-info">
To use this module with Composer you need <em>"facebook/php-sdk4": "5.*"</em> package.
</div>
## Status
[ ![Facebook Status for Codeception/Codeception](https://codeship.com/projects/e4bc90d0-1ed5-0134-566c-1ed679ae6c9d/status?branch=2.2)](https://codeship.com/projects/160201)
* Stability: **beta**
* Maintainer: **tiger-seo**
* Contact: tiger.seo@codeception.com
## Config
* app_id *required* - Facebook application ID
* secret *required* - Facebook application secret
* test_user - Facebook test user parameters:
* name - You can specify a name for the test user you create. The specified name will also be used in the email address assigned to the test user.
* locale - You can specify a locale for the test user you create, the default is en_US. The list of supported locales is available at https://www.facebook.com/translations/FacebookLocales.xml
* permissions - An array of permissions. Your app is granted these permissions for the new test user. The full list of permissions is available at https://developers.facebook.com/docs/authentication/permissions
### Config example
modules:
enabled:
- Facebook:
depends: PhpBrowser
app_id: 412345678901234
secret: ccb79c1b0fdff54e4f7c928bf233aea5
test_user:
name: FacebookGuy
locale: uk_UA
permissions: [email, publish_stream]
### Test example:
``` php
<?php
$I = new ApiGuy($scenario);
$I->am('Guest');
$I->wantToTest('check-in to a place be published on the Facebook using API');
$I->haveFacebookTestUserAccount();
$accessToken = $I->grabFacebookTestUserAccessToken();
$I->haveHttpHeader('Auth', 'FacebookToken ' . $accessToken);
$I->amGoingTo('send request to the backend, so that it will publish on user\'s wall on Facebook');
$I->sendPOST('/api/v1/some-api-endpoint');
$I->seePostOnFacebookWithAttachedPlace('167724369950862');
```
``` php
<?php
$I = new WebGuy($scenario);
$I->am('Guest');
$I->wantToTest('log in to site using Facebook');
$I->haveFacebookTestUserAccount(); // create facebook test user
$I->haveTestUserLoggedInOnFacebook(); // so that facebook will not ask us for login and password
$fbUserFirstName = $I->grabFacebookTestUserFirstName();
$I->amOnPage('/welcome');
$I->see('Welcome, Guest');
$I->click('Login with Facebook');
$I->see('Welcome, ' . $fbUserFirstName);
```
@since 1.6.3
@author tiger.seo@gmail.com
## Actions
### grabFacebookTestUserAccessToken
Returns the test user access token.
* `return` string
### grabFacebookTestUserEmail
Returns the test user email.
* `return` string
### grabFacebookTestUserId
Returns the test user id.
* `return` string
### grabFacebookTestUserLoginUrl
Returns URL for test user auto-login.
* `return` string
### grabFacebookTestUserName
Returns the test user name.
* `return` string
### grabFacebookTestUserPassword
__not documented__
### haveFacebookTestUserAccount
Get facebook test user be created.
*Please, note that the test user is created only at first invoke, unless $renew arguments is true.*
* `param bool` $renew true if the test user should be recreated
### haveTestUserLoggedInOnFacebook
Get facebook test user be logged in on facebook.
This is done by going to facebook.com
@throws ModuleConfigException
### postToFacebookAsTestUser
Please, note that you must have publish_actions permission to be able to publish to user's feed.
* `param array` $params
### seePostOnFacebookWithAttachedPlace
Please, note that you must have publish_actions permission to be able to publish to user's feed.
* `param string` $placeId Place identifier to be verified against user published posts
### seePostOnFacebookWithMessage
Please, note that you must have publish_actions permission to be able to publish to user's feed.
* `param string` $message published post to be verified against the actual post on facebook
<p>&nbsp;</p><div class="alert alert-warning">Module reference is taken from the source code. <a href="https://github.com/Codeception/Codeception/tree/2.4/src/Codeception/Module/Facebook.php">Help us to improve documentation. Edit module reference</a></div>

View File

@@ -0,0 +1,199 @@
# Filesystem
Module for testing local filesystem.
Fork it to extend the module for FTP, Amazon S3, others.
## Status
* Maintainer: **davert**
* Stability: **stable**
* Contact: codecept@davert.mail.ua
Module was developed to test Codeception itself.
## Actions
### amInPath
Enters a directory In local filesystem.
Project root directory is used by default
* `param string` $path
### cleanDir
Erases directory contents
``` php
<?php
$I->cleanDir('logs');
?>
```
* `param string` $dirname
### copyDir
Copies directory with all contents
``` php
<?php
$I->copyDir('vendor','old_vendor');
?>
```
* `param string` $src
* `param string` $dst
### deleteDir
Deletes directory with all subdirectories
``` php
<?php
$I->deleteDir('vendor');
?>
```
* `param string` $dirname
### deleteFile
Deletes a file
``` php
<?php
$I->deleteFile('composer.lock');
?>
```
* `param string` $filename
### deleteThisFile
Deletes a file
### dontSeeFileFound
Checks if file does not exist in path
* `param string` $filename
* `param string` $path
### dontSeeInThisFile
Checks If opened file doesn't contain `text` in it
``` php
<?php
$I->openFile('composer.json');
$I->dontSeeInThisFile('codeception/codeception');
?>
```
* `param string` $text
### openFile
Opens a file and stores it's content.
Usage:
``` php
<?php
$I->openFile('composer.json');
$I->seeInThisFile('codeception/codeception');
?>
```
* `param string` $filename
### seeFileContentsEqual
Checks the strict matching of file contents.
Unlike `seeInThisFile` will fail if file has something more than expected lines.
Better to use with HEREDOC strings.
Matching is done after removing "\r" chars from file content.
``` php
<?php
$I->openFile('process.pid');
$I->seeFileContentsEqual('3192');
?>
```
* `param string` $text
### seeFileFound
Checks if file exists in path.
Opens a file when it's exists
``` php
<?php
$I->seeFileFound('UserModel.php','app/models');
?>
```
* `param string` $filename
* `param string` $path
### seeInThisFile
Checks If opened file has `text` in it.
Usage:
``` php
<?php
$I->openFile('composer.json');
$I->seeInThisFile('codeception/codeception');
?>
```
* `param string` $text
### seeNumberNewLines
Checks If opened file has the `number` of new lines.
Usage:
``` php
<?php
$I->openFile('composer.json');
$I->seeNumberNewLines(5);
?>
```
* `param int` $number New lines
### seeThisFileMatches
Checks that contents of currently opened file matches $regex
* `param string` $regex
### writeToFile
Saves contents to file
* `param string` $filename
* `param string` $contents
<p>&nbsp;</p><div class="alert alert-warning">Module reference is taken from the source code. <a href="https://github.com/Codeception/Codeception/tree/2.4/src/Codeception/Module/Filesystem.php">Help us to improve documentation. Edit module reference</a></div>

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,106 @@
# Memcache
Connects to [memcached](http://www.memcached.org/) using either _Memcache_ or _Memcached_ extension.
Performs a cleanup by flushing all values after each test run.
## Status
* Maintainer: **davert**
* Stability: **beta**
* Contact: davert@codeception.com
## Configuration
* **`host`** (`string`, default `'localhost'`) - The memcached host
* **`port`** (`int`, default `11211`) - The memcached port
### Example (`unit.suite.yml`)
```yaml
modules:
- Memcache:
host: 'localhost'
port: 11211
```
Be sure you don't use the production server to connect.
## Public Properties
* **memcache** - instance of _Memcache_ or _Memcached_ object
## Actions
### clearMemcache
Flushes all Memcached data.
### dontSeeInMemcached
Checks item in Memcached doesn't exist or is the same as expected.
Examples:
``` php
<?php
// With only one argument, only checks the key does not exist
$I->dontSeeInMemcached('users_count');
// Checks a 'users_count' exists does not exist or its value is not the one provided
$I->dontSeeInMemcached('users_count', 200);
?>
```
* `param` $key
* `param` $value
### grabValueFromMemcached
Grabs value from memcached by key.
Example:
``` php
<?php
$users_count = $I->grabValueFromMemcached('users_count');
?>
```
* `param` $key
* `return` array|string
### haveInMemcached
Stores an item `$value` with `$key` on the Memcached server.
* `param string` $key
* `param mixed` $value
* `param int` $expiration
### seeInMemcached
Checks item in Memcached exists and the same as expected.
Examples:
``` php
<?php
// With only one argument, only checks the key exists
$I->seeInMemcached('users_count');
// Checks a 'users_count' exists and has the value 200
$I->seeInMemcached('users_count', 200);
?>
```
* `param` $key
* `param` $value
<p>&nbsp;</p><div class="alert alert-warning">Module reference is taken from the source code. <a href="https://github.com/Codeception/Codeception/tree/2.4/src/Codeception/Module/Memcache.php">Help us to improve documentation. Edit module reference</a></div>

View File

@@ -0,0 +1,170 @@
# MongoDb
Works with MongoDb database.
The most important function of this module is cleaning database before each test.
To have your database properly cleaned you should configure it to access the database.
In order to have your database populated with data you need a valid js file with data (of the same style which can be fed up to mongo binary)
File can be generated by RockMongo export command
You can also use directory, generated by ```mongodump``` tool or it's ```.tar.gz``` archive (not available for Windows systems), generated by ```tar -czf <archive_file_name>.tar.gz <path_to dump directory>```.
Just put it in ``` tests/_data ``` dir (by default) and specify path to it in config.
Next time after database is cleared all your data will be restored from dump.
The DB preparation should as following:
- clean database
- system collection system.users should contain the user which will be authenticated while script performs DB operations
Connection is done by MongoDb driver, which is stored in Codeception\Lib\Driver namespace.
Check out the driver if you get problems loading dumps and cleaning databases.
HINT: This module can be used with [Mongofill](https://github.com/mongofill/mongofill) library which is Mongo client written in PHP without extension.
## Status
* Maintainer: **judgedim**, **davert**
* Stability: **beta**
* Contact: davert@codeception.com
*Please review the code of non-stable modules and provide patches if you have issues.*
## Config
* dsn *required* - MongoDb DSN with the db name specified at the end of the host after slash
* user *required* - user to access database
* password *required* - password
* dump_type *required* - type of dump.
One of 'js' (MongoDb::DUMP_TYPE_JS), 'mongodump' (MongoDb::DUMP_TYPE_MONGODUMP) or 'mongodump-tar-gz' (MongoDb::DUMP_TYPE_MONGODUMP_TAR_GZ).
default: MongoDb::DUMP_TYPE_JS).
* dump - path to database dump
* populate: true - should the dump be loaded before test suite is started.
* cleanup: true - should the dump be reloaded after each test
## Actions
### dontSeeInCollection
Checks if collection doesn't contain an item.
``` php
<?php
$I->dontSeeInCollection('users', array('name' => 'miles'));
```
* `param` $collection
* `param array` $criteria
### grabCollectionCount
Grabs the documents count from a collection
``` php
<?php
$count = $I->grabCollectionCount('users');
// or
$count = $I->grabCollectionCount('users', array('isAdmin' => true));
```
* `param` $collection
* `param array` $criteria
* `return` integer
### grabFromCollection
Grabs a data from collection
``` php
<?php
$user = $I->grabFromCollection('users', array('name' => 'miles'));
```
* `param` $collection
* `param array` $criteria
* `return` array
### haveInCollection
Inserts data into collection
``` php
<?php
$I->haveInCollection('users', array('name' => 'John', 'email' => 'john@coltrane.com'));
$user_id = $I->haveInCollection('users', array('email' => 'john@coltrane.com'));
```
* `param` $collection
* `param array` $data
### seeElementIsArray
Asserts that an element in a collection exists and is an Array
``` php
<?php
$I->seeElementIsArray('users', array('name' => 'John Doe') , 'data.skills');
```
* `param String` $collection
* `param Array` $criteria
* `param String` $elementToCheck
### seeElementIsObject
Asserts that an element in a collection exists and is an Object
``` php
<?php
$I->seeElementIsObject('users', array('name' => 'John Doe') , 'data');
```
* `param String` $collection
* `param Array` $criteria
* `param String` $elementToCheck
### seeInCollection
Checks if collection contains an item.
``` php
<?php
$I->seeInCollection('users', array('name' => 'miles'));
```
* `param` $collection
* `param array` $criteria
### seeNumElementsInCollection
Count number of records in a collection
``` php
<?php
$I->seeNumElementsInCollection('users', 2);
$I->seeNumElementsInCollection('users', 1, array('name' => 'miles'));
```
* `param` $collection
* `param integer` $expected
* `param array` $criteria
### useDatabase
Specify the database to use
``` php
<?php
$I->useDatabase('db_1');
```
* `param` $dbName
<p>&nbsp;</p><div class="alert alert-warning">Module reference is taken from the source code. <a href="https://github.com/Codeception/Codeception/tree/2.4/src/Codeception/Module/MongoDb.php">Help us to improve documentation. Edit module reference</a></div>

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,297 @@
# Queue
Works with Queue servers.
Testing with a selection of remote/local queueing services, including Amazon's SQS service
Iron.io service and beanstalkd service.
Supported and tested queue types are:
* [Iron.io](http://iron.io/)
* [Beanstalkd](http://kr.github.io/beanstalkd/)
* [Amazon SQS](http://aws.amazon.com/sqs/)
The following dependencies are needed for the listed queue servers:
* Beanstalkd: pda/pheanstalk ~3.0
* Amazon SQS: aws/aws-sdk-php
* IronMQ: iron-io/iron_mq
## Status
* Maintainer: **nathanmac**
* Stability:
- Iron.io: **stable**
- Beanstalkd: **stable**
- Amazon SQS: **stable**
* Contact: nathan.macnamara@outlook.com
## Config
The configuration settings depending on which queueing service is being used, all the options are listed
here. Refer to the configuration examples below to identify the configuration options required for your chosen
service.
* type - type of queueing server (defaults to beanstalkd).
* host - hostname/ip address of the queue server or the host for the iron.io when using iron.io service.
* port: 11300 - port number for the queue server.
* timeout: 90 - timeout settings for connecting the queue server.
* token - Iron.io access token.
* project - Iron.io project ID.
* key - AWS access key ID.
* version - AWS version (e.g. latest)
* endpoint - The full URI of the webservice. This is only required when connecting to a custom endpoint (e.g., a local version of SQS).
* secret - AWS secret access key.
Warning:
Hard-coding your credentials can be dangerous, because it is easy to accidentally commit your credentials
into an SCM repository, potentially exposing your credentials to more people than intended.
It can also make it difficult to rotate credentials in the future.
* profile - AWS credential profile
- it should be located in ~/.aws/credentials file
- eg: [default]
aws_access_key_id = YOUR_AWS_ACCESS_KEY_ID
aws_secret_access_key = YOUR_AWS_SECRET_ACCESS_KEY
[project1]
aws_access_key_id = YOUR_AWS_ACCESS_KEY_ID
aws_secret_access_key = YOUR_AWS_SECRET_ACCESS_KEY
- Note: Using IAM roles is the preferred technique for providing credentials
to applications running on Amazon EC2
http://docs.aws.amazon.com/aws-sdk-php/v3/guide/guide/credentials.html?highlight=credentials
* region - A region parameter is also required for AWS, refer to the AWS documentation for possible values list.
### Example
#### Example (beanstalkd)
modules:
enabled: [Queue]
config:
Queue:
type: 'beanstalkd'
host: '127.0.0.1'
port: 11300
timeout: 120
#### Example (Iron.io)
modules:
enabled: [Queue]
config:
Queue:
'type': 'iron',
'host': 'mq-aws-us-east-1.iron.io',
'token': 'your-token',
'project': 'your-project-id'
#### Example (AWS SQS)
modules:
enabled: [Queue]
config:
Queue:
'type': 'aws',
'key': 'your-public-key',
'secret': 'your-secret-key',
'region': 'us-west-2'
#### Example AWS SQS using profile credentials
modules:
enabled: [Queue]
config:
Queue:
'type': 'aws',
'profile': 'project1', //see documentation
'region': 'us-west-2'
#### Example AWS SQS running on Amazon EC2 instance
modules:
enabled: [Queue]
config:
Queue:
'type': 'aws',
'region': 'us-west-2'
## Actions
### addMessageToQueue
Add a message to a queue/tube
```php
<?php
$I->addMessageToQueue('this is a messages', 'default');
?>
```
* `param string` $message Message Body
* `param string` $queue Queue Name
### clearQueue
Clear all messages of the queue/tube
```php
<?php
$I->clearQueue('default');
?>
```
* `param string` $queue Queue Name
### dontSeeEmptyQueue
Check if a queue/tube is NOT empty of all messages
```php
<?php
$I->dontSeeEmptyQueue('default');
?>
```
* `param string` $queue Queue Name
### dontSeeQueueExists
Check if a queue/tube does NOT exist on the queueing server.
```php
<?php
$I->dontSeeQueueExists('default');
?>
```
* `param string` $queue Queue Name
### dontSeeQueueHasCurrentCount
Check if a queue/tube does NOT have a given current number of messages
```php
<?php
$I->dontSeeQueueHasCurrentCount('default', 10);
?>
```
* `param string` $queue Queue Name
* `param int` $expected Number of messages expected
### dontSeeQueueHasTotalCount
Check if a queue/tube does NOT have a given total number of messages
```php
<?php
$I->dontSeeQueueHasTotalCount('default', 10);
?>
```
* `param string` $queue Queue Name
* `param int` $expected Number of messages expected
### grabQueueCurrentCount
Grabber method to get the current number of messages on the queue/tube (pending/ready)
```php
<?php
$I->grabQueueCurrentCount('default');
?>
```
* `param string` $queue Queue Name
* `return` int Count
### grabQueueTotalCount
Grabber method to get the total number of messages on the queue/tube
```php
<?php
$I->grabQueueTotalCount('default');
?>
```
* `param` $queue Queue Name
* `return` int Count
### grabQueues
Grabber method to get the list of queues/tubes on the server
```php
<?php
$queues = $I->grabQueues();
?>
```
* `return` array List of Queues/Tubes
### seeEmptyQueue
Check if a queue/tube is empty of all messages
```php
<?php
$I->seeEmptyQueue('default');
?>
```
* `param string` $queue Queue Name
### seeQueueExists
Check if a queue/tube exists on the queueing server.
```php
<?php
$I->seeQueueExists('default');
?>
```
* `param string` $queue Queue Name
### seeQueueHasCurrentCount
Check if a queue/tube has a given current number of messages
```php
<?php
$I->seeQueueHasCurrentCount('default', 10);
?>
```
* `param string` $queue Queue Name
* `param int` $expected Number of messages expected
### seeQueueHasTotalCount
Check if a queue/tube has a given total number of messages
```php
<?php
$I->seeQueueHasTotalCount('default', 10);
?>
```
* `param string` $queue Queue Name
* `param int` $expected Number of messages expected
<p>&nbsp;</p><div class="alert alert-warning">Module reference is taken from the source code. <a href="https://github.com/Codeception/Codeception/tree/2.4/src/Codeception/Module/Queue.php">Help us to improve documentation. Edit module reference</a></div>

View File

@@ -0,0 +1,887 @@
# REST
Module for testing REST WebService.
This module can be used either with frameworks or PHPBrowser.
If a framework module is connected, the testing will occur in the application directly.
Otherwise, a PHPBrowser should be specified as a dependency to send requests and receive responses from a server.
## Configuration
* url *optional* - the url of api
This module requires PHPBrowser or any of Framework modules enabled.
### Example
modules:
enabled:
- REST:
depends: PhpBrowser
url: 'http://serviceapp/api/v1/'
## 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
## Actions
### amAWSAuthenticated
Allows to send REST request using AWS Authorization
Only works with PhpBrowser
Example
Config -
modules:
enabled:
- REST:
aws:
key: accessKey
secret: accessSecret
service: awsService
region: awsRegion
```php
<?php
$I->amAWSAuthenticated();
?>
```
* `param array` $additionalAWSConfig
@throws ModuleException
### amBearerAuthenticated
Adds Bearer authentication via access token.
* `param` $accessToken
* `[Part]` json
* `[Part]` xml
### amDigestAuthenticated
Adds Digest authentication via username/password.
* `param` $username
* `param` $password
* `[Part]` json
* `[Part]` xml
### amHttpAuthenticated
Adds HTTP authentication via username/password.
* `param` $username
* `param` $password
* `[Part]` json
* `[Part]` xml
### amNTLMAuthenticated
Adds NTLM authentication via username/password.
Requires client to be Guzzle >=6.3.0
Out of scope for functional modules.
Example:
```php
<?php
$I->amNTLMAuthenticated('jon_snow', 'targaryen');
?>
```
* `param` $username
* `param` $password
@throws ModuleException
* `[Part]` json
* `[Part]` xml
### deleteHeader
Deletes the header with the passed name. Subsequent requests
will not have the deleted header in its request.
Example:
```php
<?php
$I->haveHttpHeader('X-Requested-With', 'Codeception');
$I->sendGET('test-headers.php');
// ...
$I->deleteHeader('X-Requested-With');
$I->sendPOST('some-other-page.php');
?>
```
* `param string` $name the name of the header to delete.
* `[Part]` json
* `[Part]` xml
### dontSeeBinaryResponseEquals
Checks if the hash of a binary response is not the same as provided.
```php
<?php
$I->dontSeeBinaryResponseEquals("8c90748342f19b195b9c6b4eff742ded");
?>
```
Opposite to `seeBinaryResponseEquals`
* `param` $hash the hashed data response expected
* `param` $algo the hash algorithm to use. Default md5.
* `[Part]` json
* `[Part]` xml
### dontSeeHttpHeader
Checks over the given HTTP header and (optionally)
its value, asserting that are not there
* `param` $name
* `param` $value
* `[Part]` json
* `[Part]` xml
### dontSeeResponseCodeIs
Checks that response code is not equal to provided value.
```php
<?php
$I->dontSeeResponseCodeIs(200);
// preferred to use \Codeception\Util\HttpCode
$I->dontSeeResponseCodeIs(\Codeception\Util\HttpCode::OK);
```
* `[Part]` json
* `[Part]` xml
* `param` $code
### dontSeeResponseContains
Checks whether last response do not contain text.
* `param` $text
* `[Part]` json
* `[Part]` xml
### dontSeeResponseContainsJson
Opposite to seeResponseContainsJson
* `[Part]` json
* `param array` $json
### dontSeeResponseJsonMatchesJsonPath
Opposite to seeResponseJsonMatchesJsonPath
* `param string` $jsonPath
* `[Part]` json
### dontSeeResponseJsonMatchesXpath
Opposite to seeResponseJsonMatchesXpath
* `param string` $xpath
* `[Part]` json
### dontSeeResponseMatchesJsonType
Opposite to `seeResponseMatchesJsonType`.
* `[Part]` json
@see seeResponseMatchesJsonType
* `param` $jsonType jsonType structure
* `param null` $jsonPath optionally set specific path to structure with JsonPath
* `Available since` 2.1.3
### dontSeeXmlResponseEquals
Checks XML response does not equal to provided XML.
Comparison is done by canonicalizing both xml`s.
Parameter can be passed either as XmlBuilder, DOMDocument, DOMNode, XML string, or array (if no attributes).
* `param` $xml
* `[Part]` xml
### dontSeeXmlResponseIncludes
Checks XML response does not include provided XML.
Comparison is done by canonicalizing both xml`s.
Parameter can be passed either as XmlBuilder, DOMDocument, DOMNode, XML string, or array (if no attributes).
* `param` $xml
* `[Part]` xml
### dontSeeXmlResponseMatchesXpath
Checks whether XML response does not match XPath
```php
<?php
$I->dontSeeXmlResponseMatchesXpath('//root/user[@id=1]');
```
* `[Part]` xml
* `param` $xpath
### grabAttributeFromXmlElement
Finds and returns attribute of element.
Element is matched by either CSS or XPath
* `param` $cssOrXPath
* `param` $attribute
* `return` string
* `[Part]` xml
### grabDataFromJsonResponse
Deprecated since 2.0.9 and removed since 2.1.0
* `param` $path
@throws ModuleException
@deprecated
### grabDataFromResponseByJsonPath
Returns data from the current JSON response using [JSONPath](http://goessner.net/articles/JsonPath/) as selector.
JsonPath is XPath equivalent for querying Json structures.
Try your JsonPath expressions [online](http://jsonpath.curiousconcept.com/).
Even for a single value an array is returned.
This method **require [`flow/jsonpath` > 0.2](https://github.com/FlowCommunications/JSONPath/) library to be installed**.
Example:
``` php
<?php
// match the first `user.id` in json
$firstUserId = $I->grabDataFromResponseByJsonPath('$..users[0].id');
$I->sendPUT('/user', array('id' => $firstUserId[0], 'name' => 'davert'));
?>
```
* `param string` $jsonPath
* `return` array Array of matching items
* `Available since` 2.0.9
@throws \Exception
* `[Part]` json
### grabHttpHeader
Returns the value of the specified header name
* `param` $name
* `param Boolean` $first Whether to return the first value or all header values
* `return string|array The first header value if` $first is true, an array of values otherwise
* `[Part]` json
* `[Part]` xml
### grabResponse
Returns current response so that it can be used in next scenario steps.
Example:
``` php
<?php
$user_id = $I->grabResponse();
$I->sendPUT('/user', array('id' => $user_id, 'name' => 'davert'));
?>
```
* `Available since` 1.1
* `return` string
* `[Part]` json
* `[Part]` xml
### grabTextContentFromXmlElement
Finds and returns text contents of element.
Element is matched by either CSS or XPath
* `param` $cssOrXPath
* `return` string
* `[Part]` xml
### haveHttpHeader
Sets HTTP header valid for all next requests. Use `deleteHeader` to unset it
```php
<?php
$I->haveHttpHeader('Content-Type', 'application/json');
// all next requests will contain this header
?>
```
* `param` $name
* `param` $value
* `[Part]` json
* `[Part]` xml
### seeBinaryResponseEquals
Checks if the hash of a binary response is exactly the same as provided.
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
<?php
$I->seeBinaryResponseEquals("8c90748342f19b195b9c6b4eff742ded");
?>
```
Example: Using md5 for a file contents
```php
<?php
$fileData = file_get_contents("test_file.jpg");
$I->seeBinaryResponseEquals(md5($fileData));
?>
```
Example: Using sha256 hash
```php
<?php
$fileData = '/9j/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8QEBEQCgwSExIQEw8QEBD/yQALCAABAAEBAREA/8wABgAQEAX/2gAIAQEAAD8A0s8g/9k='; // very small jpeg
$I->seeBinaryResponseEquals(hash("sha256", base64_decode($fileData)), 'sha256');
?>
```
* `param` $hash the hashed data response expected
* `param` $algo the hash algorithm to use. Default md5.
* `[Part]` json
* `[Part]` xml
### seeHttpHeader
Checks over the given HTTP header and (optionally)
its value, asserting that are there
* `param` $name
* `param` $value
* `[Part]` json
* `[Part]` xml
### seeHttpHeaderOnce
Checks that http response header is received only once.
HTTP RFC2616 allows multiple response headers with the same name.
You can check that you didn't accidentally sent the same header twice.
``` php
<?php
$I->seeHttpHeaderOnce('Cache-Control');
?>>
```
* `param` $name
* `[Part]` json
* `[Part]` xml
### seeResponseCodeIs
Checks response code equals to provided value.
```php
<?php
$I->seeResponseCodeIs(200);
// preferred to use \Codeception\Util\HttpCode
$I->seeResponseCodeIs(\Codeception\Util\HttpCode::OK);
```
* `[Part]` json
* `[Part]` xml
* `param` $code
### seeResponseCodeIsClientError
Checks that the response code is 4xx
### seeResponseCodeIsRedirection
Checks that the response code 3xx
### seeResponseCodeIsServerError
Checks that the response code is 5xx
### seeResponseCodeIsSuccessful
Checks that the response code is 2xx
### seeResponseContains
Checks whether the last response contains text.
* `param` $text
* `[Part]` json
* `[Part]` xml
### seeResponseContainsJson
Checks whether the last JSON response contains provided array.
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
<?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.
* `param array` $json
* `[Part]` json
### seeResponseEquals
Checks if response is exactly the same as provided.
* `[Part]` json
* `[Part]` xml
* `param` $response
### seeResponseIsJson
Checks whether last response was valid JSON.
This is done with json_last_error function.
* `[Part]` json
### seeResponseIsXml
Checks whether last response was valid XML.
This is done with libxml_get_last_error function.
* `[Part]` xml
### seeResponseJsonMatchesJsonPath
Checks if json structure in response matches [JsonPath](http://goessner.net/articles/JsonPath/).
JsonPath is XPath equivalent for querying Json structures.
Try your JsonPath expressions [online](http://jsonpath.curiousconcept.com/).
This assertion allows you to check the structure of response json.
This method **require [`flow/jsonpath` > 0.2](https://github.com/FlowCommunications/JSONPath/) library to be installed**.
```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
<?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');
?>
```
* `param string` $jsonPath
* `[Part]` json
* `Available since` 2.0.9
### seeResponseJsonMatchesXpath
Checks if json structure in response matches the xpath provided.
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.
*
```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
<?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');
?>
```
* `param string` $xpath
* `[Part]` json
* `Available since` 2.0.9
### seeResponseMatchesJsonType
Checks that Json matches provided types.
In case you don't know the actual values of JSON data returned you can match them by type.
Starts check with a root element. If JSON data is array it will check the first element of an array.
You can specify the path in the json which should be checked with JsonPath
Basic example:
```php
<?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]');
?>
```
In this case you can match that record contains fields with data types you expected.
The list of possible data types:
* string
* integer
* float
* array (json object is array as well)
* boolean
You can also use nested data type structures:
```php
<?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 `:` char after the type declaration.
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
<?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 y accessing `JsonType::addCustomFilter` method.
See [JsonType reference](http://codeception.com/docs/reference/JsonType).
* `[Part]` json
* `Available since` 2.1.3
* `param array` $jsonType
* `param string` $jsonPath
### seeXmlResponseEquals
Checks XML response equals provided XML.
Comparison is done by canonicalizing both xml`s.
Parameters can be passed either as DOMDocument, DOMNode, XML string, or array (if no attributes).
* `param` $xml
* `[Part]` xml
### seeXmlResponseIncludes
Checks XML response includes provided XML.
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
<?php
$I->seeXmlResponseIncludes("<result>1</result>");
?>
```
* `param` $xml
* `[Part]` xml
### seeXmlResponseMatchesXpath
Checks whether XML response matches XPath
```php
<?php
$I->seeXmlResponseMatchesXpath('//root/user[@id=1]');
```
* `[Part]` xml
* `param` $xpath
### sendDELETE
Sends DELETE request to given uri.
* `param` $url
* `param array` $params
* `param array` $files
* `[Part]` json
* `[Part]` xml
### sendGET
Sends a GET request to given uri.
* `param` $url
* `param array` $params
* `[Part]` json
* `[Part]` xml
### sendHEAD
Sends a HEAD request to given uri.
* `param` $url
* `param array` $params
* `[Part]` json
* `[Part]` xml
### sendLINK
Sends LINK request to given uri.
* `param` $url
* `param array` $linkEntries (entry is array with keys "uri" and "link-param")
@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.
* `param` $url
* `param array` $params
* `[Part]` json
* `[Part]` xml
### sendPATCH
Sends PATCH request to given uri.
* `param` $url
* `param array` $params
* `param array` $files
* `[Part]` json
* `[Part]` xml
### sendPOST
Sends a POST request to given uri. Parameters and files can be provided separately.
Example:
```php
<?php
//simple POST call
$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')
]
]);
```
* `param` $url
* `param array|\JsonSerializable` $params
* `param array` $files 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.
@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.
* `param` $url
* `param array` $params
* `param array` $files
* `[Part]` json
* `[Part]` xml
### sendUNLINK
Sends UNLINK request to given uri.
* `param` $url
* `param array` $linkEntries (entry is array with keys "uri" and "link-param")
@link http://tools.ietf.org/html/rfc2068#section-19.6.2.4
@author samva.ua@gmail.com
* `[Part]` json
* `[Part]` xml
### startFollowingRedirects
Enables automatic redirects to be followed by the client
```php
<?php
$I->startFollowingRedirects();
```
* `[Part]` xml
* `[Part]` json
### stopFollowingRedirects
Prevents automatic redirects to be followed by the client
```php
<?php
$I->stopFollowingRedirects();
```
* `[Part]` xml
* `[Part]` json
<p>&nbsp;</p><div class="alert alert-warning">Module reference is taken from the source code. <a href="https://github.com/Codeception/Codeception/tree/2.4/src/Codeception/Module/REST.php">Help us to improve documentation. Edit module reference</a></div>

View File

@@ -0,0 +1,285 @@
# Redis
This module uses the [Predis](https://github.com/nrk/predis) library
to interact with a Redis server.
## Status
* Stability: **beta**
## Configuration
* **`host`** (`string`, default `'127.0.0.1'`) - The Redis host
* **`port`** (`int`, default `6379`) - The Redis port
* **`database`** (`int`, no default) - The Redis database. Needs to be specified.
* **`cleanupBefore`**: (`string`, default `'never'`) - Whether/when to flush the database:
* `suite`: at the beginning of every suite
* `test`: at the beginning of every test
* Any other value: never
### Example (`unit.suite.yml`)
```yaml
modules:
- Redis:
host: '127.0.0.1'
port: 6379
database: 0
cleanupBefore: 'never'
```
## Public Properties
* **driver** - Contains the Predis client/driver
@author Marc Verney <marc@marcverney.net>
## Actions
### cleanup
Delete all the keys in the Redis database
@throws ModuleException
### dontSeeInRedis
Asserts that a key does not exist or, optionally, that it doesn't have the
provided $value
Examples:
``` php
<?php
// With only one argument, only checks the key does not exist
$I->dontSeeInRedis('example:string');
// Checks a String does not exist or its value is not the one provided
$I->dontSeeInRedis('example:string', 'life');
// Checks a List does not exist or its value is not the one provided (order of elements is compared).
$I->dontSeeInRedis('example:list', ['riri', 'fifi', 'loulou']);
// Checks a Set does not exist or its value is not the one provided (order of members is ignored).
$I->dontSeeInRedis('example:set', ['riri', 'fifi', 'loulou']);
// Checks a ZSet does not exist or its value is not the one provided (scores are required, order of members is compared)
$I->dontSeeInRedis('example:zset', ['riri' => 1, 'fifi' => 2, 'loulou' => 3]);
// Checks a Hash does not exist or its value is not the one provided (order of members is ignored).
$I->dontSeeInRedis('example:hash', ['riri' => true, 'fifi' => 'Dewey', 'loulou' => 2]);
```
* `param string` $key The key name
* `param mixed` $value Optional. If specified, also checks the key has this
value. Booleans will be converted to 1 and 0 (even inside arrays)
### dontSeeRedisKeyContains
Asserts that a given key does not contain a given item
Examples:
``` php
<?php
// Strings: performs a substring search
$I->dontSeeRedisKeyContains('string', 'bar');
// Lists
$I->dontSeeRedisKeyContains('example:list', 'poney');
// Sets
$I->dontSeeRedisKeyContains('example:set', 'cat');
// ZSets: check whether the zset has this member
$I->dontSeeRedisKeyContains('example:zset', 'jordan');
// ZSets: check whether the zset has this member with this score
$I->dontSeeRedisKeyContains('example:zset', 'jordan', 23);
// Hashes: check whether the hash has this field
$I->dontSeeRedisKeyContains('example:hash', 'magic');
// Hashes: check whether the hash has this field with this value
$I->dontSeeRedisKeyContains('example:hash', 'magic', 32);
```
* `param string` $key The key
* `param mixed` $item The item
* `param null` $itemValue Optional and only used for zsets and hashes. If
specified, the method will also check that the $item has this value/score
* `return` bool
### grabFromRedis
Returns the value of a given key
Examples:
``` php
<?php
// Strings
$I->grabFromRedis('string');
// Lists: get all members
$I->grabFromRedis('example:list');
// Lists: get a specific member
$I->grabFromRedis('example:list', 2);
// Lists: get a range of elements
$I->grabFromRedis('example:list', 2, 4);
// Sets: get all members
$I->grabFromRedis('example:set');
// ZSets: get all members
$I->grabFromRedis('example:zset');
// ZSets: get a range of members
$I->grabFromRedis('example:zset', 3, 12);
// Hashes: get all fields of a key
$I->grabFromRedis('example:hash');
// Hashes: get a specific field of a key
$I->grabFromRedis('example:hash', 'foo');
```
* `param string` $key The key name
@throws ModuleException if the key does not exist
### haveInRedis
Creates or modifies keys
If $key already exists:
- Strings: its value will be overwritten with $value
- Other types: $value items will be appended to its value
Examples:
``` php
<?php
// Strings: $value must be a scalar
$I->haveInRedis('string', 'Obladi Oblada');
// Lists: $value can be a scalar or an array
$I->haveInRedis('list', ['riri', 'fifi', 'loulou']);
// Sets: $value can be a scalar or an array
$I->haveInRedis('set', ['riri', 'fifi', 'loulou']);
// ZSets: $value must be an associative array with scores
$I->haveInRedis('zset', ['riri' => 1, 'fifi' => 2, 'loulou' => 3]);
// Hashes: $value must be an associative array
$I->haveInRedis('hash', ['obladi' => 'oblada']);
```
* `param string` $type The type of the key
* `param string` $key The key name
* `param mixed` $value The value
@throws ModuleException
### seeInRedis
Asserts that a key exists, and optionally that it has the provided $value
Examples:
``` php
<?php
// With only one argument, only checks the key exists
$I->seeInRedis('example:string');
// Checks a String exists and has the value "life"
$I->seeInRedis('example:string', 'life');
// Checks the value of a List. Order of elements is compared.
$I->seeInRedis('example:list', ['riri', 'fifi', 'loulou']);
// Checks the value of a Set. Order of members is ignored.
$I->seeInRedis('example:set', ['riri', 'fifi', 'loulou']);
// Checks the value of a ZSet. Scores are required. Order of members is compared.
$I->seeInRedis('example:zset', ['riri' => 1, 'fifi' => 2, 'loulou' => 3]);
// Checks the value of a Hash. Order of members is ignored.
$I->seeInRedis('example:hash', ['riri' => true, 'fifi' => 'Dewey', 'loulou' => 2]);
```
* `param string` $key The key name
* `param mixed` $value Optional. If specified, also checks the key has this
value. Booleans will be converted to 1 and 0 (even inside arrays)
### seeRedisKeyContains
Asserts that a given key contains a given item
Examples:
``` php
<?php
// Strings: performs a substring search
$I->seeRedisKeyContains('example:string', 'bar');
// Lists
$I->seeRedisKeyContains('example:list', 'poney');
// Sets
$I->seeRedisKeyContains('example:set', 'cat');
// ZSets: check whether the zset has this member
$I->seeRedisKeyContains('example:zset', 'jordan');
// ZSets: check whether the zset has this member with this score
$I->seeRedisKeyContains('example:zset', 'jordan', 23);
// Hashes: check whether the hash has this field
$I->seeRedisKeyContains('example:hash', 'magic');
// Hashes: check whether the hash has this field with this value
$I->seeRedisKeyContains('example:hash', 'magic', 32);
```
* `param string` $key The key
* `param mixed` $item The item
* `param null` $itemValue Optional and only used for zsets and hashes. If
specified, the method will also check that the $item has this value/score
* `return` bool
### sendCommandToRedis
Sends a command directly to the Redis driver. See documentation at
https://github.com/nrk/predis
Every argument that follows the $command name will be passed to it.
Examples:
``` php
<?php
$I->sendCommandToRedis('incr', 'example:string');
$I->sendCommandToRedis('strLen', 'example:string');
$I->sendCommandToRedis('lPop', 'example:list');
$I->sendCommandToRedis('zRangeByScore', 'example:set', '-inf', '+inf', ['withscores' => true, 'limit' => [1, 2]]);
$I->sendCommandToRedis('flushdb');
```
* `param string` $command The command name
<p>&nbsp;</p><div class="alert alert-warning">Module reference is taken from the source code. <a href="https://github.com/Codeception/Codeception/tree/2.4/src/Codeception/Module/Redis.php">Help us to improve documentation. Edit module reference</a></div>

View File

@@ -0,0 +1,235 @@
# SOAP
Module for testing SOAP WSDL web services.
Send requests and check if response matches the pattern.
This module can be used either with frameworks or PHPBrowser.
It tries to guess the framework is is attached to.
If a endpoint is a full url then it uses PHPBrowser.
### Using Inside Framework
Please note, that PHP SoapServer::handle method sends additional headers.
This may trigger warning: "Cannot modify header information"
If you use PHP SoapServer with framework, try to block call to this method in testing environment.
## Status
* Maintainer: **davert**
* Stability: **stable**
* Contact: codecept@davert.mail.ua
## Configuration
* endpoint *required* - soap wsdl endpoint
* SOAPAction - replace SOAPAction HTTP header (Set to '' to SOAP 1.2)
## Public Properties
* xmlRequest - last SOAP request (DOMDocument)
* xmlResponse - last SOAP response (DOMDocument)
## Actions
### dontSeeSoapResponseContainsStructure
Opposite to `seeSoapResponseContainsStructure`
* `param` $xml
### dontSeeSoapResponseContainsXPath
Checks XML response doesn't contain XPath locator
``` php
<?php
$I->dontSeeSoapResponseContainsXPath('//root/user[@id=1]');
?>
```
* `param` $xpath
### dontSeeSoapResponseEquals
Checks XML response equals provided XML.
Comparison is done by canonicalizing both xml`s.
Parameter can be passed either as XmlBuilder, DOMDocument, DOMNode, XML string, or array (if no attributes).
* `param` $xml
### dontSeeSoapResponseIncludes
Checks XML response does not include provided XML.
Comparison is done by canonicalizing both xml`s.
Parameter can be passed either as XmlBuilder, DOMDocument, DOMNode, XML string, or array (if no attributes).
* `param` $xml
### grabAttributeFrom
Finds and returns attribute of element.
Element is matched by either CSS or XPath
* `Available since` 1.1
* `param` $cssOrXPath
* `param` $attribute
* `return` string
### grabTextContentFrom
Finds and returns text contents of element.
Element is matched by either CSS or XPath
* `Available since` 1.1
* `param` $cssOrXPath
* `return` string
### haveSoapHeader
Prepare SOAP header.
Receives header name and parameters as array.
Example:
``` php
<?php
$I->haveSoapHeader('AuthHeader', array('username' => 'davert', 'password' => '123345'));
```
Will produce header:
```
<soapenv:Header>
<SessionHeader>
<AuthHeader>
<username>davert</username>
<password>12345</password>
</AuthHeader>
</soapenv:Header>
```
* `param` $header
* `param array` $params
### seeResponseCodeIs
@deprecated use seeSoapResponseCodeIs instead
### seeSoapResponseCodeIs
Checks response code from server.
* `param` $code
### seeSoapResponseContainsStructure
Checks XML response contains provided structure.
Response elements will be compared with XML provided.
Only nodeNames are checked to see elements match.
Example:
``` php
<?php
$I->seeSoapResponseContainsStructure("<query><name></name></query>");
?>
```
Use this method to check XML of valid structure is returned.
This method does not use schema for validation.
This method does not require path from root to match the structure.
* `param` $xml
### seeSoapResponseContainsXPath
Checks XML response with XPath locator
``` php
<?php
$I->seeSoapResponseContainsXPath('//root/user[@id=1]');
?>
```
* `param` $xpath
### seeSoapResponseEquals
Checks XML response equals provided XML.
Comparison is done by canonicalizing both xml`s.
Parameters can be passed either as DOMDocument, DOMNode, XML string, or array (if no attributes).
Example:
``` php
<?php
$I->seeSoapResponseEquals("<?xml version="1.0" encoding="UTF-8"?><SOAP-ENV:Envelope><SOAP-ENV:Body><result>1</result></SOAP-ENV:Envelope>");
$dom = new \DOMDocument();
$dom->load($file);
$I->seeSoapRequestIncludes($dom);
```
* `param` $xml
### seeSoapResponseIncludes
Checks XML response includes provided XML.
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
<?php
$I->seeSoapResponseIncludes("<result>1</result>");
$I->seeSoapRequestIncludes(\Codeception\Utils\Soap::response()->result->val(1));
$dom = new \DDOMDocument();
$dom->load('template.xml');
$I->seeSoapRequestIncludes($dom);
?>
```
* `param` $xml
### sendSoapRequest
Submits request to endpoint.
Requires of api function name and parameters.
Parameters can be passed either as DOMDocument, DOMNode, XML string, or array (if no attributes).
You are allowed to execute as much requests as you need inside test.
Example:
``` php
$I->sendSoapRequest('UpdateUser', '<user><id>1</id><name>notdavert</name></user>');
$I->sendSoapRequest('UpdateUser', \Codeception\Utils\Soap::request()->user
->id->val(1)->parent()
->name->val('notdavert');
```
* `param` $request
* `param` $body
<p>&nbsp;</p><div class="alert alert-warning">Module reference is taken from the source code. <a href="https://github.com/Codeception/Codeception/tree/2.4/src/Codeception/Module/SOAP.php">Help us to improve documentation. Edit module reference</a></div>

View File

@@ -0,0 +1,97 @@
# Sequence
Sequence solves data cleanup issue in alternative way.
Instead cleaning up the database between tests,
you can use generated unique names, that should not conflict.
When you create article on a site, for instance, you can assign it a unique name and then check it.
This module has no actions, but introduces a function `sq` for generating unique sequences within test and
`sqs` for generating unique sequences across suite.
### Usage
Function `sq` generates sequence, the only parameter it takes, is id.
You can get back to previously generated sequence using that id:
``` php
<?php
sq('post1'); // post1_521fbc63021eb
sq('post2'); // post2_521fbc6302266
sq('post1'); // post1_521fbc63021eb
```
Example:
``` php
<?php
$I->wantTo('create article');
$I->click('New Article');
$I->fillField('Title', sq('Article'));
$I->fillField('Body', 'Demo article with Lorem Ipsum');
$I->click('save');
$I->see(sq('Article') ,'#articles')
```
Populating Database:
``` php
<?php
for ($i = 0; $i<10; $i++) {
$I->haveInDatabase('users', array('login' => sq("user$i"), 'email' => sq("user$i").'@email.com');
}
?>
```
Cest Suite tests:
``` php
<?php
class UserTest
{
public function createUser(AcceptanceTester $I)
{
$I->createUser(sqs('user') . '@mailserver.com', sqs('login'), sqs('pwd'));
}
public function checkEmail(AcceptanceTester $I)
{
$I->seeInEmailTo(sqs('user') . '@mailserver.com', sqs('login'));
}
public function removeUser(AcceptanceTester $I)
{
$I->removeUser(sqs('user') . '@mailserver.com');
}
}
?>
```
### Config
By default produces unique string with param as a prefix:
```
sq('user') => 'user_876asd8as87a'
```
This behavior can be configured using `prefix` config param.
Old style sequences:
```yaml
Sequence:
prefix: '_'
```
Using id param inside prefix:
```yaml
Sequence:
prefix: '{id}.'
```
## Actions
<p>&nbsp;</p><div class="alert alert-warning">Module reference is taken from the source code. <a href="https://github.com/Codeception/Codeception/tree/2.4/src/Codeception/Module/Sequence.php">Help us to improve documentation. Edit module reference</a></div>

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,66 @@
# XMLRPC
Module for testing XMLRPC WebService.
This module can be used either with frameworks or PHPBrowser.
It tries to guess the framework is is attached to.
Whether framework is used it operates via standard framework modules.
Otherwise sends raw HTTP requests to url via PHPBrowser.
## Requirements
* Module requires installed php_xmlrpc extension
## Status
* Maintainer: **tiger-seo**
* Stability: **beta**
* Contact: tiger.seo@gmail.com
## Configuration
* url *optional* - the url of api
## Public Properties
* headers - array of headers going to be sent.
* params - array of sent data
* response - last response (string)
@since 1.1.5
@author tiger.seo@gmail.com
## Actions
### haveHttpHeader
Sets HTTP header
* `param string` $name
* `param string` $value
### seeResponseCodeIs
Checks response code.
* `param` $num
### seeResponseIsXMLRPC
Checks weather last response was valid XMLRPC.
This is done with xmlrpc_decode function.
### sendXMLRPCMethodCall
Sends a XMLRPC method call to remote XMLRPC-server.
* `param string` $methodName
* `param array` $parameters
<p>&nbsp;</p><div class="alert alert-warning">Module reference is taken from the source code. <a href="https://github.com/Codeception/Codeception/tree/2.4/src/Codeception/Module/XMLRPC.php">Help us to improve documentation. Edit module reference</a></div>

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff