├── .gitignore
├── .php_cs.dist
├── .scrutinizer.yml
├── LICENSE
├── README.md
├── codeception.https.yml
├── codeception.yml
├── composer.json
├── phpunit.xml
├── run-tests.sh
├── src
├── Connection
│ ├── Host.php
│ ├── Port.php
│ └── Scheme.php
├── Factory.php
├── Phiremock.php
├── Utils
│ ├── A.php
│ ├── ConditionsBuilder.php
│ ├── ConditionsBuilderResult.php
│ ├── ExpectationBuilder.php
│ ├── Http
│ │ └── GuzzlePsr18Client.php
│ ├── HttpResponseBuilder.php
│ ├── Is.php
│ ├── Proxy.php
│ ├── ProxyResponseBuilder.php
│ ├── Respond.php
│ └── ResponseBuilder.php
└── helper_functions.php
└── tests
├── acceptance
├── _data
│ └── .gitignore
├── _output
│ └── .gitignore
├── _support
│ ├── ApiTester.php
│ ├── Helper
│ │ └── Api.php
│ └── _generated
│ │ └── .gitignore
├── api.suite.yml
└── api
│ ├── ClearExpectationsCest.php
│ ├── CountExecutionsCest.php
│ ├── ExpectationCreationCest.php
│ ├── ListExecutionsCest.php
│ ├── ListExpectationsCest.php
│ ├── PhiremockApiTestHelper.php
│ ├── ResetCest.php
│ ├── ResetRequestCounterCest.php
│ ├── ResetScenariosCest.php
│ └── ScenarioStateCest.php
├── bootstrap.php
├── codeception
├── Extensions
│ └── ServerControl.php
└── Modules
│ └── PhiremockClient.php
└── unit
└── Utils
├── ConditionsBuilderTest.php
└── HttpResponseBuilderTest.php
/.gitignore:
--------------------------------------------------------------------------------
1 | composer.phar
2 | /vendor/
3 |
4 | # Commit your application's lock file http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file
5 | # You may choose to ignore a library lock file http://getcomposer.org/doc/02-libraries.md#lock-file
6 | composer.lock
7 |
8 | .phpunit.result.cache
9 |
--------------------------------------------------------------------------------
/.php_cs.dist:
--------------------------------------------------------------------------------
1 | setRiskyAllowed(true)
5 | ->setRules(
6 | [
7 | // PSR-12
8 | '@PSR2' => true,
9 | 'blank_line_after_opening_tag' => true,
10 | 'braces' => ['allow_single_line_closure' => true],
11 | 'compact_nullable_typehint' => true,
12 | 'concat_space' => ['spacing' => 'one'],
13 | 'declare_equal_normalize' => ['space' => 'none'],
14 | 'function_typehint_space' => true,
15 | 'new_with_braces' => true,
16 | 'method_argument_space' => ['on_multiline' => 'ensure_fully_multiline'],
17 | 'no_empty_statement' => true,
18 | 'no_leading_import_slash' => true,
19 | 'no_leading_namespace_whitespace' => true,
20 | 'no_whitespace_in_blank_line' => true,
21 | 'return_type_declaration' => ['space_before' => 'none'],
22 | 'single_trait_insert_per_statement' => true,
23 |
24 | // Own extras
25 | 'array_syntax' => ['syntax' => 'short'],
26 | 'combine_consecutive_unsets' => true,
27 | 'general_phpdoc_annotation_remove' => ['expectedException', 'expectedExceptionMessage', 'expectedExceptionMessageRegExp'],
28 | 'heredoc_to_nowdoc' => true,
29 | 'no_extra_consecutive_blank_lines' => ['break', 'continue', 'extra', 'return', 'throw', 'use', 'parenthesis_brace_block', 'square_brace_block', 'curly_brace_block'],
30 | 'no_unreachable_default_argument_value' => true,
31 | 'no_unused_imports' => true,
32 | 'no_useless_else' => true,
33 | 'no_useless_return' => true,
34 | 'ordered_class_elements' => true,
35 | 'ordered_imports' => true,
36 | 'php_unit_strict' => true,
37 | 'phpdoc_add_missing_param_annotation' => true,
38 | 'phpdoc_order' => true,
39 | 'psr4' => true,
40 | 'strict_comparison' => true,
41 | 'strict_param' => true,
42 | 'binary_operator_spaces' => ['align_double_arrow' => true],
43 | 'yoda_style' => ['equal' => false, 'identical' => false, 'less_and_greater' => false, 'always_move_variable' => true],
44 | 'is_null' => ['use_yoda_style' => false],
45 | ])
46 | ->setFinder(
47 | PhpCsFixer\Finder::create()
48 | ->in(__DIR__ . '/src')
49 | ->in(__DIR__ . '/tests')
50 | )
51 | ;
52 |
--------------------------------------------------------------------------------
/.scrutinizer.yml:
--------------------------------------------------------------------------------
1 | filter:
2 | paths: [src/*]
3 | excluded_paths: [vendor/*, test/*]
4 | before_commands:
5 | - 'composer install --dev --prefer-source'
6 |
7 | build:
8 | environment:
9 | postgresql: false
10 | mysql: false
11 | redis: false
12 | tests:
13 | override:
14 | - php-scrutinizer-run
15 | - ./vendor/bin/codecept run
16 | - ./vendor/bin/phpunit
17 | nodes:
18 | php72:
19 | environment:
20 | php:
21 | version: 7.2
22 | php73:
23 | environment:
24 | php:
25 | version: 7.3
26 | php74:
27 | environment:
28 | php:
29 | version: 7.4
30 | php80:
31 | environment:
32 | php:
33 | version: 8.0
34 | php81:
35 | environment:
36 | php:
37 | version: 8.1
38 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Phiremock Client
2 |
3 | Phiremock client provides a nice API to interact with [Phiremock Server](https://github.com/mcustiel/phiremock-server), allowing developers to setup expectations, clear state, scenarios etc. Through a fluent interface.
4 |
5 | [](https://packagist.org/packages/mcustiel/phiremock-client)
6 | [](https://scrutinizer-ci.com/g/mcustiel/phiremock-client/build-status/master)
7 | [](https://scrutinizer-ci.com/g/mcustiel/phiremock-client/?branch=master)
8 | [](https://packagist.org/packages/mcustiel/phiremock-client)
9 |
10 | ## Installation
11 |
12 | ### Default installation through composer
13 |
14 | This project is published in packagist, so you just need to add it as a dependency in your composer.json:
15 |
16 | ```json
17 | "require-dev": {
18 | "mcustiel/phiremock-client": "^1.0",
19 | "guzzlehttp/guzzle": "^6.0"
20 | }
21 | ```
22 | Phiremock Client requires guzzle client v6 to work. This dependency can be avoided and you can choose any psr18-compatible http client and overwrite Phiremock Client's factory to provide it.
23 |
24 |
25 | ### Overwriting the factory class
26 |
27 | If guzzle client v6 is provided as a dependency no extra configuration is needed. If you want to use a different http client you need to provide it to phiremock server as a psr18-compatible client.
28 | For instance, if you want to use guzzle client v7 you need to extend phiremock server's factory class:
29 |
30 | ```php
31 | createPhiremockClient(new Host('my.phiremock.host'), new Port('8080'));
59 | ```
60 |
61 | Now you can use `$phiremockClient` to access all the configuration options of Phiremock Server.
62 |
63 | *Note:* Phiremock will by default listen for http (unsecured) connections.
64 |
65 | #### Connection to a secure server
66 |
67 | If phiremock-server is listening for https connections. You can pass the scheme to use as a third argument:
68 |
69 | ```php
70 | createPhiremockClient(new Host('my.phiremock.host'), new Port('8443'), Scheme::createHttps());
76 | ```
77 |
78 | ### Expectation creation
79 |
80 | ```php
81 | createExpectation(
89 | Phiremock::on(
90 | A::getRequest()
91 | ->andUrl(Is::equalTo('/potato/tomato'))
92 | ->andBody(Is::containing('42'))
93 | ->andHeader('Accept', Is::equalTo('application/banana'))
94 | ->andFormField('name', Is::equalTo('potato'))
95 | )->then(
96 | Respond::withStatusCode(418)
97 | ->andBody('Is the answer to the Ultimate Question of Life, The Universe, and Everything')
98 | ->andHeader('Content-Type', 'application/banana')
99 | )->setPriority(new Priority(5))
100 | );
101 |
102 | ```
103 |
104 | Also a cleaner/shorter way to create expectations is provided by using helper functions:
105 |
106 | ```php
107 | createExpectation(
118 | on(
119 | getRequest('/potato/tomato')
120 | ->andBody(contains('42'))
121 | ->andHeader('Accept', isEqualTo('application/banana'))
122 | ->andFormField('name', isEqualTo('potato'))
123 | )->then(
124 | respond(418)
125 | ->andBody('Is the answer to the Ultimate Question of Life, The Universe, and Everything')
126 | ->andHeader('Content-Type', 'application/banana')
127 | )->setPriority(new Priority(5))
128 | );
129 | ```
130 | This code is equivalent to the one in the previous example.
131 |
132 | You can see the list of shortcuts here: https://github.com/mcustiel/phiremock-client/blob/master/src/helper_functions.php
133 |
134 | ### Listing created expectations
135 | The `listExpecatations` method returns an array of instances of the Expectation class containing all the current expectations checked by Phiremock Server.
136 |
137 | ```php
138 | listExpectations();
140 | ```
141 |
142 | ### Clear all configured expectations
143 | This will remove all expectations checked, causing Phiremock Server to return 404 for every non-phiremock-api request.
144 |
145 | ```php
146 | clearExpectations();
148 | ```
149 |
150 | ### List requests received by Phiremock
151 | Use this method to get a list of Psr-compatible Requests received by Phiremock Server.
152 |
153 | Lists all requests:
154 |
155 | ```php
156 | listExecutions();
158 | ```
159 |
160 | Lists requests matching condition:
161 |
162 | ```php
163 | listExecutions(getRequest()->andUrl(isEqualTo('/test'));
165 | ```
166 |
167 | **Note:** Phiremock's API request are excluded from this list.
168 |
169 | ### Count requests received by Phiremock
170 | Provides an integer >= 0 representing the amount of requests received by Phiremock Server.
171 |
172 | Count all requests:
173 |
174 | ```php
175 | countExecutions();
177 | ```
178 |
179 | Count requests matching condition:
180 |
181 | ```php
182 | countExecutions(getRequest()->andUrl(isEqualTo('/test'));
184 | ```
185 |
186 | **Note:** Phiremock's API request are excluded from this list.
187 |
188 | ### Clear stored requests
189 | This will clean the list of requests saved on Phiremock Server and resets the counter to 0.
190 |
191 | ```php
192 | clearRequests();
194 | ```
195 |
196 | ### Set Scenario State
197 | Force a scenario to have certain state on Phiremock Server.
198 |
199 | ```php
200 | setScenarioState('myScenario', 'loginExecuted');
202 | ```
203 |
204 | ### Reset Scenarios States
205 | Reset all scenarios to the initial state (Scenario.START).
206 |
207 | ```php
208 | resetScenarios();
210 | ```
211 |
212 | ### Reset all
213 | Sets Phiremock Server to its initial state. This will cause Phiremock Server to:
214 | 1. clear all expectations.
215 | 2. clear the stored requests.
216 | 3. reset all the scenarios.
217 | 4. reload all expectations stored in files.
218 |
219 | ```php
220 | reset();
222 | ```
223 |
224 | ## Appendix
225 |
226 | ### See also:
227 |
228 | * Phiremock Server: https://github.com/mcustiel/phiremock-server
229 | * Phiremock Codeception Module: https://github.com/mcustiel/phiremock-codeception-module
230 | * Examples in tests: https://github.com/mcustiel/phiremock-client/tree/master/tests/acceptance/api
231 |
232 | ### Contributing:
233 |
234 | Just submit a pull request. Don't forget to run tests and php-cs-fixer first and write documentation.
235 |
236 | ### Thanks to:
237 |
238 | * Denis Rudoi ([@drudoi](https://github.com/drudoi))
239 | * Henrik Schmidt ([@mrIncompetent](https://github.com/mrIncompetent))
240 | * Nils Gajsek ([@linslin](https://github.com/linslin))
241 | * Florian Levis ([@Gounlaf](https://github.com/Gounlaf))
242 |
243 | And [everyone](https://github.com/mcustiel/phiremock/graphs/contributors) who submitted their Pull Requests.
244 |
--------------------------------------------------------------------------------
/codeception.https.yml:
--------------------------------------------------------------------------------
1 | extensions:
2 | enabled:
3 | - Codeception\Extension\RunFailed
4 | - Mcustiel\Codeception\Extensions\ServerControl:
5 | https: true
6 |
7 | params:
8 | - env
9 |
10 | paths:
11 | tests: tests/acceptance
12 | output: tests/acceptance/_output
13 | data: tests/acceptance/_data
14 | support: tests/acceptance/_support
15 | envs: tests/acceptance/_envs
16 |
17 | settings:
18 | shuffle: false
19 | lint: true
20 | colors: true
21 | memory_limit: 1024M
22 |
--------------------------------------------------------------------------------
/codeception.yml:
--------------------------------------------------------------------------------
1 | extensions:
2 | enabled:
3 | - Codeception\Extension\RunFailed
4 | - Mcustiel\Codeception\Extensions\ServerControl
5 |
6 | env:
7 | https:
8 | extension:
9 | enabled:
10 | - Mcustiel\Codeception\Extensions\ServerControl:
11 | https: true
12 |
13 |
14 | params:
15 | - env
16 |
17 | paths:
18 | tests: tests/acceptance
19 | output: tests/acceptance/_output
20 | data: tests/acceptance/_data
21 | support: tests/acceptance/_support
22 | envs: tests/acceptance/_envs
23 |
24 | settings:
25 | shuffle: false
26 | lint: true
27 | colors: true
28 | memory_limit: 1024M
29 |
--------------------------------------------------------------------------------
/composer.json:
--------------------------------------------------------------------------------
1 | {
2 | "keywords": [
3 | "http",
4 | "mock",
5 | "server",
6 | "external",
7 | "acceptance",
8 | "tests"
9 | ],
10 | "authors": [
11 | {
12 | "name": "Mariano Custiel",
13 | "email": "jmcustiel@gmail.com",
14 | "homepage": "https://github.com/mcustiel",
15 | "role": "Developer"
16 | }
17 | ],
18 | "name": "mcustiel/phiremock-client",
19 | "type": "project",
20 | "description": "Client library to communicate with Phiremock server",
21 | "license": "GPL-3.0-or-later",
22 | "require": {
23 | "php": "^7.2|^8.0",
24 | "ext-json": "*",
25 | "mcustiel/phiremock-common": "^1.0",
26 | "psr/http-client": "^1.0"
27 | },
28 | "require-dev": {
29 | "phpunit/phpunit": "^8.0|^9.0",
30 | "codeception/codeception": "^4.0|^5.0",
31 | "codeception/module-asserts": ">=1.0 <4.0",
32 | "codeception/module-rest": ">=1.0 <4.0",
33 | "codeception/module-phpbrowser": ">=1.0 <4.0",
34 | "mcustiel/phiremock-server": "^1.0",
35 | "symfony/process": ">=3.0 <7.0",
36 | "guzzlehttp/guzzle" : "^6.0"
37 | },
38 | "autoload": {
39 | "psr-4": {
40 | "Mcustiel\\Phiremock\\Client\\": "src"
41 | },
42 | "files": [
43 | "src/helper_functions.php"
44 | ]
45 | },
46 | "autoload-dev": {
47 | "psr-4": {
48 | "Mcustiel\\Codeception\\": "tests/codeception",
49 | "Mcustiel\\Phiremock\\Client\\Tests\\Acceptance\\": "tests/acceptance/api",
50 | "Mcustiel\\Phiremock\\Client\\Tests\\Unit\\": "tests/unit"
51 | }
52 | },
53 | "suggest": {
54 | "guzzlehttp/guzzle": "Provides default client for http requests execution."
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/phpunit.xml:
--------------------------------------------------------------------------------
1 |
2 |
20 |
23 |
24 | ./tests/unit
25 |
26 |
27 |
28 | ./src
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/run-tests.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ./vendor/bin/codecept run && \
4 | ./vendor/bin/codecept -c codeception.https.yml run --env https $@
5 |
--------------------------------------------------------------------------------
/src/Connection/Host.php:
--------------------------------------------------------------------------------
1 | .
17 | */
18 |
19 | namespace Mcustiel\Phiremock\Client\Connection;
20 |
21 | use InvalidArgumentException;
22 |
23 | class Host
24 | {
25 | /** @var string */
26 | private $host;
27 |
28 | public function __construct(string $host)
29 | {
30 | $this->ensureIsValidHost($host);
31 | $this->host = $host;
32 | }
33 |
34 | public static function createLocalhost(): Host
35 | {
36 | return new self('localhost');
37 | }
38 |
39 | public function asString(): string
40 | {
41 | return $this->host;
42 | }
43 |
44 | private function ensureIsValidHost(string $host): void
45 | {
46 | if (filter_var($host, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME) === false &&
47 | filter_var($host, FILTER_VALIDATE_IP) === false) {
48 | throw new InvalidArgumentException(sprintf('Invalid host number: %d', $host));
49 | }
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/src/Connection/Port.php:
--------------------------------------------------------------------------------
1 | .
17 | */
18 |
19 | namespace Mcustiel\Phiremock\Client\Connection;
20 |
21 | use InvalidArgumentException;
22 |
23 | class Port
24 | {
25 | /** @var int */
26 | private $port;
27 |
28 | public function __construct(int $port)
29 | {
30 | $this->ensureIsValidPort($port);
31 | $this->port = $port;
32 | }
33 |
34 | public function asInt(): int
35 | {
36 | return $this->port;
37 | }
38 |
39 | private function ensureIsValidPort(int $port): void
40 | {
41 | if ($port < 1 || $port > 65535) {
42 | throw new InvalidArgumentException(sprintf('Invalid port number: %d', $port));
43 | }
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/Connection/Scheme.php:
--------------------------------------------------------------------------------
1 | .
17 | */
18 |
19 | namespace Mcustiel\Phiremock\Client\Connection;
20 |
21 | use InvalidArgumentException;
22 |
23 | class Scheme
24 | {
25 | public const HTTP = 'http';
26 | public const HTTPS = 'https';
27 |
28 | /** @var string */
29 | private $scheme;
30 |
31 | public function __construct(string $scheme)
32 | {
33 | $this->ensureIsValidScheme($scheme);
34 | $this->scheme = $scheme;
35 | }
36 |
37 | public static function createHttp(): Scheme
38 | {
39 | return new self(self::HTTP);
40 | }
41 |
42 | public static function createHttps(): Scheme
43 | {
44 | return new self(self::HTTPS);
45 | }
46 |
47 | public function asString(): string
48 | {
49 | return $this->scheme;
50 | }
51 |
52 | private function ensureIsValidScheme(string $scheme): void
53 | {
54 | if (preg_match('/^https?$/', $scheme) !== 1) {
55 | throw new InvalidArgumentException(sprintf('Invalid scheme %s', $scheme));
56 | }
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/src/Factory.php:
--------------------------------------------------------------------------------
1 | .
17 | */
18 |
19 | namespace Mcustiel\Phiremock\Client;
20 |
21 | use Exception;
22 | use Mcustiel\Phiremock\Client\Connection\Host;
23 | use Mcustiel\Phiremock\Client\Connection\Port;
24 | use Mcustiel\Phiremock\Client\Connection\Scheme;
25 | use Mcustiel\Phiremock\Client\Utils\Http\GuzzlePsr18Client;
26 | use Mcustiel\Phiremock\Factory as PhiremockFactory;
27 | use Psr\Http\Client\ClientInterface;
28 |
29 | class Factory
30 | {
31 | /** @var PhiremockFactory */
32 | private $phiremockFactory;
33 |
34 | public function __construct(PhiremockFactory $factory)
35 | {
36 | $this->phiremockFactory = $factory;
37 | }
38 |
39 | public static function createDefault(): self
40 | {
41 | return new static(new PhiremockFactory());
42 | }
43 |
44 | /** @throws Exception */
45 | public function createPhiremockClient(Host $host, Port $port, ?Scheme $scheme = null): Phiremock
46 | {
47 | return new Phiremock(
48 | $host,
49 | $port,
50 | $this->createRemoteConnection(),
51 | $this->phiremockFactory->createV2UtilsFactory()->createExpectationToArrayConverter(),
52 | $this->phiremockFactory->createV2UtilsFactory()->createArrayToExpectationConverter(),
53 | $this->phiremockFactory->createV2UtilsFactory()->createScenarioStateInfoToArrayConverter(),
54 | $scheme
55 | );
56 | }
57 |
58 | public function createSecurePhiremockClient(Host $host, Port $port): Phiremock
59 | {
60 | return new Phiremock(
61 | $host,
62 | $port,
63 | $this->createRemoteConnection(),
64 | $this->phiremockFactory->createV2UtilsFactory()->createExpectationToArrayConverter(),
65 | $this->phiremockFactory->createV2UtilsFactory()->createArrayToExpectationConverter(),
66 | $this->phiremockFactory->createV2UtilsFactory()->createScenarioStateInfoToArrayConverter(),
67 | Scheme::createHttps()
68 | );
69 | }
70 |
71 | /** @throws Exception */
72 | public function createRemoteConnection(): ClientInterface
73 | {
74 | if (!class_exists('\GuzzleHttp\Client', true)) {
75 | throw new Exception('A default http client implementation is needed. ' . 'Please extend the factory to return a PSR18-compatible HttpClient or install Guzzle Http Client v6');
76 | }
77 | return new GuzzlePsr18Client();
78 | }
79 |
80 | protected function getPhiremockFactory(): PhiremockFactory
81 | {
82 | return $this->phiremockFactory;
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/src/Phiremock.php:
--------------------------------------------------------------------------------
1 | .
17 | */
18 |
19 | namespace Mcustiel\Phiremock\Client;
20 |
21 | use Laminas\Diactoros\Request as PsrRequest;
22 | use Laminas\Diactoros\Uri;
23 | use Mcustiel\Phiremock\Client\Connection\Host;
24 | use Mcustiel\Phiremock\Client\Connection\Port;
25 | use Mcustiel\Phiremock\Client\Connection\Scheme;
26 | use Mcustiel\Phiremock\Client\Utils\ConditionsBuilder;
27 | use Mcustiel\Phiremock\Client\Utils\ExpectationBuilder;
28 | use Mcustiel\Phiremock\Common\StringStream;
29 | use Mcustiel\Phiremock\Common\Utils\ArrayToExpectationConverter;
30 | use Mcustiel\Phiremock\Common\Utils\ExpectationToArrayConverter;
31 | use Mcustiel\Phiremock\Common\Utils\ScenarioStateInfoToArrayConverter;
32 | use Mcustiel\Phiremock\Domain\Expectation;
33 | use Mcustiel\Phiremock\Domain\HttpResponse;
34 | use Mcustiel\Phiremock\Domain\Options\ScenarioName;
35 | use Mcustiel\Phiremock\Domain\Options\ScenarioState;
36 | use Mcustiel\Phiremock\Domain\ScenarioStateInfo;
37 | use Mcustiel\Phiremock\Domain\Version;
38 | use Psr\Http\Client\ClientExceptionInterface;
39 | use Psr\Http\Client\ClientInterface;
40 | use Psr\Http\Message\ResponseInterface;
41 | use RuntimeException;
42 |
43 | class Phiremock
44 | {
45 | const API_EXPECTATIONS_URL = '/__phiremock/expectations';
46 | const API_EXECUTIONS_URL = '/__phiremock/executions';
47 | const API_SCENARIOS_URL = '/__phiremock/scenarios';
48 | const API_RESET_URL = '/__phiremock/reset';
49 |
50 | /** @var ClientInterface */
51 | private $connection;
52 |
53 | /** @var ArrayToExpectationConverter */
54 | private $arrayToExpectationConverter;
55 |
56 | /** @var ExpectationToArrayConverter */
57 | private $expectationToArrayConverter;
58 |
59 | /** @var ScenarioStateInfoToArrayConverter */
60 | private $scenarioStateInfoToArrayConverter;
61 |
62 | /** @var Host */
63 | private $host;
64 |
65 | /** @var Port */
66 | private $port;
67 |
68 | /** @var Scheme */
69 | private $scheme;
70 |
71 | public function __construct(
72 | Host $host,
73 | Port $port,
74 | ClientInterface $remoteConnection,
75 | ExpectationToArrayConverter $expectationToArrayConverter,
76 | ArrayToExpectationConverter $arrayToExpectationConverter,
77 | ScenarioStateInfoToArrayConverter $scenarioStateInfoToArrayConverter,
78 | ?Scheme $scheme = null
79 | ) {
80 | $this->host = $host;
81 | $this->port = $port;
82 | $this->connection = $remoteConnection;
83 | $this->expectationToArrayConverter = $expectationToArrayConverter;
84 | $this->arrayToExpectationConverter = $arrayToExpectationConverter;
85 | $this->scenarioStateInfoToArrayConverter = $scenarioStateInfoToArrayConverter;
86 | $this->scheme = $scheme ?? Scheme::createHttp();
87 | }
88 |
89 | /**
90 | * Creates an expectation with a response for a given request.
91 | * @throws ClientExceptionInterface
92 | */
93 | public function createExpectation(Expectation $expectation): void
94 | {
95 | $body = @json_encode($this->expectationToArrayConverter->convert($expectation));
96 | if (json_last_error() !== JSON_ERROR_NONE) {
97 | throw new RuntimeException('Error generating json body for request: ' . json_last_error_msg());
98 | }
99 | $this->createExpectationFromJson($body);
100 | }
101 |
102 | /**
103 | * Creates an expectation from a json configuration
104 | * @throws ClientExceptionInterface
105 | */
106 | public function createExpectationFromJson(string $body): void
107 | {
108 | $uri = $this->createBaseUri()->withPath(self::API_EXPECTATIONS_URL);
109 | $request = (new PsrRequest())
110 | ->withUri($uri)
111 | ->withMethod('POST')
112 | ->withHeader('Content-Type', 'application/json')
113 | ->withBody(new StringStream($body));
114 | $this->ensureIsExpectedResponse(201, $this->connection->sendRequest($request));
115 | }
116 |
117 | /**
118 | * Restores pre-defined expectations and resets scenarios and requests counter.
119 | * @throws ClientExceptionInterface
120 | */
121 | public function reset(): void
122 | {
123 | $uri = $this->createBaseUri()->withPath(self::API_RESET_URL);
124 | $request = (new PsrRequest())->withUri($uri)->withMethod('POST');
125 |
126 | $this->ensureIsExpectedResponse(200, $this->connection->sendRequest($request));
127 | }
128 |
129 | /**
130 | * Clears all the currently configured expectations.
131 | * @throws ClientExceptionInterface
132 | */
133 | public function clearExpectations(): void
134 | {
135 | $uri = $this->createBaseUri()->withPath(self::API_EXPECTATIONS_URL);
136 | $request = (new PsrRequest())->withUri($uri)->withMethod('DELETE');
137 |
138 | $this->ensureIsExpectedResponse(200, $this->connection->sendRequest($request));
139 | }
140 |
141 | /**
142 | * @throws ClientExceptionInterface
143 | * @return Expectation[]
144 | */
145 | public function listExpectations(): array
146 | {
147 | $uri = $this->createBaseUri()->withPath(self::API_EXPECTATIONS_URL);
148 | $request = (new PsrRequest())->withUri($uri)->withMethod('GET');
149 | $response = $this->connection->sendRequest($request);
150 |
151 | $this->ensureIsExpectedResponse(200, $response);
152 |
153 | $arraysList = json_decode($response->getBody()->__toString(), true);
154 | $expectationsList = [];
155 |
156 | foreach ($arraysList as $expectationArray) {
157 | $expectationsList[] = $this->arrayToExpectationConverter
158 | ->convert($expectationArray);
159 | }
160 | return $expectationsList;
161 | }
162 |
163 | /** @throws ClientExceptionInterface */
164 | public function countExecutions(?ConditionsBuilder $requestBuilder = null): int
165 | {
166 | $uri = $this->createBaseUri()->withPath(self::API_EXECUTIONS_URL);
167 |
168 | $request = (new PsrRequest())
169 | ->withUri($uri)
170 | ->withMethod('POST')
171 | ->withHeader('Content-Type', 'application/json');
172 | if ($requestBuilder !== null) {
173 | $requestBuilderResult = $requestBuilder->build();
174 | $expectation = new Expectation(
175 | $requestBuilderResult->getRequestConditions(),
176 | HttpResponse::createEmpty(),
177 | $requestBuilderResult->getScenarioName(),
178 | null,
179 | new Version('2')
180 | );
181 | $jsonBody = json_encode($this->expectationToArrayConverter->convert($expectation));
182 | $request = $request->withBody(
183 | new StringStream(
184 | $jsonBody
185 | )
186 | );
187 | }
188 |
189 | $response = $this->connection->sendRequest($request);
190 |
191 | $this->ensureIsExpectedResponse(200, $response);
192 | $json = json_decode($response->getBody()->__toString());
193 |
194 | return $json->count;
195 | }
196 |
197 | /** @throws ClientExceptionInterface */
198 | public function listExecutions(?ConditionsBuilder $requestBuilder = null): array
199 | {
200 | $uri = $this->createBaseUri()->withPath(self::API_EXECUTIONS_URL);
201 |
202 | $request = (new PsrRequest())
203 | ->withUri($uri)
204 | ->withMethod('PUT')
205 | ->withHeader('Content-Type', 'application/json');
206 | if ($requestBuilder !== null) {
207 | $requestBuilderResult = $requestBuilder->build();
208 | $expectation = new Expectation(
209 | $requestBuilderResult->getRequestConditions(),
210 | HttpResponse::createEmpty(),
211 | $requestBuilderResult->getScenarioName(),
212 | null,
213 | new Version('2')
214 | );
215 | $request = $request->withBody(
216 | new StringStream(
217 | json_encode($this->expectationToArrayConverter->convert($expectation))
218 | )
219 | );
220 | }
221 |
222 | $response = $this->connection->sendRequest($request);
223 | $this->ensureIsExpectedResponse(200, $response);
224 | return json_decode($response->getBody()->__toString());
225 | }
226 |
227 | /**
228 | * Sets scenario state.
229 | * @throws ClientExceptionInterface
230 | */
231 | public function setScenarioState(string $scenarioName, string $scenarioState): void
232 | {
233 | $scenarioStateInfo = new ScenarioStateInfo(
234 | new ScenarioName($scenarioName),
235 | new ScenarioState($scenarioState)
236 | );
237 | $uri = $this->createBaseUri()->withPath(self::API_SCENARIOS_URL);
238 | $request = (new PsrRequest())
239 | ->withUri($uri)
240 | ->withMethod('PUT')
241 | ->withHeader('Content-Type', 'application/json')
242 | ->withBody(
243 | new StringStream(
244 | json_encode(
245 | $this->scenarioStateInfoToArrayConverter->convert($scenarioStateInfo)
246 | )
247 | )
248 | );
249 |
250 | $response = $this->connection->sendRequest($request);
251 | $this->ensureIsExpectedResponse(200, $response);
252 | }
253 |
254 | /**
255 | * Resets all the scenarios to start state.
256 | * @throws ClientExceptionInterface
257 | */
258 | public function resetScenarios(): void
259 | {
260 | $uri = $this->createBaseUri()->withPath(self::API_SCENARIOS_URL);
261 | $request = (new PsrRequest())->withUri($uri)->withMethod('DELETE');
262 |
263 | $this->ensureIsExpectedResponse(200, $this->connection->sendRequest($request));
264 | }
265 |
266 | /**
267 | * Resets all the requests counters to 0.
268 | * @throws ClientExceptionInterface
269 | */
270 | public function resetRequestsCounter(): void
271 | {
272 | $uri = $this->createBaseUri()->withPath(self::API_EXECUTIONS_URL);
273 | $request = (new PsrRequest())->withUri($uri)->withMethod('DELETE');
274 |
275 | $this->ensureIsExpectedResponse(200, $this->connection->sendRequest($request));
276 | }
277 |
278 | /**
279 | * Inits the fluent interface to create an expectation.
280 | *
281 | * @return ExpectationBuilder
282 | */
283 | public static function on(ConditionsBuilder $requestBuilder): ExpectationBuilder
284 | {
285 | return new ExpectationBuilder($requestBuilder);
286 | }
287 |
288 | /** Shortcut. */
289 | public static function onRequest(string $method, string $url): ExpectationBuilder
290 | {
291 | return new ExpectationBuilder(
292 | ConditionsBuilder::create($method, $url)
293 | );
294 | }
295 |
296 | private function createBaseUri(): Uri
297 | {
298 | return (new Uri())
299 | ->withScheme($this->scheme->asString())
300 | ->withHost($this->host->asString())
301 | ->withPort($this->port->asInt());
302 | }
303 |
304 | /** @throws RuntimeException */
305 | private function ensureIsExpectedResponse(int $statusCode, ResponseInterface $response): void
306 | {
307 | $responseStatusCode = $response->getStatusCode();
308 | if ($responseStatusCode !== $statusCode) {
309 | if ($responseStatusCode >= 500) {
310 | $errors = json_decode($response->getBody()->__toString(), true)['details'];
311 |
312 | throw new RuntimeException('An error occurred creating the expectation: ' . ($errors ? var_export($errors, true) : '') . $response->getBody()->__toString());
313 | }
314 |
315 | if ($responseStatusCode >= 400) {
316 | throw new RuntimeException('Request error while creating the expectation');
317 | }
318 | throw new RuntimeException('Unexpected response while creating the expectation');
319 | }
320 | }
321 | }
322 |
--------------------------------------------------------------------------------
/src/Utils/A.php:
--------------------------------------------------------------------------------
1 | .
17 | */
18 |
19 | namespace Mcustiel\Phiremock\Client\Utils;
20 |
21 | use Mcustiel\Phiremock\Domain\Http\MethodsEnum;
22 |
23 | class A
24 | {
25 | public static function getRequest(): ConditionsBuilder
26 | {
27 | return ConditionsBuilder::create(MethodsEnum::GET);
28 | }
29 |
30 | public static function postRequest(): ConditionsBuilder
31 | {
32 | return ConditionsBuilder::create(MethodsEnum::POST);
33 | }
34 |
35 | public static function putRequest(): ConditionsBuilder
36 | {
37 | return ConditionsBuilder::create(MethodsEnum::PUT);
38 | }
39 |
40 | public static function optionsRequest(): ConditionsBuilder
41 | {
42 | return ConditionsBuilder::create(MethodsEnum::OPTIONS);
43 | }
44 |
45 | public static function headRequest(): ConditionsBuilder
46 | {
47 | return ConditionsBuilder::create(MethodsEnum::HEAD);
48 | }
49 |
50 | public static function fetchRequest(): ConditionsBuilder
51 | {
52 | return ConditionsBuilder::create(MethodsEnum::FETCH);
53 | }
54 |
55 | public static function deleteRequest(): ConditionsBuilder
56 | {
57 | return ConditionsBuilder::create(MethodsEnum::DELETE);
58 | }
59 |
60 | public static function patchRequest(): ConditionsBuilder
61 | {
62 | return ConditionsBuilder::create(MethodsEnum::PATCH);
63 | }
64 |
65 | public static function linkRequest(): ConditionsBuilder
66 | {
67 | return ConditionsBuilder::create(MethodsEnum::LINK);
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/src/Utils/ConditionsBuilder.php:
--------------------------------------------------------------------------------
1 | .
17 | */
18 |
19 | namespace Mcustiel\Phiremock\Client\Utils;
20 |
21 | use Mcustiel\Phiremock\Domain\Condition\Conditions\BinaryBodyCondition;
22 | use Mcustiel\Phiremock\Domain\Condition\Conditions\BodyCondition;
23 | use Mcustiel\Phiremock\Domain\Condition\Conditions\FormDataCondition;
24 | use Mcustiel\Phiremock\Domain\Condition\Conditions\FormFieldCondition;
25 | use Mcustiel\Phiremock\Domain\Condition\Conditions\HeaderCondition;
26 | use Mcustiel\Phiremock\Domain\Condition\Conditions\HeaderConditionCollection;
27 | use Mcustiel\Phiremock\Domain\Condition\Conditions\MethodCondition;
28 | use Mcustiel\Phiremock\Domain\Condition\Conditions\UrlCondition;
29 | use Mcustiel\Phiremock\Domain\Condition\Matchers\Equals;
30 | use Mcustiel\Phiremock\Domain\Condition\Matchers\Matcher;
31 | use Mcustiel\Phiremock\Domain\Condition\Matchers\MatcherFactory;
32 | use Mcustiel\Phiremock\Domain\Conditions as RequestConditions;
33 | use Mcustiel\Phiremock\Domain\Http\FormFieldName;
34 | use Mcustiel\Phiremock\Domain\Http\HeaderName;
35 | use Mcustiel\Phiremock\Domain\Options\ScenarioName;
36 | use Mcustiel\Phiremock\Domain\Options\ScenarioState;
37 |
38 | class ConditionsBuilder
39 | {
40 | /** @var MethodCondition */
41 | private $methodCondition;
42 | /** @var UrlCondition */
43 | private $urlCondition;
44 | /** @var BodyCondition */
45 | private $bodyCondition;
46 | /** @var HeaderConditionCollection */
47 | private $headersConditions;
48 | /** @var ScenarioName */
49 | private $scenarioName;
50 | /** @var ScenarioState */
51 | private $scenarioIs;
52 | /** @var FormDataCondition */
53 | private $formData;
54 |
55 | public function __construct(?MethodCondition $methodCondition = null, ?UrlCondition $urlCondition = null)
56 | {
57 | $this->headersConditions = new HeaderConditionCollection();
58 | $this->formData = new FormDataCondition();
59 | $this->methodCondition = $methodCondition;
60 | $this->urlCondition = $urlCondition;
61 | }
62 |
63 | public static function create(?string $method = null, ?string $url = null): self
64 | {
65 | return new static(
66 | $method === null ? null : new MethodCondition(MatcherFactory::sameString($method)),
67 | $url === null ? null : new UrlCondition(MatcherFactory::equalsTo($url))
68 | );
69 | }
70 |
71 | public function andMethod(Matcher $matcher): self
72 | {
73 | if ($matcher instanceof Equals) {
74 | $matcher = MatcherFactory::sameString($matcher->getCheckValue()->get());
75 | }
76 | $this->methodCondition = new MethodCondition($matcher);
77 |
78 | return $this;
79 | }
80 |
81 | public function andBody(Matcher $matcher): self
82 | {
83 | $this->bodyCondition = new BodyCondition($matcher);
84 |
85 | return $this;
86 | }
87 |
88 | public function andBinaryBody(Matcher $matcher): self
89 | {
90 | $this->bodyCondition = new BinaryBodyCondition($matcher);
91 |
92 | return $this;
93 | }
94 |
95 | public function andHeader(string $header, Matcher $matcher): self
96 | {
97 | $this->headersConditions->setHeaderCondition(
98 | new HeaderName($header),
99 | new HeaderCondition($matcher)
100 | );
101 |
102 | return $this;
103 | }
104 |
105 | public function andFormField(string $fieldName, Matcher $matcher): self
106 | {
107 | $this->formData->setFieldCondition(
108 | new FormFieldName($fieldName),
109 | new FormFieldCondition($matcher)
110 | );
111 |
112 | return $this;
113 | }
114 |
115 | public function andUrl(Matcher $matcher): self
116 | {
117 | $this->urlCondition = new UrlCondition($matcher);
118 |
119 | return $this;
120 | }
121 |
122 | public function andScenarioState(string $scenario, string $scenarioState): self
123 | {
124 | $this->scenarioName = new ScenarioName($scenario);
125 | $this->scenarioIs = new ScenarioState($scenarioState);
126 |
127 | return $this;
128 | }
129 |
130 | public function build(): ConditionsBuilderResult
131 | {
132 | return new ConditionsBuilderResult(
133 | new RequestConditions(
134 | $this->methodCondition,
135 | $this->urlCondition,
136 | $this->bodyCondition,
137 | $this->headersConditions->iterator(),
138 | $this->formData->iterator(),
139 | $this->scenarioIs
140 | ),
141 | $this->scenarioName
142 | );
143 | }
144 | }
145 |
--------------------------------------------------------------------------------
/src/Utils/ConditionsBuilderResult.php:
--------------------------------------------------------------------------------
1 | .
17 | */
18 |
19 | namespace Mcustiel\Phiremock\Client\Utils;
20 |
21 | use Mcustiel\Phiremock\Domain\Conditions as RequestConditions;
22 | use Mcustiel\Phiremock\Domain\Options\ScenarioName;
23 |
24 | class ConditionsBuilderResult
25 | {
26 | /** @var RequestConditions */
27 | private $request;
28 | /** @var ScenarioName|null */
29 | private $scenarioName;
30 |
31 | public function __construct(
32 | RequestConditions $request,
33 | ?ScenarioName $scenarioName = null
34 | ) {
35 | $this->request = $request;
36 | $this->scenarioName = $scenarioName;
37 | }
38 |
39 | public function getRequestConditions(): RequestConditions
40 | {
41 | return $this->request;
42 | }
43 |
44 | public function getScenarioName(): ?ScenarioName
45 | {
46 | return $this->scenarioName;
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/Utils/ExpectationBuilder.php:
--------------------------------------------------------------------------------
1 | .
17 | */
18 |
19 | namespace Mcustiel\Phiremock\Client\Utils;
20 |
21 | use Mcustiel\Phiremock\Domain\Expectation;
22 | use Mcustiel\Phiremock\Domain\Response;
23 | use Mcustiel\Phiremock\Domain\Version;
24 |
25 | class ExpectationBuilder
26 | {
27 | /** @var ConditionsBuilder */
28 | private $requestBuilder;
29 |
30 | public function __construct(ConditionsBuilder $requestBuilder)
31 | {
32 | $this->requestBuilder = $requestBuilder;
33 | }
34 |
35 | public function then(ResponseBuilder $responseBuilder): Expectation
36 | {
37 | return $this->createExpectation($responseBuilder->build());
38 | }
39 |
40 | public function thenRespond(int $statusCode, string $body): Expectation
41 | {
42 | $response = HttpResponseBuilder::create($statusCode)
43 | ->andBody($body)
44 | ->build();
45 |
46 | return $this->createExpectation($response);
47 | }
48 |
49 | private function createExpectation(Response $response): Expectation
50 | {
51 | $requestOptions = $this->requestBuilder->build();
52 |
53 | return new Expectation(
54 | $requestOptions->getRequestConditions(),
55 | $response,
56 | $requestOptions->getScenarioName(),
57 | null,
58 | new Version('2')
59 | );
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/src/Utils/Http/GuzzlePsr18Client.php:
--------------------------------------------------------------------------------
1 | .
18 | */
19 |
20 | namespace Mcustiel\Phiremock\Client\Utils\Http;
21 |
22 | use GuzzleHttp\Client as GuzzleClient;
23 | use GuzzleHttp\Exception\GuzzleException;
24 | use Psr\Http\Client\ClientInterface;
25 | use Psr\Http\Message\RequestInterface;
26 | use Psr\Http\Message\ResponseInterface;
27 |
28 | class GuzzlePsr18Client implements ClientInterface
29 | {
30 | /** @var GuzzleClient */
31 | private $client;
32 |
33 | public function __construct(?GuzzleClient $client = null)
34 | {
35 | $this->client = $client ?? new GuzzleClient(
36 | [
37 | 'http_errors' => false,
38 | 'allow_redirects' => true,
39 | 'verify' => false,
40 | ]
41 | );
42 | }
43 |
44 | /** @throws GuzzleException */
45 | public function sendRequest(RequestInterface $request): ResponseInterface
46 | {
47 | return $this->client->send($request);
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/Utils/HttpResponseBuilder.php:
--------------------------------------------------------------------------------
1 | .
17 | */
18 |
19 | namespace Mcustiel\Phiremock\Client\Utils;
20 |
21 | use Mcustiel\Phiremock\Domain\Http\BinaryBody;
22 | use Mcustiel\Phiremock\Domain\Http\Body;
23 | use Mcustiel\Phiremock\Domain\Http\Header;
24 | use Mcustiel\Phiremock\Domain\Http\HeaderName;
25 | use Mcustiel\Phiremock\Domain\Http\HeadersCollection;
26 | use Mcustiel\Phiremock\Domain\Http\HeaderValue;
27 | use Mcustiel\Phiremock\Domain\Http\StatusCode;
28 | use Mcustiel\Phiremock\Domain\HttpResponse;
29 | use Mcustiel\Phiremock\Domain\Response;
30 |
31 | class HttpResponseBuilder extends ResponseBuilder
32 | {
33 | /** @var StatusCode */
34 | private $statusCode;
35 |
36 | /** @var Body */
37 | private $body;
38 |
39 | /** @var HeadersCollection */
40 | private $headers;
41 |
42 | public function __construct(StatusCode $statusCode)
43 | {
44 | $this->headers = new HeadersCollection();
45 | $this->statusCode = $statusCode;
46 | $this->body = Body::createEmpty();
47 | }
48 |
49 | public static function create(int $statusCode): HttpResponseBuilder
50 | {
51 | return new static(new StatusCode($statusCode));
52 | }
53 |
54 | public function andBody(string $body): HttpResponseBuilder
55 | {
56 | $this->body = new Body($body);
57 |
58 | return $this;
59 | }
60 |
61 | public function andBinaryBody(string $body): HttpResponseBuilder
62 | {
63 | $this->body = new BinaryBody($body);
64 |
65 | return $this;
66 | }
67 |
68 | public function andHeader(string $header, string $value): HttpResponseBuilder
69 | {
70 | $this->headers->setHeader(
71 | new Header(new HeaderName($header), new HeaderValue($value))
72 | );
73 |
74 | return $this;
75 | }
76 |
77 | /** @return Response|HttpResponse */
78 | public function build(): Response
79 | {
80 | $response = parent::build();
81 |
82 | return new HttpResponse(
83 | $this->statusCode,
84 | $this->body,
85 | $this->headers,
86 | $response->getDelayMillis(),
87 | $response->getNewScenarioState()
88 | );
89 | }
90 | }
91 |
--------------------------------------------------------------------------------
/src/Utils/Is.php:
--------------------------------------------------------------------------------
1 | .
17 | */
18 |
19 | namespace Mcustiel\Phiremock\Client\Utils;
20 |
21 | use Mcustiel\Phiremock\Domain\Condition\Matchers\CaseInsensitiveEquals;
22 | use Mcustiel\Phiremock\Domain\Condition\Matchers\Contains;
23 | use Mcustiel\Phiremock\Domain\Condition\Matchers\Equals;
24 | use Mcustiel\Phiremock\Domain\Condition\Matchers\JsonEquals;
25 | use Mcustiel\Phiremock\Domain\Condition\Matchers\MatcherFactory;
26 | use Mcustiel\Phiremock\Domain\Condition\Matchers\RegExp;
27 |
28 | class Is
29 | {
30 | public static function equalTo($value): Equals
31 | {
32 | return MatcherFactory::equalsTo($value);
33 | }
34 |
35 | public static function matching($value): RegExp
36 | {
37 | return MatcherFactory::matches($value);
38 | }
39 |
40 | public static function sameStringAs($value): CaseInsensitiveEquals
41 | {
42 | return MatcherFactory::sameString($value);
43 | }
44 |
45 | public static function containing($value): Contains
46 | {
47 | return MatcherFactory::contains($value);
48 | }
49 |
50 | public static function sameJsonObjectAs($value): JsonEquals
51 | {
52 | if (is_string($value)) {
53 | return MatcherFactory::jsonEquals($value);
54 | }
55 |
56 | return MatcherFactory::jsonEquals(json_encode($value, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT | JSON_PRESERVE_ZERO_FRACTION));
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/src/Utils/Proxy.php:
--------------------------------------------------------------------------------
1 | .
17 | */
18 |
19 | namespace Mcustiel\Phiremock\Client\Utils;
20 |
21 | use Mcustiel\Phiremock\Domain\Http\Uri;
22 |
23 | class Proxy
24 | {
25 | public static function to(string $url): ProxyResponseBuilder
26 | {
27 | return new ProxyResponseBuilder(new Uri($url));
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/Utils/ProxyResponseBuilder.php:
--------------------------------------------------------------------------------
1 | .
17 | */
18 |
19 | namespace Mcustiel\Phiremock\Client\Utils;
20 |
21 | use Mcustiel\Phiremock\Domain\Http\Uri;
22 | use Mcustiel\Phiremock\Domain\ProxyResponse;
23 | use Mcustiel\Phiremock\Domain\Response;
24 |
25 | class ProxyResponseBuilder extends ResponseBuilder
26 | {
27 | /** @var Uri */
28 | private $uri;
29 |
30 | public function __construct(Uri $uri)
31 | {
32 | $this->uri = $uri;
33 | }
34 |
35 | /** @return Response|ProxyResponse */
36 | public function build(): Response
37 | {
38 | $response = parent::build();
39 |
40 | return new ProxyResponse(
41 | $this->uri,
42 | $response->getDelayMillis(),
43 | $response->getNewScenarioState()
44 | );
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/Utils/Respond.php:
--------------------------------------------------------------------------------
1 | .
17 | */
18 |
19 | namespace Mcustiel\Phiremock\Client\Utils;
20 |
21 | class Respond
22 | {
23 | public static function withStatusCode(int $status): HttpResponseBuilder
24 | {
25 | return HttpResponseBuilder::create($status);
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/Utils/ResponseBuilder.php:
--------------------------------------------------------------------------------
1 | .
17 | */
18 |
19 | namespace Mcustiel\Phiremock\Client\Utils;
20 |
21 | use Mcustiel\Phiremock\Domain\Options\Delay;
22 | use Mcustiel\Phiremock\Domain\Options\ScenarioState;
23 | use Mcustiel\Phiremock\Domain\Response;
24 |
25 | abstract class ResponseBuilder
26 | {
27 | /** @var ScenarioState */
28 | private $newScenarioState;
29 | /** @var Delay */
30 | private $delay;
31 |
32 | public function andSetScenarioStateTo(string $scenarioState): ResponseBuilder
33 | {
34 | $this->newScenarioState = new ScenarioState($scenarioState);
35 |
36 | return $this;
37 | }
38 |
39 | public function andDelayInMillis(int $delay): ResponseBuilder
40 | {
41 | $this->delay = new Delay($delay);
42 |
43 | return $this;
44 | }
45 |
46 | /** @return Response */
47 | public function build(): Response
48 | {
49 | return new Response(
50 | $this->delay,
51 | $this->newScenarioState
52 | );
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/src/helper_functions.php:
--------------------------------------------------------------------------------
1 | .
17 | */
18 |
19 | namespace Mcustiel\Phiremock\Client;
20 |
21 | use Mcustiel\Phiremock\Client\Utils\A;
22 | use Mcustiel\Phiremock\Client\Utils\ConditionsBuilder;
23 | use Mcustiel\Phiremock\Client\Utils\ExpectationBuilder;
24 | use Mcustiel\Phiremock\Client\Utils\HttpResponseBuilder;
25 | use Mcustiel\Phiremock\Client\Utils\Is;
26 | use Mcustiel\Phiremock\Client\Utils\Proxy;
27 | use Mcustiel\Phiremock\Client\Utils\ProxyResponseBuilder;
28 | use Mcustiel\Phiremock\Client\Utils\Respond;
29 | use Mcustiel\Phiremock\Domain\Condition\Matchers\CaseInsensitiveEquals;
30 | use Mcustiel\Phiremock\Domain\Condition\Matchers\Contains;
31 | use Mcustiel\Phiremock\Domain\Condition\Matchers\Equals;
32 | use Mcustiel\Phiremock\Domain\Condition\Matchers\JsonEquals;
33 | use Mcustiel\Phiremock\Domain\Condition\Matchers\RegExp;
34 |
35 | // ConditionBuilder creators
36 |
37 | function request(): ConditionsBuilder
38 | {
39 | return new ConditionsBuilder();
40 | }
41 |
42 | function getRequest(?string $url = null): ConditionsBuilder
43 | {
44 | $builder = A::getRequest();
45 | if ($url) {
46 | $builder->andUrl(isEqualTo($url));
47 | }
48 | return $builder;
49 | }
50 |
51 | function postRequest(): ConditionsBuilder
52 | {
53 | return A::postRequest();
54 | }
55 |
56 | function putRequest(): ConditionsBuilder
57 | {
58 | return A::putRequest();
59 | }
60 |
61 | function deleteRequest(?string $url = null): ConditionsBuilder
62 | {
63 | $builder = A::deleteRequest();
64 | if ($url) {
65 | $builder->andUrl(isEqualTo($url));
66 | }
67 | return $builder;
68 | }
69 |
70 | function patchRequest(): ConditionsBuilder
71 | {
72 | return A::patchRequest();
73 | }
74 |
75 | function headRequest(): ConditionsBuilder
76 | {
77 | return A::headRequest();
78 | }
79 |
80 | function optionsRequest(): ConditionsBuilder
81 | {
82 | return A::optionsRequest();
83 | }
84 |
85 | function fetchRequest(): ConditionsBuilder
86 | {
87 | return A::fetchRequest();
88 | }
89 |
90 | function linkRequest(): ConditionsBuilder
91 | {
92 | return A::linkRequest();
93 | }
94 |
95 | // Matcher creators
96 |
97 | function isEqualTo($value): Equals
98 | {
99 | return Is::equalTo($value);
100 | }
101 |
102 | function isSameStringAs(string $value): CaseInsensitiveEquals
103 | {
104 | return Is::sameStringAs($value);
105 | }
106 |
107 | function matchesRegex(string $value): RegExp
108 | {
109 | return Is::matching($value);
110 | }
111 |
112 | function isSameJsonAs($value): JsonEquals
113 | {
114 | return Is::sameJsonObjectAs($value);
115 | }
116 |
117 | function contains(string $value): Contains
118 | {
119 | return Is::containing($value);
120 | }
121 |
122 | // ResponseBuilder creators
123 |
124 | function respond(int $statusCode): HttpResponseBuilder
125 | {
126 | return Respond::withStatusCode($statusCode);
127 | }
128 |
129 | function proxyTo(string $url): ProxyResponseBuilder
130 | {
131 | return Proxy::to($url);
132 | }
133 |
134 | // ExpectationBuilder creator
135 |
136 | function on(ConditionsBuilder $builder): ExpectationBuilder
137 | {
138 | return Phiremock::on($builder);
139 | }
140 |
141 | function onGetRequest(?string $url = null): ExpectationBuilder
142 | {
143 | return Phiremock::on(getRequest($url));
144 | }
145 |
146 | function onDeleteRequest(?string $url = null): ExpectationBuilder
147 | {
148 | return Phiremock::on(deleteRequest($url));
149 | }
150 |
--------------------------------------------------------------------------------
/tests/acceptance/_data/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
3 |
--------------------------------------------------------------------------------
/tests/acceptance/_output/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/tests/acceptance/_support/ApiTester.php:
--------------------------------------------------------------------------------
1 | .
18 | */
19 |
20 | namespace Helper;
21 |
22 | // here you can define custom actions
23 | // all public methods declared in helper class will be available in $I
24 |
25 | class Api extends \Codeception\Module
26 | {
27 | }
28 |
--------------------------------------------------------------------------------
/tests/acceptance/_support/_generated/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/tests/acceptance/api.suite.yml:
--------------------------------------------------------------------------------
1 | actor: ApiTester
2 | modules:
3 | enabled:
4 | - \Helper\Api
5 | - Asserts
6 | - REST
7 | - \Mcustiel\Codeception\Modules\PhiremockClient
8 | config:
9 | REST:
10 | depends: PhpBrowser
11 | url: 'http://localhost:8086'
12 | \Mcustiel\Codeception\Modules\PhiremockClient:
13 | https: false
14 | env:
15 | https:
16 | modules:
17 | config:
18 | REST:
19 | url: 'https://localhost:8086'
20 | \Mcustiel\Codeception\Modules\PhiremockClient:
21 | https: true
22 |
--------------------------------------------------------------------------------
/tests/acceptance/api/ClearExpectationsCest.php:
--------------------------------------------------------------------------------
1 | .
18 | */
19 |
20 | namespace Mcustiel\Phiremock\Client\Tests\Acceptance;
21 |
22 | use ApiTester;
23 | use function Mcustiel\Phiremock\Client\getRequest;
24 | use Mcustiel\Phiremock\Client\Phiremock;
25 | use function Mcustiel\Phiremock\Client\respond;
26 |
27 | class ClearExpectationsCest
28 | {
29 | use PhiremockApiTestHelper;
30 |
31 | public function clearsExpectations(ApiTester $I)
32 | {
33 | $expectations = $this->_getPhiremockClient()->listExpectations();
34 | $I->assertEmpty($expectations);
35 | $this->_getPhiremockClient()->createExpectation(
36 | Phiremock::on(
37 | getRequest()
38 | )->then(
39 | respond(418)
40 | )
41 | );
42 |
43 | $expectations = $this->_getPhiremockClient()->listExpectations();
44 | $I->assertCount(1, $expectations);
45 | $this->_getPhiremockClient()->clearExpectations();
46 | $expectations = $this->_getPhiremockClient()->listExpectations();
47 | $I->assertEmpty($expectations);
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/tests/acceptance/api/CountExecutionsCest.php:
--------------------------------------------------------------------------------
1 | .
18 | */
19 |
20 | namespace Mcustiel\Phiremock\Client\Tests\Acceptance;
21 |
22 | use ApiTester;
23 | use function Mcustiel\Phiremock\Client\getRequest;
24 | use function Mcustiel\Phiremock\Client\postRequest;
25 |
26 | class CountExecutionsCest
27 | {
28 | use PhiremockApiTestHelper;
29 |
30 | public function countsRequestsBasedInDefinition(ApiTester $I)
31 | {
32 | $I->assertSame(0, $this->_getPhiremockClient()->countExecutions(getRequest()));
33 | $I->sendGet('/tomato');
34 | $I->assertSame(1, $this->_getPhiremockClient()->countExecutions(getRequest()));
35 | $I->assertSame(0, $this->_getPhiremockClient()->countExecutions(postRequest()));
36 | }
37 |
38 | public function countsAllRequests(ApiTester $I)
39 | {
40 | $I->assertSame(0, $this->_getPhiremockClient()->countExecutions());
41 | $I->sendGet('/tomato');
42 | $I->sendPost('/potato', ['banana' => 'coconut']);
43 | $I->assertSame(1, $this->_getPhiremockClient()->countExecutions(getRequest()));
44 | $I->assertSame(1, $this->_getPhiremockClient()->countExecutions(postRequest()));
45 | $I->assertSame(2, $this->_getPhiremockClient()->countExecutions());
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/tests/acceptance/api/ExpectationCreationCest.php:
--------------------------------------------------------------------------------
1 | .
18 | */
19 |
20 | namespace Mcustiel\Phiremock\Client\Tests\Acceptance;
21 |
22 | use ApiTester;
23 | use function Mcustiel\Phiremock\Client\contains;
24 | use function Mcustiel\Phiremock\Client\getRequest;
25 | use function Mcustiel\Phiremock\Client\isEqualTo;
26 | use function Mcustiel\Phiremock\Client\on;
27 | use Mcustiel\Phiremock\Client\Phiremock;
28 | use function Mcustiel\Phiremock\Client\request;
29 | use function Mcustiel\Phiremock\Client\respond as frespond;
30 | use Mcustiel\Phiremock\Client\Utils\A;
31 | use Mcustiel\Phiremock\Client\Utils\Is;
32 | use Mcustiel\Phiremock\Client\Utils\Respond;
33 | use Mcustiel\Phiremock\Domain\Condition\MatchersEnum;
34 | use Mcustiel\Phiremock\Domain\Expectation;
35 | use Mcustiel\Phiremock\Domain\Http\MethodsEnum;
36 | use Mcustiel\Phiremock\Client\Utils\ConditionsBuilder;
37 | use function Mcustiel\Phiremock\Client\postRequest;
38 | use function Mcustiel\Phiremock\Client\isSameJsonAs;
39 |
40 | class ExpectationCreationCest
41 | {
42 | use PhiremockApiTestHelper;
43 |
44 | public function createsExpectationUsingHelperClasses(ApiTester $I)
45 | {
46 | $this->_getPhiremockClient()->createExpectation(
47 | Phiremock::on(
48 | A::getRequest()
49 | ->andUrl(Is::equalTo('/potato/tomato'))
50 | ->andBody(Is::containing('42'))
51 | ->andHeader('Accept', Is::equalTo('application/banana'))
52 | ->andFormField('name', Is::equalTo('potato'))
53 | )->then(
54 | Respond::withStatusCode(418)
55 | ->andBody('Is the answer to the Ultimate Question of Life, The Universe, and Everything')
56 | ->andHeader('Content-Type', 'application/banana')
57 | )
58 | );
59 | $expectations = $this->_getPhiremockClient()->listExpectations();
60 | $this->assertExpectationWasCorrectlyCreated($I, $expectations);
61 | }
62 |
63 | public function createsExpectationUsingHelperFunctions(ApiTester $I)
64 | {
65 | $this->_getPhiremockClient()->createExpectation(
66 | on(
67 | getRequest()
68 | ->andUrl(isEqualTo('/potato/tomato'))
69 | ->andBody(contains('42'))
70 | ->andHeader('Accept', isEqualTo('application/banana'))
71 | ->andFormField('name', isEqualTo('potato'))
72 | )->then(
73 | frespond(418)
74 | ->andBody('Is the answer to the Ultimate Question of Life, The Universe, and Everything')
75 | ->andHeader('Content-Type', 'application/banana')
76 | )
77 | );
78 |
79 | $expectations = $this->_getPhiremockClient()->listExpectations();
80 | $this->assertExpectationWasCorrectlyCreated($I, $expectations);
81 | }
82 |
83 | public function createsExpectationUsingShortcuts(\ApiTester $I)
84 | {
85 | $this->_getPhiremockClient()->createExpectation(
86 | Phiremock::onRequest(MethodsEnum::GET, '/potato/tomato')
87 | ->thenRespond(418, 'Is the answer to the Ultimate Question of Life, The Universe, and Everything')
88 | );
89 | $expectations = $this->_getPhiremockClient()->listExpectations();
90 | $I->assertCount(1, $expectations);
91 | $expectation = $expectations[0];
92 | $I->assertSame('2', $expectation->getVersion()->asString());
93 | $I->assertTrue($expectation->getRequest()->hasMethod());
94 | $I->assertSame(MatchersEnum::SAME_STRING, $expectation->getRequest()->getMethod()->getMatcher()->getName());
95 | $I->assertSame(MethodsEnum::GET, $expectation->getRequest()->getMethod()->getMatcher()->getCheckValue()->get());
96 | $I->assertTrue($expectation->getRequest()->hasUrl());
97 | $I->assertSame(MatchersEnum::EQUAL_TO, $expectation->getRequest()->getUrl()->getMatcher()->getName());
98 | $I->assertSame('/potato/tomato', $expectation->getRequest()->getUrl()->getMatcher()->getCheckValue()->get());
99 |
100 | /** @var \Mcustiel\Phiremock\Domain\HttpResponse $response */
101 | $response = $expectation->getResponse();
102 | $I->assertSame(418, $response->getStatusCode()->asInt());
103 | $I->assertSame('Is the answer to the Ultimate Question of Life, The Universe, and Everything', $response->getBody()->asString());
104 | }
105 |
106 | public function keepsFloatType(\ApiTester $I)
107 | {
108 | $this->_getPhiremockClient()->createExpectation(
109 | Phiremock::on(
110 | postRequest()->andUrl(isEqualTo('/some/path'))
111 | ->andBody(isSameJsonAs(['whatIs' => 42.0]))
112 | )->thenRespond(418, 'Is the answer to the Ultimate Question of Life, The Universe, and Everything')
113 | );
114 |
115 | $I->sendPost('/some/path', ['whatIs' => 42]);
116 | $I->seeResponseCodeIs(404);
117 | $I->sendPost('/some/path', json_encode(['whatIs' => 42.0], JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT | JSON_PRESERVE_ZERO_FRACTION));
118 | $I->seeResponseCodeIs(418);
119 | }
120 |
121 | public function createsCatchAllExpectation(\ApiTester $I)
122 | {
123 | $this->_getPhiremockClient()->createExpectation(
124 | Phiremock::on(request())->thenRespond(418, 'Is the answer to the Ultimate Question of Life, The Universe, and Everything')
125 | );
126 | $expectations = $this->_getPhiremockClient()->listExpectations();
127 | $I->assertCount(1, $expectations);
128 | $expectation = $expectations[0];
129 | $I->assertSame('2', $expectation->getVersion()->asString());
130 | $I->assertFalse($expectation->getRequest()->hasMethod());
131 | $I->assertFalse($expectation->getRequest()->hasUrl());
132 | $I->assertFalse($expectation->getRequest()->hasBody());
133 | $I->assertFalse($expectation->getRequest()->hasHeaders());
134 |
135 | /** @var \Mcustiel\Phiremock\Domain\HttpResponse $response */
136 | $response = $expectation->getResponse();
137 | $I->assertSame(418, $response->getStatusCode()->asInt());
138 | $I->assertSame('Is the answer to the Ultimate Question of Life, The Universe, and Everything', $response->getBody()->asString());
139 |
140 | $I->sendPOST('/does/not/matter');
141 | $I->seeResponseCodeIs(418);
142 | $I->seeResponseEquals('Is the answer to the Ultimate Question of Life, The Universe, and Everything');
143 |
144 | $I->sendGET('/potato');
145 | $I->seeResponseCodeIs(418);
146 | $I->seeResponseEquals('Is the answer to the Ultimate Question of Life, The Universe, and Everything');
147 | }
148 |
149 | private function assertExpectationWasCorrectlyCreated(ApiTester $I, array $expectations)
150 | {
151 | $I->assertCount(1, $expectations);
152 | /** @var Expectation $expectation */
153 | $expectation = $expectations[0];
154 | $I->assertSame('2', $expectation->getVersion()->asString());
155 | $I->assertTrue($expectation->getRequest()->hasMethod());
156 | $I->assertSame(MatchersEnum::SAME_STRING, $expectation->getRequest()->getMethod()->getMatcher()->getName());
157 | $I->assertSame(MethodsEnum::GET, $expectation->getRequest()->getMethod()->getMatcher()->getCheckValue()->get());
158 | $I->assertTrue($expectation->getRequest()->hasUrl());
159 | $I->assertSame(MatchersEnum::EQUAL_TO, $expectation->getRequest()->getUrl()->getMatcher()->getName());
160 | $I->assertSame('/potato/tomato', $expectation->getRequest()->getUrl()->getMatcher()->getCheckValue()->get());
161 | $I->assertTrue($expectation->getRequest()->hasBody());
162 | $I->assertSame(MatchersEnum::CONTAINS, $expectation->getRequest()->getBody()->getMatcher()->getName());
163 | $I->assertSame('42', $expectation->getRequest()->getBody()->getMatcher()->getCheckValue()->get());
164 | $I->assertGreaterThan(0, $expectation->getRequest()->getHeaders()->count());
165 | $I->assertSame('Accept', $expectation->getRequest()->getHeaders()->key()->asString());
166 | $I->assertSame(MatchersEnum::EQUAL_TO, $expectation->getRequest()->getHeaders()->current()->getMatcher()->getName());
167 | $I->assertSame('application/banana', $expectation->getRequest()->getHeaders()->current()->getValue()->get());
168 |
169 | $I->assertGreaterThan(0, $expectation->getRequest()->getFormFields()->count());
170 | $I->assertSame('name', $expectation->getRequest()->getFormFields()->key()->asString());
171 | $I->assertSame(MatchersEnum::EQUAL_TO, $expectation->getRequest()->getFormFields()->current()->getMatcher()->getName());
172 | $I->assertSame('potato', $expectation->getRequest()->getFormFields()->current()->getValue()->get());
173 |
174 | /** @var \Mcustiel\Phiremock\Domain\HttpResponse $response */
175 | $response = $expectation->getResponse();
176 | $I->assertSame(418, $response->getStatusCode()->asInt());
177 | $I->assertSame('Is the answer to the Ultimate Question of Life, The Universe, and Everything', $response->getBody()->asString());
178 | $I->assertSame('Content-Type', $response->getHeaders()->current()->getName()->asString());
179 | $I->assertSame('application/banana', $response->getHeaders()->current()->getValue()->asString());
180 | }
181 | }
182 |
--------------------------------------------------------------------------------
/tests/acceptance/api/ListExecutionsCest.php:
--------------------------------------------------------------------------------
1 | .
18 | */
19 |
20 | namespace Mcustiel\Phiremock\Client\Tests\Acceptance;
21 |
22 | use ApiTester;
23 | use function Mcustiel\Phiremock\Client\getRequest;
24 | use function Mcustiel\Phiremock\Client\postRequest;
25 |
26 | class ListExecutionsCest
27 | {
28 | use PhiremockApiTestHelper;
29 |
30 | public function listsRequestsBasedInDefinition(ApiTester $I)
31 | {
32 | $I->assertEmpty($this->_getPhiremockClient()->listExecutions(getRequest()));
33 | $I->sendGet('/tomato');
34 | $requests = $this->_getPhiremockClient()->listExecutions(getRequest());
35 | $I->assertCount(1, $requests);
36 | $I->assertEquals(
37 | [
38 | (object) [
39 | 'method' => 'GET',
40 | 'url' => $I->getPhiremockScheme() . '://localhost:8086/tomato',
41 | 'headers' => (object) [
42 | 'Host' => [
43 | 'localhost:8086',
44 | ],
45 | 'User-Agent' => [
46 | 'Symfony BrowserKit',
47 | ]
48 | ],
49 | 'cookies' => [],
50 | 'body' => '',
51 | ],
52 | ],
53 | $requests
54 | );
55 | $I->assertEmpty($this->_getPhiremockClient()->listExecutions(postRequest()));
56 | }
57 |
58 | public function countsAllRequests(ApiTester $I)
59 | {
60 | $expectedGetRequest = (object) [
61 | 'method' => 'GET',
62 | 'url' => $I->getPhiremockScheme() . '://localhost:8086/tomato',
63 | 'headers' => (object) [
64 | 'Host' => [
65 | 'localhost:8086',
66 | ],
67 | 'User-Agent' => [
68 | 'Symfony BrowserKit',
69 | ]
70 | ],
71 | 'cookies' => [],
72 | 'body' => '',
73 | ];
74 | $expectedPostRequest = (object) [
75 | 'method' => 'POST',
76 | 'url' => $I->getPhiremockScheme() . '://localhost:8086/potato',
77 | 'headers' => (object) [
78 | 'Host' => [
79 | 'localhost:8086',
80 | ],
81 | 'User-Agent' => [
82 | 'Symfony BrowserKit',
83 | ],
84 | 'Content-Type' => ['application/json'],
85 | 'Referer' => [$I->getPhiremockScheme() . '://localhost:8086/tomato'],
86 | 'Content-Length' => ['20'],
87 | ],
88 | 'cookies' => [],
89 | 'body' => '{"banana":"coconut"}',
90 | ];
91 |
92 | $I->assertEmpty($this->_getPhiremockClient()->listExecutions());
93 | $I->sendGet('/tomato');
94 | $I->haveHttpHeader('Content-Type', 'application/json');
95 | $I->sendPost('/potato', ['banana' => 'coconut']);
96 |
97 | $requests = $this->_getPhiremockClient()->listExecutions(getRequest());
98 | $I->assertCount(1, $requests);
99 | $I->assertEquals([$expectedGetRequest], $requests);
100 |
101 | $requests = $this->_getPhiremockClient()->listExecutions(postRequest());
102 | $I->assertCount(1, $requests);
103 | $I->assertEquals([$expectedPostRequest], $requests);
104 |
105 | $requests = $this->_getPhiremockClient()->listExecutions();
106 | $I->assertCount(2, $requests);
107 | $I->assertEquals([$expectedGetRequest, $expectedPostRequest], $requests);
108 | }
109 | }
110 |
--------------------------------------------------------------------------------
/tests/acceptance/api/ListExpectationsCest.php:
--------------------------------------------------------------------------------
1 | .
18 | */
19 |
20 | namespace Mcustiel\Phiremock\Client\Tests\Acceptance;
21 |
22 | use ApiTester;
23 | use function Mcustiel\Phiremock\Client\getRequest;
24 | use Mcustiel\Phiremock\Client\Phiremock;
25 | use function Mcustiel\Phiremock\Client\respond;
26 | use Mcustiel\Phiremock\Domain\Http\MethodsEnum;
27 |
28 | class ListExpectationsCest
29 | {
30 | use PhiremockApiTestHelper;
31 |
32 | public function noExpectationsReturnsEmptyList(ApiTester $I)
33 | {
34 | $expectations = $this->_getPhiremockClient()->listExpectations();
35 | $I->assertEmpty($expectations);
36 | }
37 |
38 | public function retrievesNotEmptyExpectationsList(ApiTester $I)
39 | {
40 | $this->_getPhiremockClient()->createExpectation(
41 | Phiremock::on(
42 | getRequest()
43 | )->then(
44 | respond(418)
45 | )
46 | );
47 | $expectations = $this->_getPhiremockClient()->listExpectations();
48 | $I->assertCount(1, $expectations);
49 | $expectation = $expectations[0];
50 | $I->assertSame(MethodsEnum::GET, $expectation->getRequest()->getMethod()->getValue()->get());
51 | /** @var \Mcustiel\Phiremock\Domain\HttpResponse $response */
52 | $response = $expectation->getResponse();
53 | $I->assertSame(418, $response->getStatusCode()->asInt());
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/tests/acceptance/api/PhiremockApiTestHelper.php:
--------------------------------------------------------------------------------
1 | .
18 | */
19 |
20 | namespace Mcustiel\Phiremock\Client\Tests\Acceptance;
21 |
22 | use ApiTester;
23 | use Mcustiel\Phiremock\Client\Phiremock;
24 |
25 | trait PhiremockApiTestHelper
26 | {
27 | /** @var Phiremock */
28 | private $phiremock;
29 |
30 | public function _before(ApiTester $I)
31 | {
32 | if ($this->phiremock === null) {
33 | $this->phiremock = $I->getPhiremockClient();
34 | }
35 | $this->phiremock->reset();
36 | }
37 |
38 | public function _getPhiremockClient(): Phiremock
39 | {
40 | return $this->phiremock;
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/tests/acceptance/api/ResetCest.php:
--------------------------------------------------------------------------------
1 | .
18 | */
19 |
20 | namespace Mcustiel\Phiremock\Client\Tests\Acceptance;
21 |
22 | use ApiTester;
23 | use function Mcustiel\Phiremock\Client\getRequest;
24 | use Mcustiel\Phiremock\Client\Phiremock;
25 | use function Mcustiel\Phiremock\Client\respond;
26 |
27 | class ResetCest
28 | {
29 | use PhiremockApiTestHelper;
30 |
31 | public function callingResetRestoresExpectations(ApiTester $I)
32 | {
33 | $expectations = $this->_getPhiremockClient()->listExpectations();
34 | $I->assertEmpty($expectations);
35 | $this->_getPhiremockClient()->createExpectation(
36 | Phiremock::on(
37 | getRequest()
38 | )->then(
39 | respond(418)
40 | )
41 | );
42 |
43 | $expectations = $this->_getPhiremockClient()->listExpectations();
44 | $I->assertCount(1, $expectations);
45 | $this->_getPhiremockClient()->reset();
46 | $expectations = $this->_getPhiremockClient()->listExpectations();
47 | $I->assertEmpty($expectations);
48 | }
49 |
50 | public function callingResetRestoresRequestsCounter(ApiTester $I)
51 | {
52 | $I->assertSame(0, $this->_getPhiremockClient()->countExecutions(getRequest()));
53 | $I->sendGet('/tomato');
54 | $I->assertSame(1, $this->_getPhiremockClient()->countExecutions(getRequest()));
55 | $this->_getPhiremockClient()->reset();
56 | $I->assertSame(0, $this->_getPhiremockClient()->countExecutions(getRequest()));
57 | }
58 |
59 | public function callingResetRestoresRequestsList(ApiTester $I)
60 | {
61 | $I->assertEmpty($this->_getPhiremockClient()->listExecutions(getRequest()));
62 | $I->sendGet('/tomato');
63 | $I->assertCount(1, $this->_getPhiremockClient()->listExecutions(getRequest()));
64 | $this->_getPhiremockClient()->reset();
65 | $I->assertEmpty($this->_getPhiremockClient()->listExecutions(getRequest()));
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/tests/acceptance/api/ResetRequestCounterCest.php:
--------------------------------------------------------------------------------
1 | .
18 | */
19 |
20 | namespace Mcustiel\Phiremock\Client\Tests\Acceptance;
21 |
22 | use ApiTester;
23 | use function Mcustiel\Phiremock\Client\getRequest;
24 | use function Mcustiel\Phiremock\Client\postRequest;
25 |
26 | class ResetRequestCounterCest
27 | {
28 | use PhiremockApiTestHelper;
29 |
30 | public function countsRequestsBasedInDefinition(ApiTester $I)
31 | {
32 | $I->assertSame(0, $this->_getPhiremockClient()->countExecutions(getRequest()));
33 | $I->sendGet('/tomato');
34 | $I->assertSame(1, $this->_getPhiremockClient()->countExecutions(getRequest()));
35 | $I->assertSame(0, $this->_getPhiremockClient()->countExecutions(postRequest()));
36 | $this->_getPhiremockClient()->resetRequestsCounter();
37 | $I->assertSame(0, $this->_getPhiremockClient()->countExecutions(getRequest()));
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/tests/acceptance/api/ResetScenariosCest.php:
--------------------------------------------------------------------------------
1 | .
18 | */
19 |
20 | namespace Mcustiel\Phiremock\Client\Tests\Acceptance;
21 |
22 | use ApiTester;
23 | use function Mcustiel\Phiremock\Client\getRequest;
24 | use function Mcustiel\Phiremock\Client\isEqualTo;
25 | use Mcustiel\Phiremock\Client\Phiremock;
26 | use function Mcustiel\Phiremock\Client\respond;
27 |
28 | class ResetScenariosCest
29 | {
30 | use PhiremockApiTestHelper;
31 |
32 | public function setsScenarioStateCorrectly(ApiTester $I)
33 | {
34 | $this->_getPhiremockClient()->createExpectation(
35 | Phiremock::on(
36 | getRequest()
37 | ->andUrl(isEqualTo('/banana'))
38 | ->andScenarioState('tomatoScenario', 'Scenario.START')
39 | )->then(
40 | respond(204)->andSetScenarioStateTo('potato')
41 | )
42 | );
43 |
44 | $this->_getPhiremockClient()->createExpectation(
45 | Phiremock::on(
46 | getRequest()
47 | ->andUrl(isEqualTo('/banana'))
48 | ->andScenarioState('tomatoScenario', 'potato')
49 | )->then(
50 | respond(418)
51 | ->andBody('Is the answer to the Ultimate Question of Life, The Universe, and Everything')
52 | )
53 | );
54 |
55 | $I->sendGET('/banana');
56 | $I->seeResponseCodeIs(204);
57 | $I->sendGET('/banana');
58 | $I->seeResponseCodeIs(418);
59 | $I->seeResponseEquals('Is the answer to the Ultimate Question of Life, The Universe, and Everything');
60 | $this->_getPhiremockClient()->resetScenarios();
61 | $I->sendGET('/banana');
62 | $I->seeResponseCodeIs(204);
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/tests/acceptance/api/ScenarioStateCest.php:
--------------------------------------------------------------------------------
1 | .
18 | */
19 |
20 | namespace Mcustiel\Phiremock\Client\Tests\Acceptance;
21 |
22 | use ApiTester;
23 | use function Mcustiel\Phiremock\Client\getRequest;
24 | use function Mcustiel\Phiremock\Client\isEqualTo;
25 | use Mcustiel\Phiremock\Client\Phiremock;
26 | use function Mcustiel\Phiremock\Client\respond;
27 |
28 | class ScenarioStateCest
29 | {
30 | use PhiremockApiTestHelper;
31 |
32 | public function setsScenarioStateCorrectly(ApiTester $I)
33 | {
34 | $this->_getPhiremockClient()->createExpectation(
35 | Phiremock::on(
36 | getRequest()
37 | ->andUrl(isEqualTo('/banana'))
38 | ->andScenarioState('tomatoScenario', 'potato')
39 | )->then(
40 | respond(418)
41 | ->andBody('Is the answer to the Ultimate Question of Life, The Universe, and Everything')
42 | )
43 | );
44 |
45 | $I->sendGET('/banana');
46 | $I->seeResponseCodeIs(404);
47 | $this->_getPhiremockClient()->setScenarioState('tomatoScenario', 'potato');
48 | $I->sendGET('/banana');
49 | $I->seeResponseCodeIs(418);
50 | $I->seeResponseEquals('Is the answer to the Ultimate Question of Life, The Universe, and Everything');
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/tests/bootstrap.php:
--------------------------------------------------------------------------------
1 | .
17 | */
18 |
19 | require_once __DIR__ . '/../vendor/autoload.php';
20 |
--------------------------------------------------------------------------------
/tests/codeception/Extensions/ServerControl.php:
--------------------------------------------------------------------------------
1 | .
18 | */
19 |
20 | namespace Mcustiel\Codeception\Extensions;
21 |
22 | use Codeception\Event\SuiteEvent;
23 | use Codeception\Events;
24 | use Symfony\Component\Process\Process;
25 |
26 | class ServerControl extends \Codeception\Extension
27 | {
28 | public static $events = [
29 | Events::SUITE_BEFORE => 'suiteBefore',
30 | Events::SUITE_AFTER => 'suiteAfter',
31 | ];
32 | protected $config = [
33 | 'https' => false,
34 | ];
35 |
36 | /** @var Process */
37 | private $application;
38 |
39 | public function suiteBefore(SuiteEvent $event)
40 | {
41 | $this->writeln('Starting Phiremock server');
42 |
43 | $commandLine = [
44 | 'exec',
45 | './vendor/bin/phiremock',
46 | '-d',
47 | ];
48 | if ($this->config['https']) {
49 | $commandLine = array_merge(
50 | $commandLine,
51 | [
52 | '--certificate=' . codecept_data_dir('certificate-cert.pem'),
53 | '--certificate-key=' . codecept_data_dir('certificate-key.key'),
54 | ]
55 | );
56 | }
57 |
58 | $commandLine += array_merge(
59 | $commandLine,
60 | [
61 | '>',
62 | codecept_log_dir('phiremock.log'),
63 | '2>&1',
64 | ]
65 | );
66 |
67 | $this->application = Process::fromShellCommandline(implode(' ', $commandLine));
68 | $this->writeln($this->application->getCommandLine());
69 | $this->application->start();
70 | sleep(1);
71 | }
72 |
73 | public function suiteAfter()
74 | {
75 | $this->writeln('Stopping Phiremock server');
76 | if (!$this->application->isRunning()) {
77 | return;
78 | }
79 | $this->application->stop(5, SIGTERM);
80 | $this->writeln('Phiremock is stopped');
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/tests/codeception/Modules/PhiremockClient.php:
--------------------------------------------------------------------------------
1 | .
18 | */
19 |
20 | namespace Mcustiel\Codeception\Modules;
21 |
22 | use Codeception\Lib\ModuleContainer;
23 | use Codeception\Module;
24 | use Mcustiel\Phiremock\Client\Connection\Host;
25 | use Mcustiel\Phiremock\Client\Connection\Port;
26 | use Mcustiel\Phiremock\Client\Connection\Scheme;
27 | use Mcustiel\Phiremock\Client\Factory as ClientFactory;
28 | use Mcustiel\Phiremock\Client\Phiremock;
29 |
30 | class PhiremockClient extends Module
31 | {
32 | protected $config = ['https' => false];
33 |
34 | /** @var Scheme */
35 | private $scheme;
36 |
37 | public function __construct(ModuleContainer $moduleContainer, $config = null)
38 | {
39 | parent::__construct($moduleContainer, $config);
40 | $this->scheme = $this->config['https'] ? Scheme::createHttps() : Scheme::createHttp();
41 | }
42 |
43 | public function getPhiremockClient(): Phiremock
44 | {
45 | $factory = ClientFactory::createDefault();
46 | return $factory->createPhiremockClient(new Host('localhost'), new Port(8086), $this->scheme);
47 | }
48 |
49 | public function getPhiremockScheme(): string
50 | {
51 | return $this->scheme->asString();
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/tests/unit/Utils/ConditionsBuilderTest.php:
--------------------------------------------------------------------------------
1 | .
17 | */
18 |
19 | namespace Mcustiel\Phiremock\Client\Tests\Unit\Utils;
20 |
21 | use Mcustiel\Phiremock\Client\Utils\ConditionsBuilder;
22 | use Mcustiel\Phiremock\Client\Utils\ConditionsBuilderResult;
23 | use Mcustiel\Phiremock\Client\Utils\Is;
24 | use Mcustiel\Phiremock\Domain\Condition\Conditions\BodyCondition;
25 | use Mcustiel\Phiremock\Domain\Condition\Conditions\UrlCondition;
26 | use Mcustiel\Phiremock\Domain\Condition\MatchersEnum;
27 | use Mcustiel\Phiremock\Domain\Conditions as RequestConditions;
28 | use Mcustiel\Phiremock\Domain\Http\MethodsEnum;
29 | use Mcustiel\Phiremock\Domain\Options\ScenarioName;
30 | use PHPUnit\Framework\TestCase;
31 |
32 | class ConditionsBuilderTest extends TestCase
33 | {
34 | /** @var ConditionsBuilder */
35 | private $builder;
36 |
37 | public function testCreatesARequestExpectationWithDefaultValues()
38 | {
39 | $this->builder = new ConditionsBuilder();
40 | $result = $this->builder->build();
41 |
42 | $this->assertInstanceOf(ConditionsBuilderResult::class, $result);
43 | $this->assertInstanceOf(RequestConditions::class, $result->getRequestConditions());
44 | $request = $result->getRequestConditions();
45 | $this->assertNull($request->getMethod());
46 | $this->assertNull($request->getBody());
47 | $this->assertNull($request->getUrl());
48 | $this->assertNull($result->getScenarioName());
49 | $this->assertTrue($request->getHeaders()->isEmpty());
50 | }
51 |
52 | public function testCreatesARequestExpectationWithSetValues()
53 | {
54 | $this->builder = new ConditionsBuilder();
55 | $this->builder->andMethod(Is::equalTo(MethodsEnum::DELETE));
56 | $this->builder->andUrl(Is::equalTo('/potato'));
57 | $this->builder->andBody(Is::containing('tomato'));
58 | $this->builder->andHeader('Content-Type', Is::sameStringAs('text/plain'));
59 | $this->builder->andScenarioState('potatoScenarioName', 'tomatoScenarioState');
60 |
61 | $result = $this->builder->build();
62 |
63 | $this->assertInstanceOf(ConditionsBuilderResult::class, $result);
64 | $this->assertInstanceOf(RequestConditions::class, $result->getRequestConditions());
65 | $request = $result->getRequestConditions();
66 | $this->assertSame(MethodsEnum::DELETE, $request->getMethod()->getValue()->asString());
67 | $this->assertInstanceof(BodyCondition::class, $request->getBody());
68 | $this->assertSame(MatchersEnum::CONTAINS, $request->getBody()->getMatcher()->getName());
69 | $this->assertSame('tomato', $request->getBody()->getValue()->asString());
70 | $this->assertInstanceof(UrlCondition::class, $request->getUrl());
71 | $this->assertSame(MatchersEnum::EQUAL_TO, $request->getUrl()->getMatcher()->getName());
72 | $this->assertSame('/potato', $request->getUrl()->getValue()->asString());
73 | $this->assertInstanceOf(ScenarioName::class, $result->getScenarioName());
74 | $this->assertSame('potatoScenarioName', $result->getScenarioName()->asString());
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/tests/unit/Utils/HttpResponseBuilderTest.php:
--------------------------------------------------------------------------------
1 | .
17 | */
18 |
19 | namespace Mcustiel\Phiremock\Client\Tests\Unit\Utils;
20 |
21 | use Mcustiel\Phiremock\Client\Utils\HttpResponseBuilder;
22 | use Mcustiel\Phiremock\Domain\Http\StatusCode;
23 | use Mcustiel\Phiremock\Domain\HttpResponse;
24 | use PHPUnit\Framework\TestCase;
25 |
26 | class HttpResponseBuilderTest extends TestCase
27 | {
28 | /** @var HttpResponseBuilder */
29 | private $builder;
30 |
31 | public function testCreatesAResponseExpectationWithDefaultValues()
32 | {
33 | $this->builder = new HttpResponseBuilder(new StatusCode(503));
34 | /** @var HttpResponse $response */
35 | $response = $this->builder->build();
36 |
37 | $this->assertInstanceOf(HttpResponse::class, $response);
38 | $this->assertSame(503, $response->getStatusCode()->asInt());
39 | $this->assertSame('', $response->getBody()->asString());
40 | $this->assertFalse($response->hasDelayMillis());
41 | $this->assertTrue($response->getHeaders()->isEmpty());
42 | }
43 |
44 | public function testCreatesAResponseWithSetValues()
45 | {
46 | $this->builder = new HttpResponseBuilder(new StatusCode(418));
47 | $this->builder->andDelayInMillis(400);
48 | $this->builder->andBody('potato');
49 | $this->builder->andHeader('Content-Type', 'text/plain');
50 | $this->builder->andSetScenarioStateTo('tomatoScenarioState');
51 |
52 | $response = $this->builder->build();
53 |
54 | $this->assertInstanceOf(HttpResponse::class, $response);
55 | $this->assertSame('potato', $response->getBody()->asString());
56 | $this->assertTrue($response->hasDelayMillis());
57 | $this->assertSame(400, $response->getDelayMillis()->asInt());
58 | $this->assertTrue($response->hasNewScenarioState());
59 | $this->assertSame('tomatoScenarioState', $response->getNewScenarioState()->asString());
60 | $this->assertFalse($response->getHeaders()->isEmpty());
61 | $this->assertSame('Content-Type', $response->getHeaders()->current()->getName()->asString());
62 | $this->assertSame('text/plain', $response->getHeaders()->current()->getValue()->asString());
63 | }
64 | }
65 |
--------------------------------------------------------------------------------