Scenario.pm untested

filter: Statementstmt 0.0% 0 / 143 Branchbran 0.0% 0 / 48 Conditioncond 0.0% 0 / 54 MC/DCmcdc 0.0% 0 / 27 Subroutinesub 0.0% 0 / 23 Podpod 0.0% 0 / 16 totaltotal 0.0% 0 / 311 CC 25 SCAR 29.7
CC
25
Cov
0%
run
56.0
handle_request
42.0
_load_if_needed
20.0
CRAP 19.6
1 package Test::HTTP::Scenario;
2  
3 use strict;
4 use warnings;
5 use Carp qw(croak carp);
6 use Exporter qw(import);
7 use Scalar::Util qw(blessed);
8 use File::Slurper qw(read_text write_text);
9  
10 our @EXPORT_OK = qw(with_http_scenario);
11 our $VERSION = '0.01';
12  
13 =head1 NAME
14  
15 Test::HTTP::Scenario - Deterministic record/replay of HTTP interactions for test suites
16  
17 =head1 VERSION
18  
19 Version 0.01
20  
21 =head1 SYNOPSIS
22  
23 use Test::Most;
24 use Test::HTTP::Scenario qw(with_http_scenario);
25  
26 with_http_scenario(
27 name => 'get_user_basic',
28 file => 't/fixtures/get_user_basic.yaml',
29 mode => 'replay',
30 adapter => 'LWP',
31 sub {
32 my $user = $client->get_user(42);
33 cmp_deeply($user, superhashof({ id => 42 }));
34 },
35 );
36  
37 =head1 DESCRIPTION
38  
39 Test::HTTP::Scenario lets you test HTTP-based code without ever hitting the real network,
40 by recording real interactions once and replaying them forever.
41 It provides a deterministic record/replay mechanism
42 for HTTP-based test suites. It allows you to capture real HTTP
43 interactions once (record mode) and replay them later without network
44 access (replay mode). This makes API client tests fast, hermetic, and
45 fully deterministic.
46  
47 Adapters provide the glue to specific HTTP client libraries such as
48 LWP. Serializers control how fixtures are stored
49 on disk.
50  
51 =head1 MODES
52  
53 =head2 record
54  
55 Real HTTP requests are executed. Each request/response pair is
56 normalized and appended to the fixture. The fixture file is written at
57 the end of C<run()>.
58  
59 =head2 replay
60  
61 No real HTTP requests are made. Requests are matched against the
62 fixture in order, and responses are reconstructed from stored data.
63  
64 =head1 STRICT MODE
65  
66 If C<strict =E<gt> 1> is enabled, replay mode requires that all
67 recorded interactions are consumed. If the callback returns early,
68 C<run()> croaks with a strict-mode error.
69  
70 =head1 DIFFING
71  
72 If C<diffing =E<gt> 1> (default), mismatched requests produce a
73 detailed diff showing expected and actual method, URI, and normalized
74 request structures.
75  
76 =head1 ADAPTERS
77  
78 Adapters implement:
79  
80 =over 4
81  
82 =item * request/response normalization
83  
84 =item * response reconstruction
85  
86 =item * temporary monkey-patching of the HTTP client library
87  
88 =back
89  
90 Available adapters:
91  
92 =over 4
93  
94 =item * LWP
95  
96 =back
97  
98 You may also supply a custom adapter object.
99  
100 =head1 SERIALIZERS
101  
102 Serializers implement encoding and decoding of fixture files.
103  
104 Available serializers:
105  
106 =over 4
107  
108 =item * YAML (default)
109  
110 =item * JSON
111  
112 =back
113  
114 =head1 USING RECORD AND REPLAY IN REAL-WORLD APPLICATIONS
115  
116 This section describes the recommended workflow for using
117 C<Test::HTTP::Scenario> in a real-world test suite. The goal is to
118 capture real HTTP traffic once (record mode) and then replay it
119 deterministically in all subsequent test runs (replay mode).
120  
121 =head2 Overview
122  
123 Record/replay is designed for API client libraries that normally make
124 live HTTP requests. In record mode, the module performs real network
125 calls and stores normalized request/response pairs in a fixture file.
126 In replay mode, the module prevents all network access and returns
127 synthetic responses reconstructed from the fixture.
128  
129 This allows your test suite to:
130  
131 =over 4
132  
133 =item * run without network access
134  
135 =item * avoid flakiness caused by external services
136  
137 =item * run quickly and deterministically in CI
138  
139 =item * capture complex multi-step API flows once and reuse them
140  
141 =back
142  
143 =head2 Typical Workflow
144  
145 =head3 Step 1: Write your test using C<with_http_scenario>
146  
147 use Test::Most;
148 use Test::HTTP::Scenario qw(with_http_scenario);
149  
150 with_http_scenario(
151 name => 'get_user_flow',
152 file => 't/fixtures/get_user_flow.yaml',
153 mode => $ENV{SCENARIO_MODE} || 'replay',
154 adapter => 'LWP',
155 sub {
156 my $user = MyAPI->new->get_user(42);
157 is $user->{id}, 42, 'user id matches';
158 },
159 );
160  
161 =head3 Step 2: Run the test suite in record mode
162  
163 $ SCENARIO_MODE=record prove -l t/get_user_flow.t
164  
165 This performs real HTTP requests and writes the fixture file:
166  
167 t/fixtures/get_user_flow.yaml
168  
169 =head3 Step 3: Commit the fixture file to version control
170  
171 The fixture becomes part of your test assets. It should be treated like
172 any other test data file.
173  
174 =head3 Step 4: Run the test suite normally (replay mode)
175  
176 $ prove -l t
177  
178 Replay mode:
179  
180 =over 4
181  
182 =item * loads the fixture
183  
184 =item * intercepts all HTTP requests
185  
186 =item * matches them against the recorded interactions
187  
188 =item * returns synthetic responses
189  
190 =back
191  
192 No network access is required.
193  
194 =head2 Updating Fixtures
195  
196 If the API changes or you need to refresh the recorded data, simply
197 delete the fixture file and re-run the test in record mode:
198  
199 $ rm t/fixtures/get_user_flow.yaml
200 $ SCENARIO_MODE=record prove -l t/get_user_flow.t
201  
202 =head2 Example: Multi-Step API Flow
203  
204 Record mode captures each request in order:
205  
206 with_http_scenario(
207 name => 'create_and_fetch',
208 file => 't/fixtures/create_and_fetch.yaml',
209 mode => $ENV{SCENARIO_MODE} || 'replay',
210 adapter => 'LWP',
211 sub {
212 my $api = MyAPI->new;
213  
214 my $id = $api->create_user({ name => 'Alice' });
215 my $user = $api->get_user($id);
216  
217 is $user->{name}, 'Alice';
218 },
219 );
220  
221 Replay mode enforces the same sequence, ensuring your client behaves
222 correctly across multiple calls.
223  
224 =head2 Notes
225  
226 =over 4
227  
228 =item * Replay mode never performs real HTTP requests.
229  
230 =item * Strict mode can be enabled to ensure all interactions are consumed.
231  
232 =item * Diffing mode provides detailed diagnostics when a request does not match.
233  
234 =item * Fixtures are stable across platforms and Perl versions.
235  
236 =back
237  
238 =head1 METHODS
239  
240 =head2 new
241  
242 Construct a new scenario object.
243  
244 =head3 Purpose
245  
246 Initializes a scenario with a name, fixture file, mode, adapter, and
247 serializer. Loads adapter and serializer classes and binds the adapter
248 to the scenario.
249  
250 =head3 Arguments
251  
252 =over 4
253  
254 =item * name (Str, required)
255  
256 Scenario name.
257  
258 =item * file (Str, required)
259  
260 Path to the fixture file.
261  
262 =item * mode (Str, required)
263  
264 Either C<record> or C<replay>.
265  
266 =item * adapter (Str|Object, required)
267  
268 Adapter name such as C<LWP> or an adapter object.
269  
270 =item * serializer (Str, optional)
271  
272 Serializer name, default C<YAML>.
273  
274 =item * diffing (Bool, optional)
275  
276 Enable or disable diffing, default true.
277  
278 =item * strict (Bool, optional)
279  
280 Enable or disable strict behaviour, default false.
281  
282 =back
283  
284 =head3 Returns
285  
286 A new L<Test::HTTP::Scenario> object.
287  
288 =head3 Side Effects
289  
290 Loads adapter and serializer classes dynamically. Binds the adapter to
291 the scenario.
292  
293 =head3 Notes
294  
295 The adapter object persists across calls to C<run()>.
296  
297 =cut
298  
299 #----------------------------------------------------------------------#
300 # Constructor
301 #----------------------------------------------------------------------#
302  
303 sub new {
304 my ($class, %args) = @_;
305  
306 # Entry: class name and argument hash
307 # Exit: new Test::HTTP::Scenario object
308 # Side effects: loads adapter and serializer classes
309 # Notes: mode must be explicit and valid
310  
311 for my $k (qw(name file mode adapter)) {
312 croak "Missing required argument '$k'" unless exists $args{$k};
313 }
314  
315 croak "Invalid mode '$args{mode}'" unless $args{mode} =~ /\A(?:record|replay)\z/;
316  
317 my $adapter = _build_adapter($args{adapter});
318 my $serializer = _build_serializer($args{serializer} || 'YAML');
319  
320 my $self = bless {
321 name => $args{name},
322 file => $args{file},
323 mode => $args{mode},
324 adapter => $adapter,
325 serializer => $serializer,
326 interactions => [],
327 loaded => 0,
328 diffing => $args{diffing} // 1,
329 strict => $args{strict} // 0,
330 _cursor => 0
331 }, $class;
332  
333 $adapter->set_scenario($self);
334  
335 return $self;
336 }
337  
338 =head2 run
339  
340 Execute a coderef under scenario control.
341  
342 =head3 Purpose
343  
344 Installs adapter hooks, loads fixtures in replay mode, executes the
345 callback, and saves fixtures in record mode. Ensures uninstall and
346 save always occur.
347  
348 =head3 Arguments
349  
350 =over 4
351  
352 =item * CODE (Coderef, required)
353  
354 The code to execute while the adapter hooks are active.
355  
356 =back
357  
358 =head3 Returns
359  
360 Whatever the coderef returns, preserving list, scalar, or void context.
361  
362 =head3 Side Effects
363  
364 =over 4
365  
366 =item * Installs adapter hooks.
367  
368 =item * Loads fixtures in replay mode.
369  
370 =item * Saves fixtures in record mode.
371  
372 =item * Uninstalls adapter hooks at scope exit.
373  
374 =back
375  
376 =head3 Notes
377  
378 Exceptions propagate naturally. Strict mode enforces full consumption
379 of recorded interactions.
380  
381 =cut
382  
383  
384 sub run {
385 my ($self, $code) = @_;
386  
387 my $adapter = $self->{adapter};
388 $adapter->set_scenario($self);
389  
390 $self->_load_if_needed;
391 $adapter->install;
392  
393 # ensure uninstall + save ALWAYS run
394 my $guard = Test::HTTP::Scenario::Guard->new(sub {
395 $adapter->uninstall;
396 $self->_save_if_needed;
397 });
398  
399 my $wantarray = wantarray;
400  
401 my (@ret, $ret);
402  
403 # *** NO eval here ***
404 if (!defined $wantarray) {
405 $code->();
406 }
407 elsif ($wantarray) {
408 @ret = $code->();
409 }
410 else {
411 $ret = $code->();
412 }
413  
414 # strict mode AFTER callback, BEFORE returning
415 if ($self->{mode} eq 'replay' && $self->{strict}) {
416 my $total = @{ $self->{interactions} || [] };
417 my $cursor = $self->{_cursor} // 0;
418  
419 if ($cursor < $total) {
420 croak "Strict mode: $total interactions recorded, "
421 . "but only $cursor were used";
422 }
423 }
424  
425 return if !defined $wantarray;
426 return @ret if $wantarray;
427 return $ret;
428 }
429  
430 =head2 with_http_scenario
431  
432 Convenience wrapper for constructing and running a scenario.
433  
434 =head3 Purpose
435  
436 Creates a scenario object from key/value arguments and immediately
437 executes C<run()> with the supplied coderef.
438  
439 =head3 Arguments
440  
441 Key/value pairs identical to C<new>, followed by a coderef.
442  
443 =head3 Returns
444  
445 Whatever the coderef returns.
446  
447 =head3 Side Effects
448  
449 Constructs a scenario and installs adapter hooks during execution.
450  
451 =head3 Notes
452  
453 The final argument must be a coderef.
454  
455 =cut
456  
457 sub with_http_scenario {
458 my @args = @_;
459  
460 # Entry: key/value arguments followed by coderef
461 # Exit: returns whatever the coderef returns
462 # Side effects: constructs a scenario and runs it
463 # Notes: convenience wrapper for tests
464  
465 my $code = @args && ref $args[-1] eq 'CODE' ? pop @args : undef;
466  
467 croak 'with_http_scenario() requires a coderef as last argument'
468 unless $code;
469  
470 my %args = @args;
471  
472 my $self = __PACKAGE__->new(%args);
473  
474 return $self->run($code);
475 }
476  
477 =head2 handle_request
478  
479 Handle a single HTTP request in record or replay mode.
480  
481 =head3 Purpose
482  
483 In record mode, performs the real HTTP request and stores the
484 normalized request and response. In replay mode, matches the incoming
485 request against stored interactions and returns a synthetic response.
486  
487 =head3 Arguments
488  
489 =over 4
490  
491 =item * req (Object)
492  
493 Adapter-specific request object.
494  
495 =item * do_real (Coderef)
496  
497 Coderef that performs the real HTTP request.
498  
499 =back
500  
501 =head3 Returns
502  
503 =over 4
504  
505 =item * In record mode: the real HTTP::Response.
506  
507 =item * In replay mode: a reconstructed HTTP::Response.
508  
509 =back
510  
511 =head3 Side Effects
512  
513 =over 4
514  
515 =item * Appends interactions in record mode.
516  
517 =item * Advances the internal cursor in replay mode.
518  
519 =back
520  
521 =head3 Notes
522  
523 Matching is currently based on method and URI only. Diffing mode
524 produces detailed mismatch diagnostics.
525  
526 =cut
527  
528 sub handle_request {
529 my ($self, $req, $do_real) = @_;
530  
531 croak 'handle_request() requires a coderef for real request'
532 unless ref $do_real eq 'CODE';
533  
534 if ($self->{mode} eq 'record') {
535 my $res = $do_real->();
536  
537 my $record = {
538 request => $self->_normalize_request($req),
539 response => $self->_normalize_response($res),
540 };
541  
542 push @{ $self->{interactions} }, $record;
543  
544 return $res;
545 }
546  
547 # replay mode
548 $self->_load_if_needed;
549  
550 my $idx = $self->{_cursor} // 0;
551 my $interactions = $self->{interactions} || [];
552  
553 if ($idx > $#$interactions) {
554 croak 'No more recorded HTTP interactions available in scenario';
555 }
556  
557 my $expected = $interactions->[$idx]{request} || {};
558 my $stored = $interactions->[$idx]{response} || {};
559  
560 my $got = $self->_normalize_request($req);
561  
562 my $match = $self->_requests_match($expected, $got);
563  
564 if (!$match) {
565 my $msg = 'No matching HTTP interaction found in scenario';
566  
567 if ($self->{diffing}) {
568 my $diff = $self->_request_diff_string($expected, $got, $idx);
569 $msg .= "\n$diff";
570 }
571  
572 croak $msg;
573 }
574  
575 # consume this interaction
576 $self->{_cursor}++;
577  
578 return $self->_denormalize_response($stored);
579 }
580  
581 #----------------------------------------------------------------------#
582 # Internal helpers
583 #----------------------------------------------------------------------#
584  
585 sub _build_adapter {
586 my $adapter = $_[0];
587  
588 # Entry: adapter name or object
589 # Exit: adapter object
590 # Side effects: may load adapter class
591 # Notes: supports LWP, HTTP_Tiny and Mojo by name
592  
593 if (blessed $adapter) {
594 return $adapter;
595 }
596  
597 my %map = (
598 LWP => 'Test::HTTP::Scenario::Adapter::LWP',
599 HTTP_Tiny => 'Test::HTTP::Scenario::Adapter::HTTP_Tiny',
600 Mojo => 'Test::HTTP::Scenario::Adapter::Mojo',
601 );
602  
603 my $class = $map{$adapter}
604 or croak "Unknown adapter '$adapter'";
605  
606 ## no critic (ProhibitStringyEval)
607 eval "require $class" or croak "Failed to load $class: $@";
608  
609 return $class->new();
610 }
611  
612 # Entry: serializer name
613 # Exit: serializer object
614 # Side effects: may load serializer class
615 # Notes: supports YAML and JSON by name
616  
617 sub _build_serializer {
618 my ($name) = @_;
619  
620 my %map = (
621 YAML => 'Test::HTTP::Scenario::Serializer::YAML',
622 JSON => 'Test::HTTP::Scenario::Serializer::JSON',
623 );
624  
625 my $class = $map{$name}
626 or croak "Unknown serializer '$name'";
627  
628 ## no critic (ProhibitStringyEval)
629 eval "require $class" or croak "Failed to load $class: $@";
630  
631 return $class->new();
632 }
633  
634 # Load fixture interactions from disk if required.
635  
636 # Populate the scenario's interactions array when in replay mode and the
637 # fixture has not yet been loaded.
638  
639 # Reads the fixture file from disk if it exists.
640  
641 # Idempotent. Does nothing if already loaded or not in replay mode.
642  
643 # Entry: scenario object
644 # Exit: interactions populated if replay mode and file exists
645 # Side effects: reads from filesystem
646 # Notes: idempotent and only active in replay mode
647  
648 sub _load_if_needed {
649 my $self = $_[0];
650  
651 return if $self->{loaded};
652 return if $self->{mode} ne 'replay';
653  
654 return unless -e $self->{file};
655  
656 my $text = read_text($self->{file});
657 my $data = $self->{serializer}->decode_scenario($text);
658  
659 $self->{interactions} = $data->{interactions} || [];
660 $self->{loaded} = 1;
661  
662 return;
663 }
664  
665 # Write fixture interactions to disk if required.
666  
667 # Serialize and write recorded interactions to the fixture file at the
668 # end of a record-mode run.
669  
670 # Writes to the fixture file on disk.
671  
672 # Only active in record mode.
673  
674 # Entry: scenario object
675 # Exit: fixtures written if record mode
676 # Side effects: writes to filesystem
677 # Notes: diffing and strict behaviour can be added later
678  
679 sub _save_if_needed {
680 my $self = $_[0];
681  
682 return if $self->{mode} ne 'record';
683  
684 my $data = {
685 name => $self->{name},
686 version => 1,
687 interactions => $self->{interactions},
688 };
689  
690 my $text = $self->{serializer}->encode_scenario($data);
691  
692 write_text($self->{file}, $text);
693  
694 return;
695 }
696  
697 # Normalize an adapter-specific request object.
698  
699 # Convert a request object into a stable, serializable hash structure.
700  
701 # Delegates to the adapter.
702  
703 # Entry: adapter specific request object
704 # Exit: normalized request hash
705 # Side effects: none
706 # Notes: delegates to adapter
707  
708 sub _normalize_request {
709 my ($self, $req) = @_;
710  
711 return $self->{adapter}->normalize_request($req);
712 }
713  
714 # Normalize an adapter-specific response object.
715  
716 # Convert a response object into a stable, serializable hash structure.
717  
718 # Entry: adapter specific response object
719 # Exit: normalized response hash
720 # Side effects: none
721 # Notes: delegates to adapter
722  
723 sub _normalize_response {
724 my ($self, $res) = @_;
725  
726 return $self->{adapter}->normalize_response($res);
727 }
728  
729 # Reconstruct an adapter-specific response object.
730  
731 # Convert a stored response hash back into a real HTTP::Response object.
732  
733 # Entry: normalized response hash
734 # Exit: adapter specific response object
735 # Side effects: none
736 # Notes: delegates to adapter
737  
738 sub _denormalize_response {
739 my ($self, $hash) = @_;
740  
741 return $self->{adapter}->build_response($hash);
742 }
743  
744 # Entry: adapter specific request object
745 # Exit: matching interaction hash or undef
746 # Side effects: none
747 # Notes: simple method and uri equality for now
748  
749 sub _find_match {
750 my ($self, $req) = @_;
751  
752 my $norm = $self->_normalize_request($req);
753  
754 for my $interaction (@{ $self->{interactions} || [] }) {
755 my $r = $interaction->{request} || {};
756  
757 next unless ($r->{method} || '') eq ($norm->{method} || '');
758 next unless ($r->{uri} || '') eq ($norm->{uri} || '');
759  
760 return $interaction;
761 }
762  
763 return;
764 }
765  
766 # Compare two normalized request hashes.
767  
768 # Determine whether an incoming request matches the expected request in
769 # the fixture.
770  
771 # Header and body matching may be added later.
772  
773 sub _requests_match {
774 my ($self, $exp, $got) = @_;
775  
776 return 0 unless ($exp->{method} || '') eq ($got->{method} || '');
777 return 0 unless ($exp->{uri} || '') eq ($got->{uri} || '');
778  
779 # you can extend this later to headers/body if desired
780 return 1;
781 }
782  
783 # Produce a human-readable diff for mismatched requests.
784  
785 # Generate a diagnostic string showing differences between expected and
786 # actual requests.
787  
788 # Used only when diffing is enabled.
789  
790 sub _request_diff_string {
791 my ($self, $exp, $got, $idx) = @_;
792  
793 require Data::Dumper;
794 local $Data::Dumper::Terse = 1;
795 local $Data::Dumper::Indent = 1;
796  
797 return
798 "HTTP interaction mismatch at index $idx:\n"
799 . " Expected method: $exp->{method}\n"
800 . " Got method: $got->{method}\n"
801 . " Expected uri: $exp->{uri}\n"
802 . " Got uri: $got->{uri}\n"
803 . " Expected request hash:\n"
804 . Data::Dumper::Dumper($exp)
805 . " Got request hash:\n"
806 . Data::Dumper::Dumper($got);
807 }
808  
809 {
810 package Test::HTTP::Scenario::Guard;
811 sub new {
812 my ($class, $cb) = @_;
813 bless $cb, $class;
814 }
815 sub DESTROY {
816 my ($self) = @_;
817 $self->();
818 }
819 }
820  
821 1;
822  
823 =head1 AUTHOR
824  
825 Nigel Horne, C<< <njh at nigelhorne.com> >>
826  
827 =head1 BUGS
828  
829 =head1 SEE ALSO
830  
831 =head1 REPOSITORY
832  
833 L<https://github.com/nigelhorne/Test-HTTP-Scenario>
834  
835 =head1 SUPPORT
836  
837 This module is provided as-is without any warranty.
838  
839 Please report any bugs or feature requests to C<bug-test-http-scenario at rt.cpan.org>,
840 or through the web interface at
841 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Test-HTTP-Scenario>.
842 I will be notified, and then you'll
843 automatically be notified of progress on your bug as I make changes.
844  
845 You can find documentation for this module with the perldoc command.
846  
847 perldoc Test::HTTP::Scenario
848  
849 You can also look for information at:
850  
851 =over 4
852  
853 =item * MetaCPAN
854  
855 L<https://metacpan.org/dist/Test-HTTP-Scenario>
856  
857 =item * RT: CPAN's request tracker
858  
859 L<https://rt.cpan.org/NoAuth/Bugs.html?Dist=Test-HTTP-Scenario>
860  
861 =item * CPAN Testers' Matrix
862  
863 L<http://matrix.cpantesters.org/?dist=Test-HTTP-Scenario>
864  
865 =item * CPAN Testers Dependencies
866  
867 L<http://deps.cpantesters.org/?module=Test::HTTP::Scenario>
868  
869 =back
870  
871 =head1 LICENCE AND COPYRIGHT
872  
873 Copyright 2026 Nigel Horne.
874  
875 Usage is subject to licence terms.
876  
877 The licence terms of this software are as follows:
878  
879 =over 4
880  
881 =item * Personal single user, single computer use: GPL2
882  
883 =item * All other users (including Commercial, Charity, Educational, Government)
884 must apply in writing for a licence for use from Nigel Horne at the
885 above e-mail.
886  
887 =back
888  
889 =cut
890  
891 1;