Trog-DataModule-schema.t 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  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 URI::Escape();
  10. use FindBin;
  11. use feature qw{signatures};
  12. no warnings qw{experimental::signatures};
  13. use lib "$FindBin::Bin/../lib";
  14. require_ok('Trog::DataModule') or BAIL_OUT("Can't find SUT");
  15. require_ok('Trog::Routes::HTML');
  16. # Point the SUT at a temp component dir we control and hand it whatever
  17. # sidecars each subtest wants. The layout has to mirror the real one -- the
  18. # component dir with a forms/ inside it -- because schema_for() keys its cache
  19. # on the mtime of forms/, and an earlier version of this fixture flattened the
  20. # two and so could not have caught it being keyed on the wrong directory.
  21. my $tempdir = Path::Tiny->tempdir();
  22. my $formsdir = $tempdir->child('forms');
  23. $formsdir->mkpath();
  24. my %sidecars;
  25. my $thememock = Test::MockModule->new('Trog::Themes');
  26. $thememock->redefine( 'template_dirs', sub { ("$tempdir") } );
  27. $thememock->redefine(
  28. 'themed_file_in_dir',
  29. sub ( $path, $file, @ ) {
  30. return -f "$formsdir/$file" ? "$formsdir/$file" : undef;
  31. }
  32. );
  33. # The logger isn't initialized outside of a running server.
  34. my $logmock = Test::MockModule->new('Trog::DataModule');
  35. $logmock->redefine( 'WARN', sub { note(shift) } );
  36. # The canned editor blocks and their sidecars, which live in the components dir
  37. # itself rather than in forms/ -- preview.json beside preview.tx.
  38. my %components;
  39. my $slurpmock = Test::MockModule->new('File::Slurper');
  40. $slurpmock->redefine(
  41. 'read_text',
  42. sub {
  43. my $name = Path::Tiny::path(shift)->basename;
  44. return exists $sidecars{$name} ? $sidecars{$name} : $components{$name};
  45. }
  46. );
  47. # -f has to agree with %sidecars, and the dir mtime has to move, or the
  48. # mtime-keyed cache will hand back a stale answer.
  49. my $generation = 0;
  50. sub set_sidecars {
  51. %sidecars = @_;
  52. $_->remove foreach $formsdir->children();
  53. $formsdir->child($_)->spew_utf8('{}') foreach keys %sidecars;
  54. $generation++;
  55. utime( time() + $generation, time() + $generation, "$formsdir" );
  56. return;
  57. }
  58. # The same, one directory up. forms/ is a child of this one, so only the files
  59. # get cleared out.
  60. sub set_components {
  61. %components = @_;
  62. $_->remove foreach grep { !$_->is_dir } $tempdir->children();
  63. $tempdir->child($_)->spew_utf8('{}') foreach keys %components;
  64. $generation++;
  65. utime( time() + $generation, time() + $generation, "$tempdir" );
  66. return;
  67. }
  68. sub sidecar { return JSON::MaybeXS::encode_json( { type => 'object', @_ } ) }
  69. subtest 'the base schema applies with no sidecar at all' => sub {
  70. set_sidecars();
  71. my $schema = Trog::DataModule::schema_for('blog.tx');
  72. ok( exists $schema->{properties}{title}, "base properties are there" );
  73. ok( !exists $schema->{properties}{gravy}, "and nothing else is" );
  74. ok( !exists $schema->{required}, "an empty required list isn't emitted - it isn't legal OpenAPI" );
  75. is_deeply(
  76. Trog::DataModule::schema_for(''),
  77. $schema,
  78. "a post with no form still gets the base schema"
  79. );
  80. };
  81. subtest 'a sidecar merges over the base' => sub {
  82. set_sidecars(
  83. 'recipe.json' => sidecar(
  84. required => ['servings'],
  85. properties => { servings => { type => 'integer' }, vegan => { type => 'boolean' } },
  86. )
  87. );
  88. my $schema = Trog::DataModule::schema_for('recipe.tx');
  89. ok( exists $schema->{properties}{servings}, "the sidecar's fields are merged in" );
  90. ok( exists $schema->{properties}{title}, "...without losing the base's" );
  91. is_deeply( $schema->{required}, ['servings'], "required carries over" );
  92. ok(
  93. !exists Trog::DataModule::schema_for('blog.tx')->{properties}{servings},
  94. "and they don't leak onto another post type"
  95. );
  96. };
  97. subtest 'sidecars cannot redefine core post fields' => sub {
  98. set_sidecars(
  99. 'evil.json' => sidecar(
  100. properties => {
  101. id => { type => 'object' },
  102. acls => { type => 'string' },
  103. callback => { type => 'string' },
  104. },
  105. )
  106. );
  107. my $schema = Trog::DataModule::schema_for('evil.tx');
  108. is( $schema->{properties}{id}{type}, 'string', "id keeps its own type" );
  109. is( $schema->{properties}{acls}{type}, 'array', "acls stays an array" );
  110. is( $schema->{properties}{callback}{type}, 'callback', "callback keeps the type that actually checks the sub exists" );
  111. };
  112. subtest 'a malformed sidecar is skipped, not fatal' => sub {
  113. set_sidecars( 'busted.json' => '{ this is not json' );
  114. my $schema;
  115. is( exception { $schema = Trog::DataModule::schema_for('busted.tx') }, undef, "no exception" );
  116. ok( exists $schema->{properties}{title}, "we fall back to the base schema" );
  117. };
  118. subtest 'the cache follows the forms dir mtime' => sub {
  119. set_sidecars( 'recipe.json' => sidecar( properties => { servings => { type => 'integer' } } ) );
  120. ok( exists Trog::DataModule::schema_for('recipe.tx')->{properties}{servings}, "declared" );
  121. set_sidecars();
  122. ok(
  123. !exists Trog::DataModule::schema_for('recipe.tx')->{properties}{servings},
  124. "removing the sidecar is picked up without a restart"
  125. );
  126. };
  127. subtest 'validate() filters, coerces and reports' => sub {
  128. set_sidecars(
  129. 'recipe.json' => sidecar(
  130. properties => {
  131. servings => { type => 'integer' },
  132. vegan => { type => 'boolean' },
  133. photo => { type => 'upload' },
  134. },
  135. )
  136. );
  137. my $post = {
  138. form => 'recipe.tx',
  139. title => 'Cookies',
  140. visibility => 'public',
  141. servings => '12',
  142. vegan => '1',
  143. # The router hands us plenty that was never a post field.
  144. app => 'junk',
  145. to => '/blog',
  146. gravy => 'yes please',
  147. };
  148. is_deeply( [ Trog::DataModule::validate($post) ], [], "a good post has no errors" );
  149. is( $post->{servings}, 12, "strings coerce to the declared type" );
  150. isa_ok( $post->{vegan}, 'JSON::PP::Boolean', "checkbox values become real booleans" );
  151. ok( !exists $post->{app} && !exists $post->{to} && !exists $post->{gravy}, "undescribed keys are filtered out" );
  152. my ($error) = Trog::DataModule::validate( { form => 'recipe.tx', servings => 'lots' } );
  153. like( $error, qr/servings/, "a bad value is reported rather than silently dropped" );
  154. # 'upload' is our own sugar for the string-or-hashref an upload field is,
  155. # depending on which direction it's travelling.
  156. is_deeply( [ Trog::DataModule::validate( { form => 'recipe.tx', photo => { filename => 'x' } } ) ], [], "an upload hashref passes" );
  157. is_deeply( [ Trog::DataModule::validate( { form => 'recipe.tx', photo => '/assets/x.jpg' } ) ], [], "so does the href it becomes" );
  158. };
  159. subtest 'what gets written is checked, not just what was submitted' => sub {
  160. set_sidecars();
  161. # validate() runs on the submitted post. _process() then builds the shape
  162. # that is actually stored, and until it was checked too, a post could be
  163. # made wrong on its way to disk and nobody would ever hear about it.
  164. my $good = { form => 'blog.tx', title => 'Fine', tags => [qw{blog public}], visibility => 'public' };
  165. is_deeply( [ Trog::DataModule::validate_built($good) ], [], 'a well built post passes' );
  166. my $holed = { form => 'blog.tx', title => 'Holed', tags => [ 'public', undef ], visibility => 'public' };
  167. my @errors = Trog::DataModule::validate_built($holed);
  168. ok( scalar(@errors), 'a null in the tags is caught' );
  169. like( "$errors[0]", qr{/tags/1}, 'and named by where it is' );
  170. # It checks rather than filters, unlike validate(): _process() adds fields
  171. # the base schema has never heard of, and throwing those away would discard
  172. # the work it just did.
  173. my $built = {
  174. form => 'blog.tx',
  175. title => 'Built',
  176. tags => ['public'],
  177. visibility => 'public',
  178. content_type => 'text/html',
  179. is_video => 1,
  180. attachments => ['/assets/thing.txt'],
  181. preview => '/assets/thumb.png',
  182. };
  183. is_deeply( [ Trog::DataModule::validate_built($built) ], [], "the fields _process() invents do not fail it" );
  184. ok( exists $built->{is_video}, 'and are not deleted' );
  185. ok( exists $built->{attachments}, 'any of them' );
  186. };
  187. subtest '_process no longer builds a post wrong' => sub {
  188. # The bug: a post saved without a visibility had an undef pushed into its
  189. # tags, which is a tag no query ever matches -- so the post went invisible
  190. # to all but an admin, silently, and the bunk tag was written to disk.
  191. my $post = Trog::DataModule::_process( { form => 'blog.tx', title => 'No Visibility', tags => ['blog'] } );
  192. is_deeply( [ grep { !defined } @{ $post->{tags} } ], [], 'no undef survives into the tags' );
  193. is( $post->{visibility}, 'private', 'and the visibility is defaulted where the tag is made' );
  194. ok( scalar( grep { $_ eq 'private' } @{ $post->{tags} } ), 'so the tag it produces is a real one' );
  195. # Which is the same thing validate_built() is there to notice.
  196. is_deeply( [ Trog::DataModule::validate_built($post) ], [], 'and the result passes the check' );
  197. # An undef among the acls of a private post went the same way.
  198. my $acled = Trog::DataModule::_process( { form => 'blog.tx', title => 'Acled', tags => ['blog'], visibility => 'private', acls => [ 'members', undef ] } );
  199. is_deeply( [ grep { !defined } @{ $acled->{tags} } ], [], 'nor from the acls' );
  200. ok( scalar( grep { $_ eq 'members' } @{ $acled->{tags} } ), 'while the real acl still lands' );
  201. };
  202. subtest 'add() refuses to store a post it built wrong' => sub {
  203. set_sidecars();
  204. # Break _process on purpose: the point is that add() no longer takes its
  205. # word for it. This is the shape the real bug produced.
  206. #
  207. # One mock object for all three, and unmocked by hand at the end.
  208. # Test::MockModule keeps one per package, so a second new() on the same
  209. # package hands back the first -- and leaving it to go out of scope left
  210. # _process broken for every subtest after this one.
  211. my @written;
  212. my $mock = Test::MockModule->new('Trog::DataModule');
  213. $mock->redefine(
  214. '_process',
  215. sub ($post) {
  216. push( @{ $post->{tags} }, undef );
  217. return $post;
  218. }
  219. );
  220. $mock->redefine( 'write', sub { my ( $self, $data ) = @_; push( @written, @$data ); return 1 } );
  221. $mock->redefine( 'get', sub { return () } );
  222. my $model = bless {}, 'Trog::DataModule';
  223. my $err = exception { $model->add( { form => 'blog.tx', title => 'Doomed', tags => ['blog'], visibility => 'public' } ) };
  224. $mock->unmock_all();
  225. ok( $err, 'the save fails' );
  226. is( ref $err, 'ARRAY', 'with the errors the submitter is shown' );
  227. like( "$err->[0]", qr{/tags/}, 'saying what was wrong' );
  228. is_deeply( \@written, [], 'and nothing was written' );
  229. # The mock really is gone, or every subtest after this one is testing it.
  230. my $sane = Trog::DataModule::_process( { form => 'blog.tx', title => 'Sane', tags => ['blog'], visibility => 'public' } );
  231. is_deeply( [ grep { !defined } @{ $sane->{tags} } ], [], '_process is itself again afterwards' );
  232. };
  233. subtest 'empty inputs are treated as absent, except for strings' => sub {
  234. set_sidecars( 'recipe.json' => sidecar( properties => { servings => { type => 'integer' } } ) );
  235. # An untouched number input submits '', which is not an integer and was
  236. # never meant to be one.
  237. my $post = { form => 'recipe.tx', servings => '', title => '' };
  238. is_deeply( [ Trog::DataModule::validate($post) ], [], "no spurious type error" );
  239. ok( !exists $post->{servings}, "the blank number is dropped" );
  240. is( $post->{title}, '', "a blank string field is left exactly as it was before any of this was typed" );
  241. };
  242. subtest 'the custom types actually bite' => sub {
  243. set_sidecars();
  244. my ($bad) = Trog::DataModule::validate( { title => 'x', callback => 'Some::Random::Sub' } );
  245. like( $bad, qr/cannot be loaded/, "a callback naming a module that isn't there is refused" );
  246. is_deeply(
  247. [ Trog::DataModule::validate( { title => 'x', callback => 'Trog::Routes::HTML::posts' } ) ],
  248. [],
  249. "a real one is fine"
  250. );
  251. };
  252. subtest 'add() rejects a post that does not validate' => sub {
  253. set_sidecars( 'recipe.json' => sidecar( required => ['servings'], properties => { servings => { type => 'integer' } } ) );
  254. my $written;
  255. {
  256. no warnings qw{once};
  257. @TestData::ISA = ('Trog::DataModule');
  258. *TestData::get = sub { return () };
  259. *TestData::write = sub { $written = $_[1]; return 0 };
  260. }
  261. my $why = exception {
  262. bless( {}, 'TestData' )->add( { form => 'recipe.tx', title => 'Cookies', visibility => 'public' } );
  263. };
  264. is( ref $why, 'ARRAY', "it dies with the error list, not a string" );
  265. like( join( ' ', @$why ), qr/servings/, "which names the offending field" );
  266. # A string die would come back wearing a Carp::Always stack trace, which is
  267. # no use at all to whoever just submitted the form.
  268. unlike( join( ' ', @$why ), qr/DataModule\.pm line/, "and carries no stack trace" );
  269. ok( !$written, "nothing was written" );
  270. bless( {}, 'TestData' )->add( { form => 'recipe.tx', title => 'Cookies', visibility => 'public', servings => '4' } );
  271. is( $written->[0]{servings}, 4, "the good one went through, coerced" );
  272. };
  273. subtest 'a post always ends up with a visibility' => sub {
  274. set_sidecars();
  275. my $written;
  276. {
  277. no warnings qw{once};
  278. @VisData::ISA = ('Trog::DataModule');
  279. *VisData::get = sub { return () };
  280. *VisData::write = sub { $written = $_[1]; return 0 };
  281. }
  282. # A post type built without a visibility selector submits none. _process
  283. # pushes visibility into the tags, so an undef one puts an undef in there
  284. # and the post becomes invisible to everyone but an admin.
  285. bless( {}, 'VisData' )->add( { title => 'No Visibility', tags => ['sometag'] } );
  286. is( $written->[0]{visibility}, 'private', 'it defaults, rather than staying undef' );
  287. ok( !( grep { !defined $_ } @{ $written->[0]{tags} } ), 'so no undef finds its way into the tags' );
  288. bless( {}, 'VisData' )->add( { title => 'Explicit', visibility => 'public', tags => ['sometag'] } );
  289. is( $written->[0]{visibility}, 'public', 'and an explicit one is left alone' );
  290. };
  291. subtest 'a save message never becomes a URL' => sub {
  292. # The whole shape of the bug: a write that failed deep in File::Slurper,
  293. # decorated by Carp::Always with the entire call stack, went into the
  294. # redirect URL as a query parameter. The result was several thousand
  295. # characters, and tPSGI answered its own redirect with a 419 -- so the user
  296. # saw neither the page they saved from nor the error.
  297. my $realistic = "Couldn't rename data/dnZHxmlXE5 to data/files/: Not a directory at /opt/perl5/lib/File/Slurper/Temp.pm line 56.\n" . "\tFile::Slurper::Temp::write_text(\"data/files/\", \"[{...}]\") called at /opt/perl5/lib/File/Slurper/Temp.pm line 63\n" . ( "\tTrog::Routes::HTML::post_save(HASH(0x5e798a626570)) called at lib/TCMS.pm line 130\n" x 40 );
  298. my $short = Trog::Routes::HTML::_short_error($realistic);
  299. unlike( $short, qr/\n/, 'the trace is gone' );
  300. unlike( $short, qr/line \d+/, 'and so is the file and line Perl glued on' );
  301. like( $short, qr/^Couldn't rename data/, 'leaving what actually went wrong' );
  302. my $cookie = Trog::Routes::HTML::_feedback_cookie( 1, $realistic );
  303. ok( length($cookie) < 2048, 'even the whole untrimmed thing fits in a cookie' )
  304. or diag( 'cookie was ' . length($cookie) . ' bytes' );
  305. like( $cookie, qr/^tcmsfeedback=1:/, 'flagged as a failure' );
  306. like( $cookie, qr/HttpOnly/, 'and not readable by script, since nothing needs to' );
  307. like( $cookie, qr/Max-Age=\d+/, 'and does not outlive the message it carries' );
  308. # One line, because the banner puts it in a JS string literal.
  309. my ($value) = $cookie =~ m/^tcmsfeedback=1:([^;]*)/;
  310. unlike( URI::Escape::uri_unescape($value), qr/\n/, 'the message is one line' );
  311. # Round trips.
  312. my ( $failure, $message ) = Trog::Routes::HTML::_feedback_from_cookie($cookie);
  313. is( $failure, 1, 'the outcome comes back out' );
  314. like( $message, qr/^Couldn't rename/, 'and so does the message' );
  315. ( $failure, $message ) = Trog::Routes::HTML::_feedback_from_cookie( Trog::Routes::HTML::_feedback_cookie( 0, "Saved post 'Thing'." ) );
  316. is( $failure, 0, 'a success comes back as one' );
  317. is( $message, "Saved post 'Thing'.", 'with its message intact' );
  318. # And nothing at all when there is no cookie to read.
  319. is_deeply( [ Trog::Routes::HTML::_feedback_from_cookie('') ], [], 'no cookies, no feedback' );
  320. is_deeply( [ Trog::Routes::HTML::_feedback_from_cookie('other=thing') ], [], 'nor other cookies' );
  321. is_deeply( [ Trog::Routes::HTML::_feedback_from_cookie('tcmsfeedback=xyz') ], [], 'nor one that is malformed' );
  322. };
  323. subtest '_wizard_fields zips the parallel arrays' => sub {
  324. # The middle row was left blank. Dropping it must not shift the type of
  325. # the row after it -- this is the whole reason param_required is a select.
  326. my $fields = Trog::Routes::HTML::_wizard_fields(
  327. {
  328. param_name => [ 'Servings', '', 'cook_time', 'id', 'servings' ],
  329. param_type => [ 'number', 'text', 'textarea', 'text', 'text' ],
  330. param_label => [ 'Servings', '', 'Cook Time', 'ID', 'Dupe' ],
  331. param_placeholder => [ '4', '', '45 min', '', '' ],
  332. param_required => [ 1, 0, 0, 0, 0 ],
  333. }
  334. );
  335. is( scalar @$fields, 2, "blank, core-shadowing and duplicate rows are dropped" );
  336. is( $fields->[0]{name}, 'servings', "names are lowercased" );
  337. is( $fields->[0]{required}, 1, "required survives" );
  338. is( $fields->[1]{name}, 'cook_time', "the row after the blank one is still present" );
  339. is( $fields->[1]{type}, 'textarea', "...with its own type, not the blank row's" );
  340. };
  341. subtest '_wizard_sidecar emits a usable OpenAPIv3 schema' => sub {
  342. my $spec = Trog::Routes::HTML::_wizard_sidecar(
  343. 'recipe',
  344. [
  345. { name => 'servings', type => 'number', label => 'Servings', placeholder => '4', required => 1 },
  346. { name => 'vegan', type => 'checkbox', label => 'Vegan?', placeholder => '', required => 0 },
  347. ],
  348. ['inc_tags'],
  349. 'form_common.tx',
  350. );
  351. is( $spec->{type}, 'object', "it's an object schema" );
  352. is( $spec->{properties}{servings}{type}, 'integer', "a number input is an integer" );
  353. is( $spec->{properties}{vegan}{type}, 'boolean', "a checkbox is a boolean" );
  354. is_deeply( $spec->{required}, ['servings'], "only the required rows are required" );
  355. # UI metadata rides along on x- keys so there's only one file to keep in sync.
  356. is( $spec->{properties}{servings}{'x-tcms-label'}, 'Servings', "labels are kept" );
  357. is( $spec->{properties}{servings}{'x-tcms-placeholder'}, '4', "so are placeholders" );
  358. ok( !exists $spec->{properties}{vegan}{'x-tcms-placeholder'}, "but an empty placeholder isn't written out" );
  359. is_deeply( $spec->{'x-tcms-post-type'}{includes}, ['tags.tx'], "the includes are recorded for regeneration" );
  360. };
  361. subtest 'a type records what the wizard was told, where the validator cannot see it' => sub {
  362. my $fields = [
  363. {
  364. name => 'cook_time', type => 'text', label => 'Cook Time', placeholder => '45 minutes',
  365. required => 1, private => 0, indexed => 1, relation_form => '', relation_mode => 'one',
  366. },
  367. {
  368. name => 'everything', type => 'relation', label => '', placeholder => '',
  369. required => 0, private => 0, indexed => 0, relation_form => 'blog.tx', relation_mode => 'all',
  370. },
  371. ];
  372. my $spec = Trog::Routes::HTML::_wizard_sidecar(
  373. 'recipe', $fields, ['inc_tags'], 'form_common.tx', '',
  374. {
  375. description => 'A recipe, with its cook time.',
  376. display => '<div class="r"><: $post.cook_time :></div>',
  377. title_placeholder => 'Bread',
  378. wrapper => 1,
  379. inc_post_title => 1,
  380. inc_post_tags => 0,
  381. }
  382. );
  383. my $type = $spec->{'x-tcms-post-type'};
  384. is( $type->{description}, 'A recipe, with its cook time.', 'the description is recorded' );
  385. is( $type->{display}, '<div class="r"><: $post.cook_time :></div>', 'and the display template' );
  386. is( $type->{title_placeholder}, 'Bread', 'and the title placeholder' );
  387. ok( $type->{wrapper}, 'and the checkboxes which are not includes' );
  388. ok( $type->{inc_post_title}, 'all of them' );
  389. ok( !$type->{inc_post_tags}, 'including the ones that were clear' );
  390. # The point of putting it there: schema_for() keeps properties and required
  391. # and nothing else, so none of this can affect whether a post validates.
  392. set_sidecars( 'recipe.json' => JSON::MaybeXS::encode_json($spec) );
  393. my $schema = Trog::DataModule::schema_for('recipe.tx');
  394. ok( !exists $schema->{'x-tcms-post-type'}, 'and the validator never sees any of it' );
  395. ok( exists $schema->{properties}{cook_time}, 'while the fields it does care about are there' );
  396. is_deeply( [ Trog::DataModule::validate( { form => 'recipe.tx', title => 'x', cook_time => '45 minutes' } ) ], [], 'so a post of the type still saves' );
  397. };
  398. subtest 'a type reads back as the form that made it' => sub {
  399. my $spec = Trog::Routes::HTML::_wizard_sidecar(
  400. 'recipe',
  401. [
  402. {
  403. name => 'cook_time', type => 'number', label => 'Cook Time', placeholder => '45',
  404. required => 1, private => 0, indexed => 1, relation_form => '', relation_mode => 'one',
  405. },
  406. {
  407. name => 'secret_note', type => 'textarea', label => 'Note', placeholder => '',
  408. required => 0, private => 1, indexed => 0, relation_form => '', relation_mode => 'one',
  409. },
  410. {
  411. name => 'picked', type => 'relation', label => 'Picked', placeholder => '',
  412. required => 0, private => 0, indexed => 0, relation_form => 'blog.tx', relation_mode => 'one',
  413. },
  414. {
  415. name => 'everything', type => 'relation', label => '', placeholder => '',
  416. required => 0, private => 0, indexed => 0, relation_form => 'entities.tx', relation_mode => 'all',
  417. },
  418. ],
  419. [qw{inc_preview inc_tags}],
  420. 'form_multi.tx',
  421. 'Trog::DataSource::Virt',
  422. {
  423. description => 'What it is for.',
  424. display => '<div>x</div>',
  425. title_placeholder => 'Bread',
  426. wrapper => 1,
  427. inc_post_title => 0,
  428. inc_post_tags => 1,
  429. }
  430. );
  431. set_sidecars( 'recipe.json' => JSON::MaybeXS::encode_json($spec) );
  432. my $types = Trog::Routes::HTML::_wizard_types( ['recipe.tx'] );
  433. my $back = $types->{'recipe.tx'};
  434. is( $back->{name}, 'recipe', 'the name comes back without the extension' );
  435. is( $back->{description}, 'What it is for.', 'the description comes back' );
  436. is( $back->{display}, '<div>x</div>', 'and the display' );
  437. is( $back->{body_form}, 'form_multi.tx', 'and which body form' );
  438. is( $back->{datasource}, 'Trog::DataSource::Virt', 'and the datasource' );
  439. is( $back->{title_placeholder}, 'Bread', 'and the placeholder' );
  440. is( $back->{wrapper}, 1, 'the ticked boxes come back ticked' );
  441. is( $back->{inc_post_title}, 0, 'the clear ones clear' );
  442. is( $back->{inc_post_tags}, 1, 'individually' );
  443. is( $back->{inc_preview}, 1, 'and the includes are recovered from the list' );
  444. is( $back->{inc_tags}, 1, 'all of them' );
  445. is( $back->{inc_aliases}, 0, 'and only them' );
  446. my %by_name = map { $_->{name} => $_ } @{ $back->{fields} };
  447. is( scalar( keys %by_name ), 4, 'every custom field comes back' );
  448. is( $by_name{cook_time}{type}, 'number', 'with the input it was given' );
  449. is( $by_name{cook_time}{label}, 'Cook Time', 'its label' );
  450. is( $by_name{cook_time}{required}, 1, 'whether it was required' );
  451. is( $by_name{cook_time}{indexed}, 1, 'and whether it was indexed' );
  452. is( $by_name{secret_note}{private}, 1, 'a private field says so' );
  453. is( $by_name{picked}{type}, 'relation', 'a relation says so' );
  454. is( $by_name{picked}{relation_form}, 'blog.tx', 'naming its target' );
  455. is( $by_name{picked}{relation_mode}, 'one', 'and that it picks one' );
  456. # This one stores nothing, so it has no property to be found by -- it exists
  457. # only as a relations entry, and would be lost without looking there.
  458. is( $by_name{everything}{relation_mode}, 'all', 'a pick-everything relation comes back too' );
  459. is( $by_name{everything}{relation_form}, 'entities.tx', 'naming its target' );
  460. # And nothing from the base post schema, which was never a wizard field.
  461. ok( !exists $by_name{title}, 'the base schema fields are not offered as custom ones' );
  462. ok( !exists $by_name{visibility}, 'any of them' );
  463. };
  464. subtest 'the checkboxes outside the editor come back from the template too' => sub {
  465. set_components();
  466. # A hand-written type: a wrapper div, both display blocks, and the
  467. # multi-page body form. Its sidecar records none of that, because nothing
  468. # but a generated one ever did.
  469. set_sidecars(
  470. 'deck.json' => sidecar(),
  471. 'deck.tx' => <<'TEMPLATE',
  472. <div class="post <: $style :>">
  473. :if ( !$post.addpost ) {
  474. : include "post_title.tx";
  475. : include "post_tags.tx";
  476. : }
  477. : include "form_multi.tx";
  478. </div>
  479. TEMPLATE
  480. # And one which opens with its own markup instead of the wrapper, and
  481. # shows neither block -- as file.tx and profile.tx really do.
  482. 'bare.json' => sidecar(),
  483. 'bare.tx' => qq|<!-- a comment first, which is not the wrapper -->\n:if ( !\$post.addpost ) {\n: }\n : include "form_common.tx";\n|,
  484. );
  485. my $types = Trog::Routes::HTML::_wizard_types( [ 'deck.tx', 'bare.tx' ] );
  486. is( $types->{'deck.tx'}{wrapper}, 1, "the wrapper div is seen where a type opens with one" );
  487. is( $types->{'deck.tx'}{inc_post_title}, 1, "as is the post title block" );
  488. is( $types->{'deck.tx'}{inc_post_tags}, 1, "and the post tag block" );
  489. is( $types->{'deck.tx'}{body_form}, 'form_multi.tx', "and which body form carries the post" );
  490. is( $types->{'bare.tx'}{wrapper}, 0, 'a type which opens with its own markup has the box clear' );
  491. is( $types->{'bare.tx'}{inc_post_title}, 0, 'and the blocks it does not include are clear' );
  492. is( $types->{'bare.tx'}{inc_post_tags}, 0, 'both of them' );
  493. is( $types->{'bare.tx'}{body_form}, 'form_common.tx', 'and a single page body form is read back as one' );
  494. };
  495. subtest 'the types are handed to the page as JSON it cannot break out of' => sub {
  496. no warnings qw{once};
  497. my $spec = Trog::Routes::HTML::_wizard_sidecar(
  498. 'nasty', [], [], 'form_common.tx', '',
  499. { description => 'ends a script </script><script>alert(1)</script>', display => '<div>markup</div>' }
  500. );
  501. set_sidecars( 'nasty.json' => JSON::MaybeXS::encode_json($spec) );
  502. my $json = Trog::Routes::HTML::_wizard_types_json( ['nasty.tx'] );
  503. unlike( $json, qr/</, 'no bare < survives, so the script element cannot be closed early' );
  504. my $back = JSON::MaybeXS::decode_json($json);
  505. like( $back->{'nasty.tx'}{description}, qr{</script>}, 'while the text itself is intact once parsed' );
  506. is( $back->{'nasty.tx'}{display}, '<div>markup</div>', 'and so is the display template' );
  507. # A description is free text, but it still goes in a file.
  508. my $long = Trog::Routes::HTML::_wizard_description( 'x' x 9000 );
  509. ok( length($long) <= $Trog::Routes::HTML::wizard_description_max, 'a very long description is capped' );
  510. is( Trog::Routes::HTML::_wizard_description(), '', 'and no description at all is empty rather than undef' );
  511. is( Trog::Routes::HTML::_wizard_description( [ 'an', 'array' ] ), '', 'as is one that is not a string' );
  512. };
  513. subtest 'a canned block declares what it collects, and the types including it get it' => sub {
  514. set_components(
  515. 'preview.json' => sidecar(
  516. properties => {
  517. preview => { type => 'string', 'x-tcms-label' => 'Preview Image' },
  518. preview_file => { type => 'upload', 'x-tcms-label' => 'Preview Image', 'x-tcms-input' => 'file' },
  519. }
  520. )
  521. );
  522. # What the wizard writes for a type with 'Preview image upload' ticked: the
  523. # block spliced into the template, and a sidecar naming only the field
  524. # somebody actually typed into the form.
  525. my $spec = Trog::Routes::HTML::_wizard_sidecar(
  526. 'recipe',
  527. [
  528. {
  529. name => 'cook_time', type => 'number', label => 'Cook Time', placeholder => '45',
  530. required => 0, private => 0, indexed => 0, relation_form => '', relation_mode => 'one',
  531. },
  532. ],
  533. [qw{inc_preview inc_visibility inc_acls}],
  534. 'form_common.tx',
  535. '',
  536. { description => 'What it is for.', display => '', title_placeholder => '' },
  537. );
  538. set_sidecars(
  539. 'recipe.json' => JSON::MaybeXS::encode_json($spec),
  540. 'recipe.tx' => qq| : include "preview.tx";\n : include "form_common.tx";\n|,
  541. );
  542. is_deeply(
  543. Trog::DataModule::includes_for('recipe.tx'),
  544. [qw{preview.tx form_common.tx}],
  545. "the blocks a type splices in are read out of the template it renders"
  546. );
  547. my $schema = Trog::DataModule::schema_for('recipe.tx');
  548. ok( exists $schema->{properties}{preview_file}, "a block's fields land in the schema of every type that includes it" );
  549. ok( exists $schema->{properties}{cook_time}, "alongside the ones the type declares itself" );
  550. # The whole point: validate() drops every field the schema doesn't describe,
  551. # so until the block said what it collects, a generated type threw away the
  552. # preview image its own editor had just uploaded.
  553. my $post = {
  554. form => 'recipe.tx',
  555. title => 'Bread',
  556. preview_file => { tempname => '/tmp/nope', filename => 'loaf.jpg' },
  557. };
  558. is_deeply( [ Trog::DataModule::validate($post) ], [], "a post carrying one still validates" );
  559. ok( exists $post->{preview_file}, "and keeps it rather than having it filtered away" );
  560. # A block never gets to overrule the type that borrows it, nor the base
  561. # schema -- see the merge order in schema_for().
  562. set_components( 'preview.json' => sidecar( properties => { preview => { type => 'integer' }, title => { type => 'integer' } } ) );
  563. $schema = Trog::DataModule::schema_for('recipe.tx');
  564. is( $schema->{properties}{title}{type}, 'string', "and it cannot redefine a base post field" );
  565. };
  566. subtest 'the wizard tells a canned field apart from one somebody typed in' => sub {
  567. set_components(
  568. 'preview.json' => sidecar(
  569. properties => {
  570. preview => { type => 'string' },
  571. preview_file => { type => 'upload' },
  572. }
  573. )
  574. );
  575. # A hand-written type: it declares the block's fields itself, the way every
  576. # stock form does, and records nothing about which blocks it includes.
  577. set_sidecars(
  578. 'blog.json' => sidecar(
  579. properties => {
  580. preview => { type => 'string' },
  581. preview_file => { type => 'upload' },
  582. video_href => { type => 'string', 'x-tcms-input' => 'url', 'x-tcms-label' => 'Video' },
  583. }
  584. ),
  585. 'blog.tx' => qq| : include "preview.tx";\n : include "form_common.tx";\n|,
  586. # And one which declares a field of the same name without including the
  587. # block -- a datasource fills this one in, so it really is the type's.
  588. 'guests.json' => sidecar( properties => { preview => { type => 'string', 'x-tcms-label' => 'Console capture' } } ),
  589. 'guests.tx' => qq| : include "post_title.tx";\n|,
  590. );
  591. my $types = Trog::Routes::HTML::_wizard_types( [ 'blog.tx', 'guests.tx' ] );
  592. is( $types->{'blog.tx'}{inc_preview}, 1, "the box for a block the template includes comes back ticked" );
  593. is_deeply(
  594. [ map { $_->{name} } @{ $types->{'blog.tx'}{fields} } ],
  595. ['video_href'],
  596. "and what that block collects is not offered back as a custom field"
  597. );
  598. is( $types->{'guests.tx'}{inc_preview}, 0, "a type which does not include the block has the box clear" );
  599. is_deeply(
  600. [ map { $_->{name} } @{ $types->{'guests.tx'}{fields} } ],
  601. ['preview'],
  602. "and keeps the field of that name, which is its own rather than the block's"
  603. );
  604. };
  605. subtest '_kolon_safe defuses template syntax' => sub {
  606. my $safe = Trog::Routes::HTML::_kolon_safe(qq{<: \$post.id :>\n: include "evil.tx";});
  607. unlike( $safe, qr/</, "no angle brackets survive" );
  608. unlike( $safe, qr/[\r\n]/, "no newlines survive, so ':' can't start a directive" );
  609. is( Trog::Routes::HTML::_kolon_safe( [] ), '', "a repeated param can't sneak a ref through" );
  610. };
  611. done_testing();