Test-DBIC-ExpectedQueries-2.002000755001755001752 013655533126 15561 5ustar00bbcpebbcpe000000000000README100644001755001752 62113655533126 16501 0ustar00bbcpebbcpe000000000000Test-DBIC-ExpectedQueries-2.002This archive contains the distribution Test-DBIC-ExpectedQueries, version 2.002: Test that only expected DBIx::Class queries are run This software is copyright (c) 2020 by Johan Lindstrom. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. This README file was generated by Dist::Zilla::Plugin::Readme v6.014. Changes100644001755001752 574013655533126 17143 0ustar00bbcpebbcpe000000000000Test-DBIC-ExpectedQueries-2.002 Feature oriented Revision history for Test-DBIC-ExpectedQueries =============================================================== 2.002 -- 2020-05-09 13:55:33 UTC * Fix issue #6, sub-selects identifis table as "select". New option "report_subselect_tables" to try to find the first table actually selected from. 2.001 -- 2019-08-12 17:39:31 UTC * Support a test description, and report the test correctly. * Fix the stack trace so it's less spammy (filter out more common infrastructure modules), and more readable. 2.000 -- 2019-07-17 21:14:39 UTC * BREAKING CHANGE -- This release includes a bug fix to the library. It now tests queries more comprehensively (i.e. all queries). You may find your tests now breaking when previously they didn't. If this happens, you always had inaccurate tests but Test::DBIC::ExpectedQueries didn't flag this up correctly. This is the fault of this library, not your code. Sorry about that! It is however your problem, and now you need to fix your tests. If you need to make your tests pass immediately, pin the version to pre 2.000, e.g. if you have a "cpanfile" in your project: requires "Test::DBIC::ExpectedQueries", "< 2.0"; The fix you need to make is that the library will now report queries that were supposed to run n times, but didn't run at all. Let's say you have the check: { book_lender => { select => 1 } } You might see failures for queries that were supposed to run n times, but didn't run at all, e.g. Expected '1' inserts for table 'book_lender', got '0 Whether this is a problem or not depends on the situation. Either you're happy that you're not making any redundant queries because the information is cached or prefetched. Or this indicates a problem, because something that you thought happened isn't. In the former case, a useful fix is to either remove the line or to relax the test: { book_lender => { select => "<= 1" } } 1.011 -- 2015-11-05 15:18:09 UTC * Bug fix: Avoid wantarray being masked inside try-catch block 1.010 -- 2015-09-23 22:16:24 UTC * Bug fix: stack trace ignored classes 1.009 -- 2015-09-20 21:34:08 UTC * Table level option "stack_trace" to show a strack trace for each SQL query that fails. 1.008 -- 2015-04-27 14:49:49 UTC * Replace Attribute::Exporter with Exporter::Tiny, since Attribute::Exporter gone dun weird. 1.007 -- 2015-04-27 13:25:09 UTC * Fixed prereq on Attribute::Exporter 1.006 -- 2015-02-23 09:14:44 UTC * Fix #1 - Dereference hash for calling 'keys' - patch by Syohei YOSHIDA (syohex) 1.005 -- 2015-02-22 17:58:28 UTC * More POD improvements 1.004 -- 2015-02-20 17:30:45 UTC * Default ->test() to an empty hashref * Reset collected stats when calling ->test() properly! 1.003 -- 2015-02-20 16:48:11 UTC * Reset collected stats when calling ->test(). 1.002 -- 2015-02-20 14:34:10 UTC * Even more better POD docs. 1.001 -- 2015-02-20 13:51:38 UTC * POD 1.000 -- 2015-02-19 20:51:12 UTC * First release LICENSE100644001755001752 4366613655533126 16706 0ustar00bbcpebbcpe000000000000Test-DBIC-ExpectedQueries-2.002This software is copyright (c) 2020 by Johan Lindstrom. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. Terms of the Perl programming language system itself a) the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version, or b) the "Artistic License" --- The GNU General Public License, Version 1, February 1989 --- This software is Copyright (c) 2020 by Johan Lindstrom. This is free software, licensed under: The GNU General Public License, Version 1, February 1989 GNU GENERAL PUBLIC LICENSE Version 1, February 1989 Copyright (C) 1989 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The license agreements of most software companies try to keep users at the mercy of those companies. By contrast, our General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. The General Public License applies to the Free Software Foundation's software and to any other program whose authors commit to using it. You can use it for your programs, too. When we speak of free software, we are referring to freedom, not price. Specifically, the General Public License is designed to make sure that you have the freedom to give away or sell copies of free software, that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of a such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must tell them their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any work containing the Program or a portion of it, either verbatim or with modifications. Each licensee is addressed as "you". 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this General Public License and to the absence of any warranty; and give any other recipients of the Program a copy of this General Public License along with the Program. You may charge a fee for the physical act of transferring a copy. 2. You may modify your copy or copies of the Program or any portion of it, and copy and distribute such modifications under the terms of Paragraph 1 above, provided that you also do the following: a) cause the modified files to carry prominent notices stating that you changed the files and the date of any change; and b) cause the whole of any work that you distribute or publish, that in whole or in part contains the Program or any part thereof, either with or without modifications, to be licensed at no charge to all third parties under the terms of this General Public License (except that you may choose to grant warranty protection to some or all third parties, at your option). c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the simplest and most usual way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this General Public License. d) You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. Mere aggregation of another independent work with the Program (or its derivative) on a volume of a storage or distribution medium does not bring the other work under the scope of these terms. 3. You may copy and distribute the Program (or a portion or derivative of it, under Paragraph 2) in object code or executable form under the terms of Paragraphs 1 and 2 above provided that you also do one of the following: a) accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Paragraphs 1 and 2 above; or, b) accompany it with a written offer, valid for at least three years, to give any third party free (except for a nominal charge for the cost of distribution) a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Paragraphs 1 and 2 above; or, c) accompany it with the information you received as to where the corresponding source code may be obtained. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form alone.) Source code for a work means the preferred form of the work for making modifications to it. For an executable file, complete source code means all the source code for all modules it contains; but, as a special exception, it need not include source code for modules which are standard libraries that accompany the operating system on which the executable file runs, or for standard header files or definitions files that accompany that operating system. 4. You may not copy, modify, sublicense, distribute or transfer the Program except as expressly provided under this General Public License. Any attempt otherwise to copy, modify, sublicense, distribute or transfer the Program is void, and will automatically terminate your rights to use the Program under this License. However, parties who have received copies, or rights to use copies, from you under this General Public License will not have their licenses terminated so long as such parties remain in full compliance. 5. By copying, distributing or modifying the Program (or any work based on the Program) you indicate your acceptance of this license to do so, and all its terms and conditions. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. 7. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of the license which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the license, you may choose any version ever published by the Free Software Foundation. 8. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 10. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to humanity, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 19yy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19xx name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (a program to direct compilers to make passes at assemblers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice That's all there is to it! --- The Artistic License 1.0 --- This software is Copyright (c) 2020 by Johan Lindstrom. This is free software, licensed under: The Artistic License 1.0 The Artistic License Preamble The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. Definitions: - "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. - "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder. - "Copyright Holder" is whoever is named in the copyright or copyrights for the package. - "You" is you, if you're thinking about copying or distributing this Package. - "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) - "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. 1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. 3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least ONE of the following: a) place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or placing the modifications on a major archive site such as ftp.uu.net, or by allowing the Copyright Holder to include your modifications in the Standard Version of the Package. b) use the modified Package only within your corporation or organization. c) rename any non-standard executables so the names do not conflict with standard executables, which must also be provided, and provide a separate manual page for each non-standard executable that clearly documents how it differs from the Standard Version. d) make other distribution arrangements with the Copyright Holder. 4. You may distribute the programs of this Package in object code or executable form, provided that you do at least ONE of the following: a) distribute a Standard Version of the executables and library files, together with instructions (in the manual page or equivalent) on where to get the Standard Version. b) accompany the distribution with the machine-readable source of the Package with your modifications. c) accompany any non-standard executables with their corresponding Standard Version executables, giving the non-standard executables non-standard names, and clearly documenting the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. d) make other distribution arrangements with the Copyright Holder. 5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own. 6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whomever generated them, and may be sold commercially, and may be aggregated with this Package. 7. C or perl subroutines supplied by you and linked into this Package shall not be considered part of this Package. 8. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End dist.ini100644001755001752 133513655533126 17310 0ustar00bbcpebbcpe000000000000Test-DBIC-ExpectedQueries-2.002name = Test-DBIC-ExpectedQueries author = Johan Lindstrom license = Perl_5 copyright_holder = Johan Lindstrom [Bugtracker] web = https://github.com/jplindstrom/p5-Test-DBIC-ExpectedQueries/issues [Git::Check] [GatherDir] include_dotfiles = 1 [PruneCruft] [ManifestSkip] [MetaYAML] [License] [Readme] [ExtraTests] [ExecDir] [ShareDir] [MakeMaker] [Manifest] [TestRelease] [PodSyntaxTests] ; [CheckChangesHasContent] Doesn't seem to work... ; [PodWeaver] [AutoPrereqs] [Prereqs] ; [ConfirmRelease] [UploadToCPAN] [Git::Commit] [Git::Tag] ; [Git::CommitBuild] [Git::Push] [Git::NextVersion] first_version = 1.000 [PkgVersion] [NextRelease] time_zone = UTC format = %v -- %{yyyy-MM-dd HH:mm:ss VVVV}d META.yml100644001755001752 163613655533126 17121 0ustar00bbcpebbcpe000000000000Test-DBIC-ExpectedQueries-2.002--- abstract: 'Test that only expected DBIx::Class queries are run' author: - 'Johan Lindstrom ' build_requires: Test::Deep: '0' Test::Warnings: '0' lib: '0' strict: '0' warnings: '0' configure_requires: ExtUtils::MakeMaker: '0' dynamic_config: 0 generated_by: 'Dist::Zilla version 6.014, CPAN::Meta::Converter version 2.150010' license: perl meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: '1.4' name: Test-DBIC-ExpectedQueries requires: Carp: '0' DBIx::Class: '0' Devel::StackTrace: '0' Exporter::Tiny: '0' Moo: '0' Test::More: '0' Try::Tiny: '0' autobox::Core: '0' autobox::Transform: '0' resources: bugtracker: https://github.com/jplindstrom/p5-Test-DBIC-ExpectedQueries/issues version: '2.002' x_generated_by_perl: v5.26.1 x_serialization_backend: 'YAML::Tiny version 1.73' x_spdx_expression: 'Artistic-1.0-Perl OR GPL-1.0-or-later' MANIFEST100644001755001752 47213655533126 16756 0ustar00bbcpebbcpe000000000000Test-DBIC-ExpectedQueries-2.002# This file was automatically generated by Dist::Zilla::Plugin::Manifest v6.014. Changes LICENSE MANIFEST MANIFEST.SKIP META.yml Makefile.PL README dist.ini lib/Test/DBIC/ExpectedQueries.pm lib/Test/DBIC/ExpectedQueries/Query.pm t/author-pod-syntax.t t/class.t t/queries.t t/query.t t/stack_trace.t t/subroutine.t t000755001755001752 013655533126 15745 5ustar00bbcpebbcpe000000000000Test-DBIC-ExpectedQueries-2.002query.t100644001755001752 513113655533126 17437 0ustar00bbcpebbcpe000000000000Test-DBIC-ExpectedQueries-2.002/t use strict; use warnings; use Test::More; use lib "lib"; use Test::DBIC::ExpectedQueries::Query; note "*** SQL queries parsed correctly"; sub test_parse { my ($sql, $operation, $table, $report_subselect_tables) = @_; local $Test::Builder::Level = $Test::Builder::Level + 1; $report_subselect_tables ||= 0; my $query = Test::DBIC::ExpectedQueries::Query->new({ sql => $sql, stack_trace => "not under test", report_subselect_tables => $report_subselect_tables, }); my $display_operation = $operation // ""; is($query->operation, $operation, "Correct ->operation for $display_operation"); is($query->table, $table, "Correct ->table for $display_operation"); } subtest "Simple operations" => sub { subtest "SELECT" => sub { test_parse("Select * from file", "select", "file"); test_parse("Select * from metric_value", "select", "metric_value"); test_parse("Select * from 'file'", "select", "file"); }; subtest "INSERT" => sub { test_parse("insert into file ('id') values (1)", "insert", "file"); test_parse("insert into `file` ('id') values (1)", "insert", "file"); }; subtest "UPDATE" => sub { test_parse("update file set id = 2 where id = 4", "update", "file"); test_parse('update "file" set id = 2 where id = 4', "update", "file"); }; subtest "DELETE" => sub { test_parse("delete from other_db.file where id = 4", "delete", "other_db.file"); test_parse("delete from 'other_db.file' where id = 4", "delete", "other_db.file"); }; }; subtest "Sub selects" => sub { test_parse("SELECT abc, def from (select * from file)", "select", "select"); note "Sub-select"; test_parse("SELECT abc, def from (select * from file)", "select", "file", 1); note "Nested sub-selects"; test_parse( "SELECT abc, def from (select * from (select * from (select * from file)))", "select", "file", 1, ); note "Nested sub-selects, with eventually no identifiable table at the core"; test_parse( "SELECT abc, def from (select * from (select * from (select 'Just a value')))", undef, undef, 1, ); }; subtest "Issue 6" => sub { note "Actal query reported"; test_parse( q| (SELECT me.id, me.req_id, me.version, me.name FROM ( SELECT me.id, me.req_id, me.version, me.name FROM tablename me WHERE ( req_id = ? ) ORDER BY version DESC ) me WHERE ROWNUM <= ? |, "select", "tablename", 1, ); }; done_testing(); class.t100644001755001752 1037113655533126 17421 0ustar00bbcpebbcpe000000000000Test-DBIC-ExpectedQueries-2.002/tuse strict; use warnings; use Test::More; use Test::Deep; use Test::Warnings; use lib "lib"; use Test::DBIC::ExpectedQueries; sub query { my ($table, $operation) = @_; return Test::DBIC::ExpectedQueries::Query->new({ sql => "$operation on $table", stack_trace => "not under test", table => $table, operation => $operation, report_subselect_tables => 0, }); } sub add_queries { my ($queries) = @_; $queries->queries([ query("puff", "select"), query("puff", "select"), query("magic", "insert"), query("magic", "insert"), query("magic", "select"), query("magic", "select"), query("magic", "select"), query("dragon", "delete"), Test::DBIC::ExpectedQueries::Query->new({ sql => "create table abc", stack_trace => "", report_subselect_tables => 0, }), ]); } my $queries = Test::DBIC::ExpectedQueries->new({ schema => "don't hit anything that uses ->schema and we'll be fine", }); note "Test queries vs expected"; # # puff # select 2 # magic # insert 2 # select 3 # dragon # delete 1 # * Expect # ok - puff select 2 # not - puff insert > 0 # ok - magic insert < 3 # not - no mention of magic select # not - dragon, no mention of add_queries($queries); my $table_operation_count = $queries->table_operation_count; my $expected_operation_count = { dragon => { delete => 1 }, magic => { select => 3, insert => 2 }, puff => { select => 2 } }; cmp_deeply( $table_operation_count, $expected_operation_count, "Correct table_operation_count", ) or diag explain $table_operation_count; my $failure = $queries->check_table_operation_counts({ puff => { select => 2 }, magic => { insert => "> 0", stack_trace => 1 }, }); is( $failure, "* Table: dragon Expected '0' deletes for table 'dragon', got '1' Actually executed SQL queries on table 'dragon': SQL: (delete on dragon) * Table: magic Expected '0' selects for table 'magic', got '3' Actually executed SQL queries on table 'magic': SQL: (insert on magic) not under test SQL: (insert on magic) not under test SQL: (select on magic) not under test SQL: (select on magic) not under test SQL: (select on magic) not under test ", "Correctly identified all discrepancies", ); is( $queries->unknown_warning, " Warning: unknown queries: SQL: (create table abc) ", "Found unknown queries", ); note "Check it works to run many times and then checking"; $queries->queries([ query("puff", "select"), ]); $failure = $queries->check_table_operation_counts({ puff => { select => 1 }, }); is($failure, "", "Re-setting queries re-sets the stats"); ###JPL: test all $expected_queries, even if there's no query for one subtest "Missing operation fails" => sub { add_queries($queries); my $failure = $queries->check_table_operation_counts({ %$expected_operation_count, dragon => { delete => 1, # sql was run for this insert => 1, # no sql for this }, }); is( $failure, q|* Table: dragon Expected '1' inserts for table 'dragon', got '0' Actually executed SQL queries on table 'dragon': SQL: (delete on dragon) |, "Missing dragon insert failed", ); }; subtest "Missing table fails" => sub { add_queries($queries); my $failure = $queries->check_table_operation_counts({ %$expected_operation_count, othertable => { insert => 1, # no sql for this }, }); is( $failure, q|* Table: othertable Expected '1' inserts for table 'othertable', got '0' Actually executed SQL queries on table 'othertable': |, "Missing othertable (no operations at all) failed", ); }; subtest "Test spec undef doesn't warn" => sub { add_queries($queries); my $failure = $queries->check_table_operation_counts({ %$expected_operation_count, puff => { insert => undef, # shouldn't warn }, }); pass("Placeholder PASS, the warnings will be reported at the end"); }; # TODO: test invalid test operation like "isnert" done_testing(); queries.t100644001755001752 175313655533126 17755 0ustar00bbcpebbcpe000000000000Test-DBIC-ExpectedQueries-2.002/t use strict; use warnings; use Test::More; use lib "lib"; use Test::DBIC::ExpectedQueries; my $queries = Test::DBIC::ExpectedQueries->new({ schema => "don't run", queries => [ Test::DBIC::ExpectedQueries::Query->new({ sql => "UPDATE datum SET is_valid = ? WHERE ( id = ? )", stack_trace => "not under test", report_subselect_tables => 0, }), Test::DBIC::ExpectedQueries::Query->new({ sql => " sELECT * from file", stack_trace => "not under test", report_subselect_tables => 0, }), ], }); is(scalar @{$queries->queries}, 2, "Parsed out two query objects"); my $query = $queries->queries->[0]; is($query->operation, "update", "Correct ->operation"); is($query->table, "datum", "Correct ->table"); $query = $queries->queries->[1]; is($query->operation, "select", "Correct ->operation"); is($query->table, "file", "Correct ->table"); done_testing(); Makefile.PL100644001755001752 303613655533126 17616 0ustar00bbcpebbcpe000000000000Test-DBIC-ExpectedQueries-2.002# This file was automatically generated by Dist::Zilla::Plugin::MakeMaker v6.014. use strict; use warnings; use ExtUtils::MakeMaker; my %WriteMakefileArgs = ( "ABSTRACT" => "Test that only expected DBIx::Class queries are run", "AUTHOR" => "Johan Lindstrom ", "CONFIGURE_REQUIRES" => { "ExtUtils::MakeMaker" => 0 }, "DISTNAME" => "Test-DBIC-ExpectedQueries", "LICENSE" => "perl", "NAME" => "Test::DBIC::ExpectedQueries", "PREREQ_PM" => { "Carp" => 0, "DBIx::Class" => 0, "Devel::StackTrace" => 0, "Exporter::Tiny" => 0, "Moo" => 0, "Test::More" => 0, "Try::Tiny" => 0, "autobox::Core" => 0, "autobox::Transform" => 0 }, "TEST_REQUIRES" => { "Test::Deep" => 0, "Test::Warnings" => 0, "lib" => 0, "strict" => 0, "warnings" => 0 }, "VERSION" => "2.002", "test" => { "TESTS" => "t/*.t" } ); my %FallbackPrereqs = ( "Carp" => 0, "DBIx::Class" => 0, "Devel::StackTrace" => 0, "Exporter::Tiny" => 0, "Moo" => 0, "Test::Deep" => 0, "Test::More" => 0, "Test::Warnings" => 0, "Try::Tiny" => 0, "autobox::Core" => 0, "autobox::Transform" => 0, "lib" => 0, "strict" => 0, "warnings" => 0 ); unless ( eval { ExtUtils::MakeMaker->VERSION(6.63_03) } ) { delete $WriteMakefileArgs{TEST_REQUIRES}; delete $WriteMakefileArgs{BUILD_REQUIRES}; $WriteMakefileArgs{PREREQ_PM} = \%FallbackPrereqs; } delete $WriteMakefileArgs{CONFIGURE_REQUIRES} unless eval { ExtUtils::MakeMaker->VERSION(6.52) }; WriteMakefile(%WriteMakefileArgs); MANIFEST.SKIP100644001755001752 17713655533126 17525 0ustar00bbcpebbcpe000000000000Test-DBIC-ExpectedQueries-2.002^_build ^Build$ ^blib ~$ \.bak$ \.bat$ \.log$ \.tmp$ \.out \.old$ CVS \.svn release.pl ^\.PerlySenseProject ^cover_db ^covered subroutine.t100644001755001752 51513655533126 20452 0ustar00bbcpebbcpe000000000000Test-DBIC-ExpectedQueries-2.002/tuse strict; use warnings; package Fake::DBIC; use Moo; sub storage { return shift } sub debug { return shift } sub debugcb { return shift } package main; use Test::More; use lib "lib"; use Test::DBIC::ExpectedQueries; # Doesn't blow up, good expected_queries( Fake::DBIC->new, sub { }, {} ); done_testing(); stack_trace.t100644001755001752 210213655533126 20550 0ustar00bbcpebbcpe000000000000Test-DBIC-ExpectedQueries-2.002/tuse strict; use warnings; use Test::More; use Test::Deep; use Test::Warnings; use lib "lib"; use Test::DBIC::ExpectedQueries; my $queries = Test::DBIC::ExpectedQueries->new({ schema => "don't hit anything that uses ->schema and we'll be fine", }); sub Test::A::abc { Test::B::def(@_) } sub Test::B::def { shift->_stack_trace() } *abc = "abc"; subtest "_stack_trace string has correct shape" => sub { my $with_newline = "new\nline"; my $callers = Test::A::abc($queries, $with_newline, sub { "code ref" }, [], {}, \*abc); like( $callers, qr|^SQL executed at t.stack_trace.t line \d+ Test::B::def\('Test::DBIC::ExpectedQueries', 'new\^Jline', '', '', '', ''\) called at t.stack_trace.t line \d+ Test::A::abc\('Test::DBIC::ExpectedQueries', 'new\^Jline', '', '', '', ''\) called at t.stack_trace.t line \d+ Test::More::subtest\('_stack_trace string has correct shape', ''\) called at t.stack_trace.t line \d+|, "Correct frames, and shape" ); }; done_testing(); author-pod-syntax.t100644001755001752 45413655533126 21663 0ustar00bbcpebbcpe000000000000Test-DBIC-ExpectedQueries-2.002/t#!perl BEGIN { unless ($ENV{AUTHOR_TESTING}) { print qq{1..0 # SKIP these tests are for testing by the author\n}; exit } } # This file was automatically generated by Dist::Zilla::Plugin::PodSyntaxTests. use strict; use warnings; use Test::More; use Test::Pod 1.41; all_pod_files_ok(); DBIC000755001755001752 013655533126 17670 5ustar00bbcpebbcpe000000000000Test-DBIC-ExpectedQueries-2.002/lib/TestExpectedQueries.pm100644001755001752 5053513655533126 23515 0ustar00bbcpebbcpe000000000000Test-DBIC-ExpectedQueries-2.002/lib/Test/DBIC=head1 NAME Test::DBIC::ExpectedQueries - Test that only expected DBIx::Class queries are run =head1 VERSION 2.000 Version 2.000 is out with a breaking change. If you're having issues with your test suite, please see the L file for details. =head1 DESCRIPTION Ensure that only the DBIx::Class SQL queries you expect are executed while a particular piece of code under test is run. Find the places in your code where the unexpected queries are executed. =head2 Avoiding the n+1 problem When following a relation off a DBIC row object it's easy to overlook the fact that it might be causing one query for each and every row in the resultset. This can easily be solved by prefetching those relations, but you have to know it happens first. This module will help you finding unexpected queries, where they are being caused, and to ensure you don't accidentally start running many single-row queries in the future. =head1 SYNOPSIS =head2 Setup use Test::More; use Test::DBIC::ExpectedQueries; my $schema = ...; # Connect to a DBIx::Class schema =head2 Simple my @book_rows = expected_queries( $schema, sub { $schema->resultset("Book")->find(34); $schema->resultset("Author")->create( ... ); $schema->resultset("Book")->search( undef, { join => "author" } )->all; }, { book => { select => "<= 2", stack_trace => 1, }, author => { insert => undef }, }, "Doing that stuff runs correct SQL", # optional ); =head2 Flexible my $queries = Test::DBIC::ExpectedQueries->new({ schema => $schema, report_subselect_tables => 1, }); $queries->run(sub { $schema->resultset("Book")->find(34); $schema->resultset("Author")->create( ... ); }); my @book_rows = $queries->run(sub { $schema->resultset("Book")->search( undef, { join => "author" } )->all; }); $queries->test({ book => { select => "<= 2"}, author => { insert => undef }, }); # or, with test description $queries->test( { book => { select => "<= 2"}, author => { insert => undef }, }, "Doing that stuff runs correct SQL", # optional ); =head1 USAGE You might already have a good idea of what queries are/should be run. But often that's not the case. Start by wrapping some DBIC application code in a test without any specific limits. The default expectation for all tables is 0 queries run. So the test will fail, and report all the executed queries it didn't expect. Now you know what's going on. Now you can add prefetches or caching for queries that shouldn't happen and specify query limits for the currently known behaviour. Whether you want to nail down the expected queries with exact counts, or just put wide-margin comparisons in place is up to you. =head2 Finding the unexpected queries Once you find unexpected queries made by your code, the next step is eliminating them. But where are they called from? =head3 Chained ResultSets DBIC has this nice feature of chaining resultsets, which means you can create a resultset and later modify it by adding things to the WHERE clause, joining in other resultsets, add prefetching of relations or whatever you need to do. You can create small logical pieces of queries (and put them on their corresponding Result/ResultSet classes) and then combine them in to actual queries, expressed in higher level operation. This is very, very powerful and one of the coolest features of DBIC. There is a problem with passing around a resultset before finally executing it though, and that is that it can often be tricky to find exactly where it is being executed. =head3 Following relations The problem of finding the source of a database call isn't limited to chained queries though. The same thing happens when you construct a query, and then follow relations off of the main table. This is what causes the n + 1 problem and you accidentally make n queries for individual rows on top of the first one. These additional queries might be a long way off from where the initial query was made. =head3 Show the stack trace To solve this problem of where the queries originate you can tell Test::DBIC::ExpectedQueries to show a C for particular tables. These call stacks may be quite deep, so you'll have to find the unexpected queries first, and then enable the call stack for each of them. That will also avoid spamming the test output with things you're not interested in. =head2 Return value from the test For the subroutine C, and the method C<$queries->run(...)>, the return value is whatever the subroutine under test returned, so it's easy to wrap the DBIC code under test and still get out the result. It is context sensitive. =head2 Executed queries vs resultsets Only queries actually executed inside the test are being monitored. This sounds obvious, but might be a source of problems. Many DBIC methods are context sensitive, and in scalar context might just return an unrealized resultset rather than execute a query and return the resulting rows. If you're unsure, assigning the query to an array will make it run in list context and therefore execute the SQL query. Or you can call C<->>all> on the resultset object. =head2 DBIC_TRACE Normally, setting the ENV variable DBIC_TRACE can be used to "warn" the DBIC queries. Test::DBIC:ExpectedQueries uses the same mechanism as DBIC_TRACE does, so while the code is run under the test the normal DBIC_TRACE will not happen. =head1 SUBROUTINES =head2 expected_queries( $schema, $sub_ref, $expected_table_operations = {}, $description? ) : $result | @result Run $sub_ref and collect stats for queries executed on $schema, then test (using $description) that they match the $expected_table_operations. Return the return value of $sub_ref->(). See the ANNOTATED EXAMPLES below for examples on how the $expected_table_operations is used, but here's a simple example: { book => { select => "<= 2", update => 3 }, author => { insert => undef }, genre => { select => 2, stack_trace => 1 }, }, =over 4 =item * Use table names as found in the raw SQL, not DBIC terms like resultset and relation names. For relational queries, only the first main table is collected. =item * Use SQL terms like "select", "insert", "update", "delete", not DBIC terms like "create" and "search". =item * A number means exact match. Comparisons in a string means, well that. =item * Undef means any number of queries =item * If you need to see where the queries for a table are executed from, use C 1>. =back =head1 METHODS =head2 new({ schema => $schema, report_subselect_tables => 0 }}) : $new_object Create new test object. $schema is a DBIx::Class::Schema object. If C is false (default), any SQL query like select * from (select abc from def); will report a select on the table C