Skip to content

Commit

Permalink
[SRV-25754] updated docs
Browse files Browse the repository at this point in the history
  • Loading branch information
KonstantinKuklin committed Sep 1, 2017
1 parent 589dc26 commit bce2bfb
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 51 deletions.
3 changes: 2 additions & 1 deletion CHANGELOG.md
@@ -1,10 +1,11 @@
# SoftMocks v1 Change Log

## master
## v1.1.3

There are next changes:
- added Travis and Scrutinizer support
- skipped running PHP7.0 tests on previously versions of PHP
- changed default namespace to \Badoo. \QA namespace marked as deprecated and will be removed in 2.0.0

## v1.1.2

Expand Down
52 changes: 26 additions & 26 deletions README.md
Expand Up @@ -25,15 +25,15 @@ The thing that sets SoftMocks apart (and also limits their usage) is that they n

SoftMocks don't rewrite the following system parts:
* it's own code;
* PHPUnit code (see `\QA\SoftMocks::addIgnorePath()` for details);
* PHP-Parser code (see `\QA\SoftMocks::addIgnorePath()` for details);
* PHPUnit code (see `\Badoo\SoftMocks::addIgnorePath()` for details);
* PHP-Parser code (see `\Badoo\SoftMocks::addIgnorePath()` for details);
* already rewritten code;
* code which was loaded before SoftMocks initialization.

In order to add external dependencies (for example, vendor/autoload.php) in file, which which was loaded before SoftMocks initialization, you need to use a wrapper:
```
require_once (\QA\SoftMocks::rewrite('vendor/autoload.php'));
require_once (\QA\SoftMocks::rewrite('path/to/external/lib.php'));
require_once (\Badoo\SoftMocks::rewrite('vendor/autoload.php'));
require_once (\Badoo\SoftMocks::rewrite('path/to/external/lib.php'));
```

After you've added the file via `SoftMocks::rewrite()`, all nested include calls will already be "wrapped" by the system itself.
Expand Down Expand Up @@ -69,13 +69,13 @@ API (short description)
Initialize SoftMocks (set phpunit injections, define internal mocks, get list of internal functions, etc):

```
\QA\SoftMocks::init();
\Badoo\SoftMocks::init();
```

Cache files are created in /tmp/mocks by default. If you want to choose a different path, you can redefine it as follows:

```
\QA\SoftMocks::setMocksCachePath($cache_path);
\Badoo\SoftMocks::setMocksCachePath($cache_path);
```

Redefine constant
Expand All @@ -86,25 +86,25 @@ You can assign a new value to $constantName or create one if it wasn't already d
Both "regular constants" and class constants like "className::CONST_NAME" are supported.

```
\QA\SoftMocks::redefineConstant($constantName, $value)
\Badoo\SoftMocks::redefineConstant($constantName, $value)
```

Redefine functions
==

SoftMocks let you redefine both user-defined and built-in functions except for those that depend on the current context (see \QA\SoftMocksTraverser::$ignore_functions property if you want to see the full list), or for those that have built-in mocks (debug_backtrace, call_user_func* and a few others, but built-in mocks you can enable redefine by call `\QA\SoftMocks::setRewriteInternal(true)`).
SoftMocks let you redefine both user-defined and built-in functions except for those that depend on the current context (see \Badoo\SoftMocksTraverser::$ignore_functions property if you want to see the full list), or for those that have built-in mocks (debug_backtrace, call_user_func* and a few others, but built-in mocks you can enable redefine by call `\Badoo\SoftMocks::setRewriteInternal(true)`).

Definition:
```
\QA\SoftMocks::redefineFunction($func, $functionArgs, $fakeCode)
\Badoo\SoftMocks::redefineFunction($func, $functionArgs, $fakeCode)
```

Usage example (redefine strlen function and call original for the trimmed string):
```
\QA\SoftMocks::redefineFunction(
\Badoo\SoftMocks::redefineFunction(
'strlen',
'$a',
'return \\QA\\SoftMocks::callOriginal("strlen", [trim($a)]));'
'return \\Badoo\\SoftMocks::callOriginal("strlen", [trim($a)]));'
);
var_dump(strlen(" a ")); // int(1)
Expand All @@ -117,7 +117,7 @@ At the moment, only user-defined method redefinition is supported. This function

Definition:
```
\QA\SoftMocks::redefineMethod($class, $method, $functionArgs, $fakeCode)
\Badoo\SoftMocks::redefineMethod($class, $method, $functionArgs, $fakeCode)
```

Arguments are the same as for redefineFunction, but argument $class is introduced.
Expand All @@ -129,25 +129,25 @@ Redefining functions that are generators
This method that lets you replace a generator function call with another \Generator. Generators differ from regular functions in that you can't return a value using "return"; you have to use "yield".

```
\QA\SoftMocks::redefineGenerator($class, $method, \Generator $replacement)
\Badoo\SoftMocks::redefineGenerator($class, $method, \Generator $replacement)
```

Restore values
==

The following functions undo mocks that were made using one of the redefine methods described above.
```
\QA\SoftMocks::restoreAll()
\Badoo\SoftMocks::restoreAll()
// You can also undo only chosen mocks:
\QA\SoftMocks::restoreConstant($constantName)
\QA\SoftMocks::restoreAllConstants()
\QA\SoftMocks::restoreFunction($func)
\QA\SoftMocks::restoreMethod($class, $method)
\QA\SoftMocks::restoreGenerator($class, $method)
\QA\SoftMocks::restoreNew()
\QA\SoftMocks::restoreAllNew()
\QA\SoftMocks::restoreExit()
\Badoo\SoftMocks::restoreConstant($constantName)
\Badoo\SoftMocks::restoreAllConstants()
\Badoo\SoftMocks::restoreFunction($func)
\Badoo\SoftMocks::restoreMethod($class, $method)
\Badoo\SoftMocks::restoreGenerator($class, $method)
\Badoo\SoftMocks::restoreNew()
\Badoo\SoftMocks::restoreAllNew()
\Badoo\SoftMocks::restoreExit()
```

Using with PHPUnit
Expand Down Expand Up @@ -183,7 +183,7 @@ FAQ
=
**Q**: How can I prevent a specific function/class/constant from being redefined?

**A**: Use the \QA\SoftMocks::ignore(Class|Function|Constant) method.
**A**: Use the \Badoo\SoftMocks::ignore(Class|Function|Constant) method.

**Q**: I can't override certain function calls: call_user_func(_array)?, defined, etc.

Expand All @@ -197,11 +197,11 @@ Here is an incomplete list of them:
* defined
* debug_backtrace

So you can enable intercepting for them by call `\QA\SoftMocks::setRewriteInternal(true)` after require bootstrap, but be attentive.
So you can enable intercepting for them by call `\Badoo\SoftMocks::setRewriteInternal(true)` after require bootstrap, but be attentive.
For example, if strlen and call_user_func(_array) is redefined, then you can get different result for strlen:
```php
\QA\SoftMocks::redefineFunction('call_user_func_array', '', 'return 20;');
\QA\SoftMocks::redefineFunction('strlen', '', 'return 5;');
\Badoo\SoftMocks::redefineFunction('call_user_func_array', '', 'return 20;');
\Badoo\SoftMocks::redefineFunction('strlen', '', 'return 5;');
...
strlen('test'); // will return 5
call_user_func_array('strlen', ['test']); // will return 20
Expand Down
48 changes: 24 additions & 24 deletions README.ru.md
Expand Up @@ -25,8 +25,8 @@ SoftMocks не переписывают следующие части систе

Для того, чтобы подключить какие-либо внешние зависимости (например, vendor/autoload.php) в файле, который был подключен до инициализации SoftMocks, их нужно подключить через обертку:
```
require_once (\QA\SoftMocks::rewrite('vendor/autoload.php'));
require_once (\QA\SoftMocks::rewrite('path/to/external/lib.php'));
require_once (\Badoo\SoftMocks::rewrite('vendor/autoload.php'));
require_once (\Badoo\SoftMocks::rewrite('path/to/external/lib.php'));
```

После того, как вы подключите файл через SoftMocks::rewrite(), все вложенные вызовы `include` уже будут «обернуты» самой системой.
Expand Down Expand Up @@ -60,12 +60,12 @@ Result after reverting SoftMocks = array (
API (краткое описание)
=
```
\QA\SoftMocks::init();
\Badoo\SoftMocks::init();
```
Инициализирует софт-моки. По умолчанию, кэш файлов создаётся в /tmp/mocks. Если вам такой путь не подходит, то его можно переопределить следующим образом:

```
\QA\SoftMocks::setMocksCachePath($cache_path);
\Badoo\SoftMocks::setMocksCachePath($cache_path);
```


Expand All @@ -77,25 +77,25 @@ API (краткое описание)
Поддерживаются как «обычные константы», так и константы классов, с синтаксисом "className::CONST_NAME".

```
\QA\SoftMocks::redefineConstant($constantName, $value)
\Badoo\SoftMocks::redefineConstant($constantName, $value)
```

Переопределение функций
==

Soft Mocks позволяет переопределить как пользовательские, так и встроенные функции, кроме функций, которые зависят от текущего контекста (см. свойство \QA\SoftMocksTraverser::$ignore_functions), а также тех, для которых есть встроенные моки (debug_backtrace, call_user_func* и некоторые другие, но встроенные моки можно разрешить переотпределять через `\QA\SoftMocks::setRewriteInternal(true)`).
Soft Mocks позволяет переопределить как пользовательские, так и встроенные функции, кроме функций, которые зависят от текущего контекста (см. свойство \Badoo\SoftMocksTraverser::$ignore_functions), а также тех, для которых есть встроенные моки (debug_backtrace, call_user_func* и некоторые другие, но встроенные моки можно разрешить переотпределять через `\Badoo\SoftMocks::setRewriteInternal(true)`).

Сигнатура:
```
\QA\SoftMocks::redefineFunction($func, $functionArgs, $fakeCode)
\Badoo\SoftMocks::redefineFunction($func, $functionArgs, $fakeCode)
```

Пример использования (переопределить функцию strlen и вызвать оригинальную для trim'нутой строки):
```
\QA\SoftMocks::redefineFunction(
\Badoo\SoftMocks::redefineFunction(
'strlen',
'$a',
'return \\QA\\SoftMocks::callOriginal("strlen", [trim($a)]));'
'return \\Badoo\\SoftMocks::callOriginal("strlen", [trim($a)]));'
);
var_dump(strlen(" a ")); // int(1)
Expand All @@ -108,7 +108,7 @@ var_dump(strlen(" a ")); // int(1)

Сигнатура:
```
\QA\SoftMocks::redefineMethod($class, $method, $functionArgs, $fakeCode)
\Badoo\SoftMocks::redefineMethod($class, $method, $functionArgs, $fakeCode)
```

Отличие от redefineFunction состоит в наличии класса ($class).
Expand All @@ -120,7 +120,7 @@ var_dump(strlen(" a ")); // int(1)
Метод позволяет заменить вызов функции-генератора на \Callable-объект также являющийся генератором. Генераторы отличаются от обычных функций тем, что в них невозможно вернуть значение через return и обязательно нужно пользоваться yield.

```
\QA\SoftMocks::redefineGenerator($class, $method, Callable $replacement)
\Badoo\SoftMocks::redefineGenerator($class, $method, Callable $replacement)
```

Восстановление значений
Expand All @@ -129,17 +129,17 @@ var_dump(strlen(" a ")); // int(1)
Следующие функции отменяют замену, осуществлённую одним из приведенных раннее redefine-методов.

```
\QA\SoftMocks::restoreAll()
\Badoo\SoftMocks::restoreAll()
// Так же можно отменить конкретные моки:
\QA\SoftMocks::restoreConstant($constantName)
\QA\SoftMocks::restoreAllConstants()
\QA\SoftMocks::restoreFunction($func)
\QA\SoftMocks::restoreMethod($class, $method)
\QA\SoftMocks::restoreGenerator($class, $method)
\QA\SoftMocks::restoreNew()
\QA\SoftMocks::restoreAllNew()
\QA\SoftMocks::restoreExit()
\Badoo\SoftMocks::restoreConstant($constantName)
\Badoo\SoftMocks::restoreAllConstants()
\Badoo\SoftMocks::restoreFunction($func)
\Badoo\SoftMocks::restoreMethod($class, $method)
\Badoo\SoftMocks::restoreGenerator($class, $method)
\Badoo\SoftMocks::restoreNew()
\Badoo\SoftMocks::restoreAllNew()
\Badoo\SoftMocks::restoreExit()
```

Использование совместно с PHPUnit
Expand Down Expand Up @@ -175,7 +175,7 @@ FAQ
=
**Q**: Как запретить переопределять ту или иную функцию/класс/константу?

**A**: Используйте методы \QA\SoftMocks::ignore(Class|Function|Constant).
**A**: Используйте методы \Badoo\SoftMocks::ignore(Class|Function|Constant).

**Q**: Я не могу переопределить вызовы некоторых функций: call_user_func(_array)?, defined, etc.

Expand All @@ -188,11 +188,11 @@ FAQ
* defined
* debug_backtrace

Что бы включить перехватывание для них, нужно вызвать `\QA\SoftMocks::setRewriteInternal(true)` после подключения bootstrap-а, но будьте внимателены.
Что бы включить перехватывание для них, нужно вызвать `\Badoo\SoftMocks::setRewriteInternal(true)` после подключения bootstrap-а, но будьте внимателены.
Например, если strlen и call_user_func(_array) переопределены, то можно получить разные результаты для strlen:
```php
\QA\SoftMocks::redefineFunction('call_user_func_array', '', function () {return 20;});
\QA\SoftMocks::redefineFunction('strlen', '', function () {return 5;});
\Badoo\SoftMocks::redefineFunction('call_user_func_array', '', function () {return 20;});
\Badoo\SoftMocks::redefineFunction('strlen', '', function () {return 5;});
...
strlen('test'); // вернет 5
call_user_func_array('strlen', ['test']); // вернет 20
Expand Down
5 changes: 5 additions & 0 deletions UPGRADE.md
@@ -1,3 +1,8 @@
# Upgrading Instructions for SoftMocks 1.1.3

- Class `\QA\SoftMocks` marked as deprecated
- All methods of `\QA\SoftMocks` moved to `\Badoo\SoftMocks`

# Upgrading Instructions for SoftMocks 1.1.2

!!!IMPORTANT!!!
Expand Down

0 comments on commit bce2bfb

Please sign in to comment.