Trog-DataModule-schema.t 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. use strict;
  2. use warnings;
  3. use Test::More;
  4. use Test::MockModule qw{strict};
  5. use Test::Deep;
  6. use Test::Fatal qw{exception};
  7. use JSON::MaybeXS();
  8. use Path::Tiny();
  9. use FindBin;
  10. use feature qw{signatures};
  11. no warnings qw{experimental::signatures};
  12. use lib "$FindBin::Bin/../lib";
  13. require_ok('Trog::DataModule') or BAIL_OUT("Can't find SUT");
  14. require_ok('Trog::Routes::HTML');
  15. # Point the SUT at a temp component dir we control and hand it whatever
  16. # sidecars each subtest wants. The layout has to mirror the real one -- the
  17. # component dir with a forms/ inside it -- because schema_for() keys its cache
  18. # on the mtime of forms/, and an earlier version of this fixture flattened the
  19. # two and so could not have caught it being keyed on the wrong directory.
  20. my $tempdir = Path::Tiny->tempdir();
  21. my $formsdir = $tempdir->child('forms');
  22. $formsdir->mkpath();
  23. my %sidecars;
  24. my $thememock = Test::MockModule->new('Trog::Themes');
  25. $thememock->redefine( 'template_dirs', sub { ("$tempdir") } );
  26. $thememock->redefine(
  27. 'themed_file_in_dir',
  28. sub ( $path, $file, @ ) {
  29. return -f "$formsdir/$file" ? "$formsdir/$file" : undef;
  30. }
  31. );
  32. # The logger isn't initialized outside of a running server.
  33. my $logmock = Test::MockModule->new('Trog::DataModule');
  34. $logmock->redefine( 'WARN', sub { note(shift) } );
  35. my $slurpmock = Test::MockModule->new('File::Slurper');
  36. $slurpmock->redefine( 'read_text', sub { $sidecars{ Path::Tiny::path(shift)->basename } } );
  37. # -f has to agree with %sidecars, and the dir mtime has to move, or the
  38. # mtime-keyed cache will hand back a stale answer.
  39. my $generation = 0;
  40. sub set_sidecars {
  41. %sidecars = @_;
  42. $_->remove foreach $formsdir->children();
  43. $formsdir->child($_)->spew_utf8('{}') foreach keys %sidecars;
  44. $generation++;
  45. utime( time() + $generation, time() + $generation, "$formsdir" );
  46. return;
  47. }
  48. sub sidecar { return JSON::MaybeXS::encode_json( { type => 'object', @_ } ) }
  49. subtest 'the base schema applies with no sidecar at all' => sub {
  50. set_sidecars();
  51. my $schema = Trog::DataModule::schema_for('blog.tx');
  52. ok( exists $schema->{properties}{title}, "base properties are there" );
  53. ok( !exists $schema->{properties}{gravy}, "and nothing else is" );
  54. ok( !exists $schema->{required}, "an empty required list isn't emitted - it isn't legal OpenAPI" );
  55. is_deeply(
  56. Trog::DataModule::schema_for(''),
  57. $schema,
  58. "a post with no form still gets the base schema"
  59. );
  60. };
  61. subtest 'a sidecar merges over the base' => sub {
  62. set_sidecars(
  63. 'recipe.json' => sidecar(
  64. required => ['servings'],
  65. properties => { servings => { type => 'integer' }, vegan => { type => 'boolean' } },
  66. )
  67. );
  68. my $schema = Trog::DataModule::schema_for('recipe.tx');
  69. ok( exists $schema->{properties}{servings}, "the sidecar's fields are merged in" );
  70. ok( exists $schema->{properties}{title}, "...without losing the base's" );
  71. is_deeply( $schema->{required}, ['servings'], "required carries over" );
  72. ok( !exists Trog::DataModule::schema_for('blog.tx')->{properties}{servings},
  73. "and they don't leak onto another post type" );
  74. };
  75. subtest 'sidecars cannot redefine core post fields' => sub {
  76. set_sidecars(
  77. 'evil.json' => sidecar(
  78. properties => {
  79. id => { type => 'object' },
  80. acls => { type => 'string' },
  81. callback => { type => 'string' },
  82. },
  83. )
  84. );
  85. my $schema = Trog::DataModule::schema_for('evil.tx');
  86. is( $schema->{properties}{id}{type}, 'string', "id keeps its own type" );
  87. is( $schema->{properties}{acls}{type}, 'array', "acls stays an array" );
  88. is( $schema->{properties}{callback}{type}, 'callback', "callback keeps the type that actually checks the sub exists" );
  89. };
  90. subtest 'a malformed sidecar is skipped, not fatal' => sub {
  91. set_sidecars( 'busted.json' => '{ this is not json' );
  92. my $schema;
  93. is( exception { $schema = Trog::DataModule::schema_for('busted.tx') }, undef, "no exception" );
  94. ok( exists $schema->{properties}{title}, "we fall back to the base schema" );
  95. };
  96. subtest 'the cache follows the forms dir mtime' => sub {
  97. set_sidecars( 'recipe.json' => sidecar( properties => { servings => { type => 'integer' } } ) );
  98. ok( exists Trog::DataModule::schema_for('recipe.tx')->{properties}{servings}, "declared" );
  99. set_sidecars();
  100. ok( !exists Trog::DataModule::schema_for('recipe.tx')->{properties}{servings},
  101. "removing the sidecar is picked up without a restart" );
  102. };
  103. subtest 'validate() filters, coerces and reports' => sub {
  104. set_sidecars(
  105. 'recipe.json' => sidecar(
  106. properties => {
  107. servings => { type => 'integer' },
  108. vegan => { type => 'boolean' },
  109. photo => { type => 'upload' },
  110. },
  111. )
  112. );
  113. my $post = {
  114. form => 'recipe.tx',
  115. title => 'Cookies',
  116. visibility => 'public',
  117. servings => '12',
  118. vegan => '1',
  119. # The router hands us plenty that was never a post field.
  120. app => 'junk',
  121. to => '/blog',
  122. gravy => 'yes please',
  123. };
  124. is_deeply( [ Trog::DataModule::validate($post) ], [], "a good post has no errors" );
  125. is( $post->{servings}, 12, "strings coerce to the declared type" );
  126. isa_ok( $post->{vegan}, 'JSON::PP::Boolean', "checkbox values become real booleans" );
  127. ok( !exists $post->{app} && !exists $post->{to} && !exists $post->{gravy}, "undescribed keys are filtered out" );
  128. my ($error) = Trog::DataModule::validate( { form => 'recipe.tx', servings => 'lots' } );
  129. like( $error, qr/servings/, "a bad value is reported rather than silently dropped" );
  130. # 'upload' is our own sugar for the string-or-hashref an upload field is,
  131. # depending on which direction it's travelling.
  132. is_deeply( [ Trog::DataModule::validate( { form => 'recipe.tx', photo => { filename => 'x' } } ) ], [], "an upload hashref passes" );
  133. is_deeply( [ Trog::DataModule::validate( { form => 'recipe.tx', photo => '/assets/x.jpg' } ) ], [], "so does the href it becomes" );
  134. };
  135. subtest 'empty inputs are treated as absent, except for strings' => sub {
  136. set_sidecars( 'recipe.json' => sidecar( properties => { servings => { type => 'integer' } } ) );
  137. # An untouched number input submits '', which is not an integer and was
  138. # never meant to be one.
  139. my $post = { form => 'recipe.tx', servings => '', title => '' };
  140. is_deeply( [ Trog::DataModule::validate($post) ], [], "no spurious type error" );
  141. ok( !exists $post->{servings}, "the blank number is dropped" );
  142. is( $post->{title}, '', "a blank string field is left exactly as it was before any of this was typed" );
  143. };
  144. subtest 'the custom types actually bite' => sub {
  145. set_sidecars();
  146. my ($bad) = Trog::DataModule::validate( { title => 'x', callback => 'Some::Random::Sub' } );
  147. like( $bad, qr/cannot be loaded/, "a callback naming a module that isn't there is refused" );
  148. is_deeply(
  149. [ Trog::DataModule::validate( { title => 'x', callback => 'Trog::Routes::HTML::posts' } ) ],
  150. [],
  151. "a real one is fine"
  152. );
  153. };
  154. subtest 'add() rejects a post that does not validate' => sub {
  155. set_sidecars( 'recipe.json' => sidecar( required => ['servings'], properties => { servings => { type => 'integer' } } ) );
  156. my $written;
  157. {
  158. no warnings qw{once};
  159. @TestData::ISA = ('Trog::DataModule');
  160. *TestData::get = sub { return () };
  161. *TestData::write = sub { $written = $_[1]; return 0 };
  162. }
  163. my $why = exception {
  164. bless( {}, 'TestData' )->add( { form => 'recipe.tx', title => 'Cookies', visibility => 'public' } );
  165. };
  166. is( ref $why, 'ARRAY', "it dies with the error list, not a string" );
  167. like( join( ' ', @$why ), qr/servings/, "which names the offending field" );
  168. # A string die would come back wearing a Carp::Always stack trace, which is
  169. # no use at all to whoever just submitted the form.
  170. unlike( join( ' ', @$why ), qr/DataModule\.pm line/, "and carries no stack trace" );
  171. ok( !$written, "nothing was written" );
  172. bless( {}, 'TestData' )->add( { form => 'recipe.tx', title => 'Cookies', visibility => 'public', servings => '4' } );
  173. is( $written->[0]{servings}, 4, "the good one went through, coerced" );
  174. };
  175. subtest '_wizard_fields zips the parallel arrays' => sub {
  176. # The middle row was left blank. Dropping it must not shift the type of
  177. # the row after it -- this is the whole reason param_required is a select.
  178. my $fields = Trog::Routes::HTML::_wizard_fields(
  179. {
  180. param_name => [ 'Servings', '', 'cook_time', 'id', 'servings' ],
  181. param_type => [ 'number', 'text', 'textarea', 'text', 'text' ],
  182. param_label => [ 'Servings', '', 'Cook Time', 'ID', 'Dupe' ],
  183. param_placeholder => [ '4', '', '45 min', '', '' ],
  184. param_required => [ 1, 0, 0, 0, 0 ],
  185. }
  186. );
  187. is( scalar @$fields, 2, "blank, core-shadowing and duplicate rows are dropped" );
  188. is( $fields->[0]{name}, 'servings', "names are lowercased" );
  189. is( $fields->[0]{required}, 1, "required survives" );
  190. is( $fields->[1]{name}, 'cook_time', "the row after the blank one is still present" );
  191. is( $fields->[1]{type}, 'textarea', "...with its own type, not the blank row's" );
  192. };
  193. subtest '_wizard_sidecar emits a usable OpenAPIv3 schema' => sub {
  194. my $spec = Trog::Routes::HTML::_wizard_sidecar(
  195. 'recipe',
  196. [
  197. { name => 'servings', type => 'number', label => 'Servings', placeholder => '4', required => 1 },
  198. { name => 'vegan', type => 'checkbox', label => 'Vegan?', placeholder => '', required => 0 },
  199. ],
  200. ['inc_tags'],
  201. 'form_common.tx',
  202. );
  203. is( $spec->{type}, 'object', "it's an object schema" );
  204. is( $spec->{properties}{servings}{type}, 'integer', "a number input is an integer" );
  205. is( $spec->{properties}{vegan}{type}, 'boolean', "a checkbox is a boolean" );
  206. is_deeply( $spec->{required}, ['servings'], "only the required rows are required" );
  207. # UI metadata rides along on x- keys so there's only one file to keep in sync.
  208. is( $spec->{properties}{servings}{'x-tcms-label'}, 'Servings', "labels are kept" );
  209. is( $spec->{properties}{servings}{'x-tcms-placeholder'}, '4', "so are placeholders" );
  210. ok( !exists $spec->{properties}{vegan}{'x-tcms-placeholder'}, "but an empty placeholder isn't written out" );
  211. is_deeply( $spec->{'x-tcms-post-type'}{includes}, ['tags.tx'], "the includes are recorded for regeneration" );
  212. };
  213. subtest '_kolon_safe defuses template syntax' => sub {
  214. my $safe = Trog::Routes::HTML::_kolon_safe(qq{<: \$post.id :>\n: include "evil.tx";});
  215. unlike( $safe, qr/</, "no angle brackets survive" );
  216. unlike( $safe, qr/[\r\n]/, "no newlines survive, so ':' can't start a directive" );
  217. is( Trog::Routes::HTML::_kolon_safe( [] ), '', "a repeated param can't sneak a ref through" );
  218. };
  219. done_testing();