Trog-Routes-HTML-series-lifecycle.t 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107
  1. #!/usr/bin/env perl
  2. # Stands up a genuinely fresh tCMS in a temp dir, then walks the loop a user
  3. # actually performs: register an admin, invent a post type in the wizard, and
  4. # for each content post type build a topbar series, confirm it lands in the
  5. # nav, add a child post and confirm the child renders on the series page.
  6. #
  7. # Verification goes through Trog::Routes::HTML::index() -- directly, or via
  8. # series() which delegates to it -- and matches on the returned HTML.
  9. use strict;
  10. use warnings;
  11. # FindBin MUST come first. $FindBin::Bin is derived from $0, which prove hands
  12. # us relatively, and it is computed once. chdir before this loads and every
  13. # module's `use FindBin::libs` resolves against the sandbox instead of the repo.
  14. use FindBin;
  15. use lib "$FindBin::Bin/../lib";
  16. use Test::More;
  17. use Cwd ();
  18. use Encode ();
  19. use File::Copy ();
  20. use File::Find ();
  21. use File::Path ();
  22. use File::Temp ();
  23. use Time::HiRes ();
  24. use URI::Escape ();
  25. use JSON::MaybeXS ();
  26. our ( $REPO, $ROOT, $OLDCWD );
  27. our %REPO_BEFORE;
  28. # name => (size, mtime) for every file under the repo dirs this test could
  29. # plausibly disturb. Cheap enough, and it is the only real proof of isolation.
  30. sub _snapshot {
  31. my ($dir) = @_;
  32. my %seen;
  33. File::Find::find(
  34. {
  35. no_chdir => 1,
  36. wanted => sub {
  37. return unless -f $File::Find::name;
  38. my @st = stat(_);
  39. $seen{$File::Find::name} = "$st[7]:$st[9]";
  40. },
  41. },
  42. $dir
  43. );
  44. return %seen;
  45. }
  46. sub _copy_tree {
  47. my ( $from, $to ) = @_;
  48. File::Path::make_path($to);
  49. File::Find::find(
  50. {
  51. no_chdir => 1,
  52. wanted => sub {
  53. my $rel = substr( $File::Find::name, length($from) );
  54. return unless length $rel;
  55. my $dst = "$to$rel";
  56. if ( -d $File::Find::name ) { File::Path::make_path($dst) }
  57. elsif ( -f $File::Find::name ) { File::Copy::copy( $File::Find::name, $dst ) or die "copy $File::Find::name: $!" }
  58. },
  59. },
  60. $from
  61. );
  62. return;
  63. }
  64. # Everything the sandbox needs, in one BEGIN. The Trog:: modules are require()d
  65. # at runtime below, which is unconditionally after every BEGIN -- so no later
  66. # edit can accidentally load them before the chdir. That matters: TCMS.pm runs
  67. # build_routes() at file scope and FlatFile.pm reads the tag index at file
  68. # scope, both against whatever cwd happens to be current.
  69. BEGIN {
  70. $REPO = Cwd::abs_path("$FindBin::Bin/..");
  71. $OLDCWD = Cwd::getcwd();
  72. %REPO_BEFORE = map { _snapshot("$REPO/$_") } qw{config data www/templates www/assets logs totp};
  73. $ROOT = File::Temp::tempdir( 'tcms-lifecycle-XXXXXX', TMPDIR => 1, CLEANUP => 0 );
  74. # Installer.mk's tree, plus upload-src for the file.tx fixture.
  75. File::Path::make_path(
  76. map { "$ROOT/$_" }
  77. qw{
  78. config schema data/files logs totp upload-src
  79. www/assets/private www/statics www/themes www/scripts
  80. }
  81. );
  82. # A real fresh install: get() looks for config/main.cfg, doesn't find one,
  83. # and falls through to the shipped default.
  84. File::Copy::copy( "$REPO/config/default.cfg", "$ROOT/config/default.cfg" ) or die $!;
  85. # Hardcoded paths in Auth.pm, TagIndex.pm and Log.pm -- not negotiable.
  86. File::Copy::copy( "$REPO/schema/$_", "$ROOT/schema/$_" ) or die $! for qw{auth.schema flatfile.schema log.schema};
  87. # COPY, don't symlink: post_wizard_save() writes into Trog::Themes::forms_dir(),
  88. # and a symlink would land the generated post type in the real repo.
  89. _copy_tree( "$REPO/www/templates", "$ROOT/www/templates" );
  90. # posts.tx pulls in the EmojiPicker component for an editor, and EmojiPicker
  91. # dies outright if this file is missing. Only category and emoji are read.
  92. open( my $fh, '>', "$ROOT/www/scripts/list.min.json" ) or die $!;
  93. print {$fh} '{"emojis":[{"category":"Smileys","emoji":"X"}]}';
  94. close $fh;
  95. # Text::Xslate computes its default cache dir from $HOME once, at load time.
  96. # Without this the sandbox writes compiled templates into the real ~/.xslate_cache.
  97. $ENV{HOME} = $ROOT;
  98. chdir($ROOT) or die "could not chdir to sandbox $ROOT: $!";
  99. }
  100. END {
  101. # Never rmtree the directory you are standing in.
  102. chdir($OLDCWD) if $OLDCWD;
  103. if ( $ENV{TCMS_TEST_KEEP} ) {
  104. diag("TCMS_TEST_KEEP set, sandbox left at $ROOT");
  105. }
  106. elsif ( $ROOT && -d $ROOT ) {
  107. # SQLite handles are file-lexical in Trog::SQLite and unreachable from
  108. # here; DBI disconnects at global destruction, after these are gone.
  109. eval { File::Path::remove_tree($ROOT) };
  110. }
  111. }
  112. diag("sandbox: $ROOT");
  113. require Trog::Log;
  114. Trog::Log::log_init( 'logs/tcms.log', 'info' ); # sets $LOGDIR, hence logs/log.db
  115. require Trog::Config;
  116. require Trog::Themes;
  117. require Trog::Data;
  118. require Trog::Auth;
  119. require Trog::SQLite::TagIndex;
  120. require Trog::Routes::HTML;
  121. require Trog::Routes::JSON;
  122. #--------------------------------------------------------------------------
  123. # A stand-in for the tPSGI object the router injects as $query->{tpsgi}.
  124. #--------------------------------------------------------------------------
  125. {
  126. package Test::TPSGI;
  127. sub new {
  128. my ( $class, %args ) = @_;
  129. return bless {
  130. callbacks => 0,
  131. renders => {},
  132. invalidated => [],
  133. restarts => 0,
  134. tpsgi_dir => Cwd::getcwd(),
  135. log_dir => 'logs',
  136. gid => $),
  137. verbose => 0,
  138. %args,
  139. }, $class;
  140. }
  141. sub INFO { 1 }
  142. sub DEBUG { 1 }
  143. sub WARN { 1 }
  144. sub ERROR { 1 }
  145. sub CRIT { 1 }
  146. sub ALERT { 1 }
  147. sub EMERG { 1 }
  148. sub FATAL { 1 }
  149. sub see_also { return [ 303, [ 'Location' => $_[1], 'Content-Length' => 0 ], [''] ] }
  150. sub redirect { return [ 302, [ 'Location' => $_[1], 'Content-Length' => 0 ], [''] ] }
  151. sub redirect_permanent { return [ 301, [ 'Location' => $_[1], 'Content-Length' => 0 ], [''] ] }
  152. sub _reply { return [ $_[1], [ 'Content-type' => 'text/html' ], [ defined $_[2] ? $_[2] : '' ] ] }
  153. sub ok { return $_[0]->_reply( 200, $_[2] ) }
  154. sub notfound { return $_[0]->_reply( 404, $_[2] // 'Not Found' ) }
  155. sub forbidden { return $_[0]->_reply( 403, $_[2] // 'Forbidden' ) }
  156. sub badrequest { return $_[0]->_reply( 400, $_[2] // 'Bad Request' ) }
  157. sub error { return $_[0]->_reply( 500, $_[2] // 'Error' ) }
  158. sub serve { return [ 200, [], [''] ] }
  159. # These two must be inert.
  160. #
  161. # add_post_close_callback is the ONLY path by which Trog::Renderer and
  162. # post_save reach save_render()/invalidate_renders(). Dropping the callback
  163. # on the floor is what guarantees this test never writes into www/statics,
  164. # whatever the renderer's own skip-save logic decides.
  165. sub add_post_close_callback { $_[0]{callbacks}++; return 1 }
  166. # The real one is `kill 'HUP', getppid`. Under prove, that is prove.
  167. sub signal_restart_parent { $_[0]{restarts}++; return 1 }
  168. sub invalidate_renders { push @{ $_[0]{invalidated} }, $_[1]; return 1 }
  169. sub invalidate_render { push @{ $_[0]{invalidated} }, [ @_[ 1 .. $#_ ] ]; return 1 }
  170. sub save_render { $_[0]{renders}{"$_[1]:$_[2]"} = $_[3]; return 1 }
  171. }
  172. our $TPSGI = Test::TPSGI->new();
  173. our $ADMIN_USER = 'specadmin';
  174. our $ADMIN_DISPLAY = 'Spec Admin';
  175. our $ADMIN_EMAIL = 'specadmin@example.com';
  176. our $ADMIN_PASS = 'spec-password';
  177. #--------------------------------------------------------------------------
  178. # Harness
  179. #--------------------------------------------------------------------------
  180. # Always build a fresh query: posts() pushes onto user_acls, and series()
  181. # rewrites route/aclname/tag/in_series/primary_post in place.
  182. sub _query {
  183. my (%over) = @_;
  184. my %q = (
  185. route => '/',
  186. method => 'GET',
  187. scheme => 'http', # Renderer::Base compares this with no undef guard
  188. domain => 'tcms.test',
  189. start => [ Time::HiRes::gettimeofday() ], # tv_interval() dies on anything else
  190. deflate => 0,
  191. streaming => 0,
  192. ranges => [],
  193. last_fetched => undef,
  194. has_query => 0,
  195. social_meta => 0,
  196. acls => [],
  197. user_acls => [],
  198. body => undef,
  199. tpsgi => $TPSGI,
  200. %over,
  201. );
  202. $q{fullpath} //= $q{route};
  203. return \%q;
  204. }
  205. sub _anon { return _query( user => undef, user_acls => [], @_ ) }
  206. sub _admin { return _query( user => $ADMIN_USER, user_acls => ['admin'], @_ ) }
  207. # Returns ($code, $body, $error). Never dies, so one bad post type cannot take
  208. # the rest of the file with it -- which matters because a failed render inside
  209. # index() dies rather than returning a 500 (there is no www/templates/html/500.tx).
  210. sub _render {
  211. my ( $query, $how ) = @_;
  212. $how ||= \&Trog::Routes::HTML::index;
  213. my $res = eval { $how->($query) };
  214. return ( 0, '', "died: $@" ) if !$res;
  215. return ( 0, '', 'returned a ' . ( ref($res) || 'plain scalar' ) ) if ref $res ne 'ARRAY';
  216. my ( $code, $headers, $body ) = @$res;
  217. $body = ref $body eq 'ARRAY' ? join( '', @$body ) : ( $body // '' );
  218. return ( $code, Encode::decode_utf8($body), '', $headers );
  219. }
  220. # FlatFile snapshots the tag list at load time and then filters each query's
  221. # tags against it IN PLACE -- so a tag created later isn't merely unindexed, it
  222. # is deleted from the query, and the filter silently degrades to "every public
  223. # post". Production gets away with it because a save HUPs the parent and the
  224. # worker re-execs. We have to do it by hand.
  225. sub _reindex {
  226. no warnings 'once';
  227. @Trog::Data::FlatFile::tags = Trog::SQLite::TagIndex::tags();
  228. %Trog::Data::FlatFile::posts_by_tag = ();
  229. return;
  230. }
  231. sub _data { return Trog::Data->new( Trog::Config::get() ) }
  232. # categories.tx renders into <span id="categories">. Scope to it -- index.tx
  233. # emits other class="topbar" anchors outside that span.
  234. sub _topbar_titles {
  235. my ($body) = @_;
  236. my ($span) = $body =~ m{<span id="categories">(.*?)</span>}s;
  237. return () unless defined $span;
  238. return $span =~ m{class="topbar">([^<]*)</a>}g;
  239. }
  240. # post_title.tx emits exactly one of these per displayed post.
  241. sub _post_count {
  242. my $n = () = $_[0] =~ m{<h3 class='blogtitles'>}g;
  243. return $n;
  244. }
  245. # The rendered page is ~40KB and mostly JavaScript. Show the content well.
  246. sub _kontent {
  247. my ($body) = @_;
  248. my ($k) = $body =~ m{<div id="kontent" class="kontained">(.*?)<div id="rightbar"}s;
  249. $k //= $body;
  250. $k =~ s/<script\b.*?<\/script>//gs;
  251. return length($k) > 2500 ? substr( $k, 0, 2500 ) . "\n...[truncated]" : $k;
  252. }
  253. # Save through post_save() rather than $data->add(): add() dies with an
  254. # arrayref of validator errors, whereas post_save catches them and hands back a
  255. # 400 with the field-level detail in the body -- which is the single most
  256. # useful thing to see when a fixture is wrong.
  257. sub _save_post {
  258. my ( $label, %post ) = @_;
  259. my $to = delete $post{to};
  260. my $res = eval { Trog::Routes::HTML::post_save( _admin( route => '/post/save', method => 'POST', to => $to, %post ) ) };
  261. if ( !$res || ref $res ne 'ARRAY' ) {
  262. fail("$label: saved");
  263. diag( $@ || 'post_save returned nothing' );
  264. return undef;
  265. }
  266. my ( $code, $headers, $body ) = @$res;
  267. my %h = @{ $headers || [] };
  268. # Both outcomes redirect now, so the status alone proves nothing -- the
  269. # outcome is in the query string post_save hands to the destination.
  270. if ( $code != 303 || ( $h{Location} // '' ) =~ m/savefailed=/ ) {
  271. fail("$label: saved");
  272. diag( "post_save returned $code, Location: " . ( $h{Location} // '(none)' ) );
  273. diag( join( '', @{ $body || [''] } ) ) if $body && @$body;
  274. return undef;
  275. }
  276. pass("$label: saved");
  277. _reindex(); # mandatory: see the comment on _reindex
  278. my $saved = _find_post( $post{title} );
  279. ok( $saved, "$label: readable back out of the datastore" ) or return undef;
  280. return $saved;
  281. }
  282. sub _find_post {
  283. my ($title) = @_;
  284. # filter() short-circuits on title; the admin acl skips the visibility filter.
  285. my @posts = _data()->get( title => $title, acls => ['admin'], limit => 0 );
  286. return $posts[0];
  287. }
  288. #--------------------------------------------------------------------------
  289. subtest 'the sandbox is what we are actually running against' => sub {
  290. is( Cwd::getcwd(), Cwd::abs_path($ROOT), 'cwd is the sandbox' );
  291. ok( -d 'data/files', 'datastore dir exists' );
  292. ok( -f 'config/default.cfg', 'config was seeded' );
  293. ok( !-f 'config/main.cfg', 'and there is no main.cfg, so we fall through to the default' );
  294. my $conf = Trog::Config::get();
  295. is( $conf->param('general.data_model'), 'FlatFile', 'config resolves inside the sandbox' );
  296. like( Trog::Themes::forms_dir(), qr/^www\/templates/, 'forms dir is relative, hence sandboxed' );
  297. ok( -d Cwd::abs_path( Trog::Themes::forms_dir() ), 'and it exists' );
  298. like( Cwd::abs_path( Trog::Themes::forms_dir() ), qr/^\Q$ROOT\E/, 'and it is under the sandbox, not the repo' );
  299. };
  300. subtest 'registering the first admin bootstraps the install' => sub {
  301. ok( !-f 'config/has_users', 'no users yet, so login() is in register mode' );
  302. my ( $code, $body, $err, $headers ) = _render(
  303. _anon(
  304. route => '/login',
  305. method => 'POST',
  306. username => $ADMIN_USER,
  307. display_name => $ADMIN_DISPLAY,
  308. contact_email => $ADMIN_EMAIL,
  309. password => $ADMIN_PASS,
  310. to => '/',
  311. ),
  312. \&Trog::Routes::HTML::login,
  313. );
  314. is( $code, 200, 'login() rendered' ) or diag($err);
  315. my %h = @{ $headers || [] };
  316. like( $h{'Set-Cookie'} // '', qr/^tcmslogin=[0-9a-f-]{36};/, 'a session cookie came back' );
  317. ok( -f 'config/has_users', 'registration is now closed' );
  318. is_deeply( Trog::Auth::acls4user($ADMIN_USER), ['admin'], 'the new user is an admin' );
  319. _reindex();
  320. my @seeded = _data()->get( acls => ['admin'], limit => 0 );
  321. is( scalar @seeded, 4, 'the four seed posts were written' )
  322. or diag( 'got: ' . join( ', ', map { "$_->{title} ($_->{form})" } @seeded ) );
  323. };
  324. subtest 'the post wizard invents a new post type' => sub {
  325. my %wizard = (
  326. name => 'spec_widget',
  327. title_placeholder => 'Widget Name',
  328. body_form => 'form_common.tx',
  329. wrapper => 1,
  330. inc_post_title => 1,
  331. inc_post_tags => 1,
  332. inc_title_input => 1,
  333. inc_visibility => 1,
  334. inc_tags => 1,
  335. inc_aliases => 1,
  336. param_name => ['flavor'],
  337. param_type => ['text'],
  338. param_label => ['Flavor'],
  339. param_placeholder => ['Strawberry'],
  340. param_required => [0],
  341. display => q{<div class="postData responsive-text" id="postData-<: $post.id :>">} . q{<span class="spec-flavor"><: $post.flavor :></span>} . q{<: render_it($post.data) | mark_raw :></div>},
  342. );
  343. my ( $code, $body, $err ) = _render(
  344. _admin( route => '/admin/wyzzerdd/save', method => 'POST', %wizard ),
  345. \&Trog::Routes::HTML::post_wizard_save,
  346. );
  347. is( $code, 200, 'wizard save rendered' ) or diag($err);
  348. ok( -f 'www/templates/html/components/forms/spec_widget.tx', 'the template was written' );
  349. ok( -f 'www/templates/html/components/forms/spec_widget.json', 'the schema sidecar was written' );
  350. like( $body, qr{<li>spec_widget\.tx</li>}, 'and the new type is listed back to us' );
  351. # This is the assertion that the sandbox is real: a symlinked template tree
  352. # would have put these in the developer's actual checkout.
  353. ok( !-e "$REPO/www/templates/html/components/forms/spec_widget.tx", 'nothing was written into the repo' );
  354. # The relation controls have to be present in every row and always submit,
  355. # or the parallel param_* arrays de-align server side.
  356. like( $body, qr/name="param_relation_form"/, 'the relation target select is in the row template' );
  357. like( $body, qr/name="param_relation_mode"/, 'so is the relation mode select' );
  358. like( $body, qr/<option value="relation">/, 'and relation is offered as a field type' );
  359. # A series can ask for its children to be tiled. A generated type has to
  360. # carry that on its wrapper like the hand-written forms do, or it is the
  361. # one kind of post that silently ignores the setting.
  362. my $generated = Path::Tiny->new('www/templates/html/components/forms/spec_widget.tx')->slurp_utf8;
  363. # Single quoted: the wrapper is Kolon source, so every sigil in it is
  364. # literal and must not be interpolated by the test that checks for it.
  365. my $wrapper = q{<div class="post <: $style :> <: $tiled ? 'tile' : '' :>">};
  366. ok( index( $generated, $wrapper ) >= 0, 'the generated wrapper carries the tile class when the series asks for it' )
  367. or diag( "wanted: $wrapper\ngot: " . ( split( /\n/, $generated ) )[1] );
  368. # Every post has a title, a visibility and acls. The wizard used to let a
  369. # type opt out of collecting them, which is how a hypervisor post ended up
  370. # stored with no visibility and an undef in its tags.
  371. foreach my $required ( 'visibility.tx', 'acls.tx' ) {
  372. like( $generated, qr/\Q: include "$required";\E/, "$required is included whether or not it was asked for" );
  373. }
  374. like( $generated, qr/name="title"/, 'and so is the title input' );
  375. foreach my $gone (qw{inc_title_input inc_visibility inc_acls}) {
  376. unlike( $body, qr/name="\Q$gone\E"/, "the wizard no longer offers '$gone' as a choice" );
  377. }
  378. like( $body, qr/name="param_private"/, 'and it offers per-field privacy' );
  379. like( $body, qr/name="datasource"/, 'and a datasource to draw the posts from' );
  380. like( $body, qr/Trog::DataSource::Virt/, 'listing the ones that exist' );
  381. };
  382. subtest 'a datasource-backed type gets no editor' => sub {
  383. # A datasource whose posts are built rather than written has nothing behind
  384. # a form to save, so generating one would produce an editor that writes
  385. # real posts to sit alongside the synthesized ones.
  386. my ( $code, $body, $err ) = _render(
  387. _admin(
  388. route => '/admin/wyzzerdd/save',
  389. method => 'POST',
  390. name => 'spec_sourced',
  391. datasource => 'Trog::DataSource::Virt',
  392. body_form => 'form_common.tx',
  393. wrapper => 1,
  394. inc_post_title => 1,
  395. display => q{<div class="s"><: $post.title :></div>},
  396. ),
  397. \&Trog::Routes::HTML::post_wizard_save,
  398. );
  399. is( $code, 200, 'the type was created' ) or diag($err);
  400. my $generated = Path::Tiny->new('www/templates/html/components/forms/spec_sourced.tx')->slurp_utf8;
  401. unlike( $generated, qr{action="/post/save"}, 'no editor was generated' );
  402. unlike( $generated, qr/\$can_edit/, 'and nothing guards one' );
  403. like( $generated, qr/class="s"/, 'but the display half is there' );
  404. my $sidecar = JSON::MaybeXS::decode_json( Path::Tiny->new('www/templates/html/components/forms/spec_sourced.json')->slurp_utf8 );
  405. is( $sidecar->{'x-tcms-datasource'}, 'Trog::DataSource::Virt', 'and the sidecar records the datasource' );
  406. # The same type without one keeps its editor.
  407. _render(
  408. _admin(
  409. route => '/admin/wyzzerdd/save',
  410. method => 'POST',
  411. name => 'spec_stored',
  412. body_form => 'form_common.tx',
  413. wrapper => 1,
  414. inc_post_title => 1,
  415. display => q{<div class="s"><: $post.title :></div>},
  416. ),
  417. \&Trog::Routes::HTML::post_wizard_save,
  418. );
  419. my $stored = Path::Tiny->new('www/templates/html/components/forms/spec_stored.tx')->slurp_utf8;
  420. like( $stored, qr{action="/post/save"}, 'a type on the datastore still gets one' );
  421. # The name is require()d later, so it has to be one we found.
  422. ( $code, $body ) = _render(
  423. _admin( route => '/admin/wyzzerdd/save', method => 'POST', name => 'spec_bogus', datasource => 'Evil::Module' ),
  424. \&Trog::Routes::HTML::post_wizard_save,
  425. );
  426. like( $body, qr/not a datasource I can find/, 'a datasource we did not find is refused' );
  427. ok( !-e 'www/templates/html/components/forms/spec_bogus.tx', 'and nothing was written' );
  428. };
  429. subtest 'a field can be declared editors-only' => sub {
  430. my ( $code, $body, $err ) = _render(
  431. _admin(
  432. route => '/admin/wyzzerdd/save',
  433. method => 'POST',
  434. name => 'spec_secretive',
  435. body_form => 'form_common.tx',
  436. wrapper => 1,
  437. inc_post_title => 1,
  438. inc_tags => 1,
  439. param_name => [ 'shown', 'hidden' ],
  440. param_type => [ 'text', 'text' ],
  441. param_label => [ 'Shown', 'Hidden' ],
  442. param_placeholder => [ '', '' ],
  443. param_required => [ 0, 0 ],
  444. param_private => [ 0, 1 ],
  445. param_relation_form => [ 'blog.tx', 'blog.tx' ],
  446. param_relation_mode => [ 'one', 'one' ],
  447. # Deliberately unguarded: declaring the field private is supposed
  448. # to be enough, so an author does not have to remember.
  449. display => q{<div class="s"><: $post.shown :></div><div class="h"><: $post.hidden :></div>},
  450. ),
  451. \&Trog::Routes::HTML::post_wizard_save,
  452. );
  453. is( $code, 200, 'the type was created' ) or diag($err);
  454. my $sidecar = JSON::MaybeXS::decode_json( Path::Tiny->new('www/templates/html/components/forms/spec_secretive.json')->slurp_utf8 );
  455. ok( $sidecar->{properties}{hidden}{'x-tcms-private'}, 'the private field is marked so' );
  456. ok( !exists $sidecar->{properties}{shown}{'x-tcms-private'}, 'and a public one carries no flag at all' );
  457. _reindex();
  458. _make_series( 'spec_secretive', 'specsecretive', 'spec_secretive.tx', 'Spec Secretive Series', no_topbar => 1 ) or return;
  459. my $child = _save_post(
  460. 'spec_secretive child',
  461. form => 'spec_secretive.tx',
  462. title => 'Spec Secretive Child',
  463. shown => 'public value',
  464. hidden => 'private value',
  465. visibility => 'public',
  466. tags => ['specsecretive'],
  467. to => '/specsecretive',
  468. ) or return;
  469. is( $child->{hidden}, 'private value', 'the value is stored like any other' );
  470. # An editor sees both.
  471. my ( $acode, $abody ) = _render( _admin( route => '/specsecretive' ), \&Trog::Routes::HTML::series );
  472. is( $acode, 200, 'the series renders for an admin' );
  473. like( $abody, qr{<div class="h">private value</div>}, 'who sees the private field' );
  474. # A logged out reader sees only the public one, without the template
  475. # having guarded anything.
  476. my ( $ncode, $nbody ) = _render( _anon( route => '/specsecretive' ), \&Trog::Routes::HTML::series );
  477. is( $ncode, 200, 'and for everyone else' );
  478. like( $nbody, qr{<div class="s">public value</div>}, 'who still sees the public field' );
  479. unlike( $nbody, qr/private value/, 'but not the private one' );
  480. };
  481. #--------------------------------------------------------------------------
  482. # The matrix.
  483. #
  484. # Per type: build a topbar series whose child_form is that type, check it shows
  485. # up in the nav, add a child post, check the child renders on the series page.
  486. #
  487. # Everything is verified ANONYMOUSLY. can_edit is then false, so the editor
  488. # half of each form never renders and a title appears exactly once -- which is
  489. # what makes like($body, qr/$title/) mean anything. It also sidesteps the
  490. # /secure prefixing that both _post_helper and categories.tx apply when a user
  491. # is set.
  492. #--------------------------------------------------------------------------
  493. sub _make_series {
  494. my ( $label, $aclname, $child_form, $title, %opt ) = @_;
  495. # _get_series caps the bar at 10 and the seeds already use two, so only the
  496. # series whose topbar behaviour we actually care about get tagged.
  497. my @tags = $opt{no_topbar} ? ('series') : ( 'series', 'topbar' );
  498. my $series = _save_post(
  499. "$label series",
  500. form => 'series.tx',
  501. title => $title,
  502. aclname => $aclname, # required by series.json
  503. child_form => $child_form, # required by series.json
  504. local_href => "/$aclname",
  505. href => "/$aclname",
  506. data => "$title subhead",
  507. callback => 'Trog::Routes::HTML::series',
  508. visibility => 'public',
  509. tags => \@tags,
  510. tiled => 0,
  511. to => '/',
  512. ) or return undef;
  513. return $series if $opt{no_topbar};
  514. # The topbar comes from _get_series(), which index() renders through
  515. # categories.tx. Check it on / -- the series has no children yet, and
  516. # posts() 404s on an empty series.
  517. my ( $code, $body, $err ) = _render( _anon( route => '/' ) );
  518. is( $code, 200, "$label: / renders" ) or diag($err);
  519. my @titles = _topbar_titles($body);
  520. ok( ( grep { $_ eq $title } @titles ), "$label: series is in the topbar" )
  521. or diag( 'topbar was: ' . join( ', ', @titles ) );
  522. return $series;
  523. }
  524. sub _series_page {
  525. my ( $label, $aclname, $series_title, $expected_posts ) = @_;
  526. my ( $code, $body, $err ) = _render( _anon( route => "/$aclname" ), \&Trog::Routes::HTML::series );
  527. is( $code, 200, "$label: series page renders" ) or do { diag($err); return '' };
  528. like( $body, qr{<title>[^<]*\Q$series_title\E}, "$label: series page is the right series" );
  529. is( _post_count($body), $expected_posts, "$label: exactly $expected_posts post(s) listed" )
  530. or diag( _kontent($body) );
  531. return $body;
  532. }
  533. # Entities first: the invoice type resolves payee/payor against existing public
  534. # entities.tx posts, so those have to be in the datastore before we get there.
  535. our ( $PAYEE, $PAYOR );
  536. subtest 'entities' => sub {
  537. my $title = 'Spec Entities Series';
  538. _make_series( 'entities', 'specentities', 'entities.tx', $title ) or return;
  539. $PAYEE = _save_post(
  540. 'entities payee child',
  541. form => 'entities.tx',
  542. title => 'Spec Payee Entity',
  543. data => 'Acme Payments LLC, 1 Road, Metropolis',
  544. payment_method => 'ACH',
  545. payment_details => 'Routing 0000 Account 1111',
  546. visibility => 'public',
  547. tags => ['specentities'],
  548. to => '/specentities',
  549. ) or return;
  550. $PAYOR = _save_post(
  551. 'entities payor child',
  552. form => 'entities.tx',
  553. title => 'Spec Payor Entity',
  554. data => 'Wile E Coyote, PO Box 9',
  555. payment_method => 'Carrier Pigeon',
  556. payment_details => 'none',
  557. visibility => 'public',
  558. tags => ['specentities'],
  559. to => '/specentities',
  560. ) or return;
  561. my $body = _series_page( 'entities', 'specentities', $title, 2 ) or return;
  562. like( $body, qr{id="postData-\Q$PAYEE->{id}\E"}, 'payee body rendered' );
  563. like( $body, qr/Acme Payments LLC/, 'payee data rendered' );
  564. like( $body, qr/Wile E Coyote/, 'payor data rendered' );
  565. # entity_details.tx is included only in the editor half, so these are stored
  566. # but never displayed. Pinning that so a template change is noticed.
  567. unlike( $body, qr/Carrier Pigeon/, 'payment details are not shown to anonymous readers' );
  568. is( _find_post('Spec Payee Entity')->{payment_method}, 'ACH', 'but payment_method did survive the schema' );
  569. };
  570. subtest 'blog' => sub {
  571. my $title = 'Spec Blog Series';
  572. _make_series( 'blog', 'specblog', 'blog.tx', $title ) or return;
  573. my $child = _save_post(
  574. 'blog child',
  575. form => 'blog.tx',
  576. title => 'Spec Blog Child',
  577. data => 'Spec blog body text.',
  578. visibility => 'public',
  579. tags => ['specblog'],
  580. to => '/specblog',
  581. ) or return;
  582. my $body = _series_page( 'blog', 'specblog', $title, 1 ) or return;
  583. like( $body, qr/Spec Blog Child/, 'child title rendered' );
  584. like( $body, qr{href='/posts/\Q$child->{id}\E'}, 'child permalink rendered' );
  585. like( $body, qr{id="postData-\Q$child->{id}\E"}, 'child body block rendered' );
  586. like( $body, qr/Spec blog body text\./, 'child body text rendered' );
  587. unlike( $body, qr/Spec Payee Entity/, 'no bleed from the entities series' );
  588. };
  589. subtest 'microblog' => sub {
  590. my $title = 'Spec Microblog Series';
  591. _make_series( 'microblog', 'specmicroblog', 'microblog.tx', $title ) or return;
  592. my $child = _save_post(
  593. 'microblog child',
  594. form => 'microblog.tx',
  595. title => 'Spec Microblog Child',
  596. href => 'https://example.com/spec',
  597. data => 'Spec microblog body.',
  598. visibility => 'public',
  599. tags => ['specmicroblog'],
  600. to => '/specmicroblog',
  601. ) or return;
  602. my $body = _series_page( 'microblog', 'specmicroblog', $title, 1 ) or return;
  603. like( $body, qr{href='https://example\.com/spec' >Spec Microblog Child</a>}, 'title links out to href' );
  604. like( $body, qr{id="postData-\Q$child->{id}\E"}, 'body block rendered' );
  605. like( $body, qr/Spec microblog body\./, 'body text rendered' );
  606. };
  607. subtest 'file' => sub {
  608. my $title = 'Spec File Series';
  609. _make_series( 'file', 'specfile', 'file.tx', $title ) or return;
  610. # _handle_upload MOVES the file, so it has to be created fresh here.
  611. my $src = "$ROOT/upload-src/spec-upload.txt";
  612. open( my $fh, '>', $src ) or die $!;
  613. print {$fh} "spec upload contents\n";
  614. close $fh;
  615. my $child = _save_post(
  616. 'file child',
  617. form => 'file.tx',
  618. title => 'Spec File Child',
  619. data => 'Spec file body.',
  620. file => { tempname => $src, filename => 'spec-upload.txt' },
  621. visibility => 'public',
  622. tags => ['specfile'],
  623. to => '/specfile',
  624. ) or return;
  625. ok( !-e $src, 'the upload was moved out of its temp location, not copied' );
  626. ok( -f "www/assets/$child->{id}.spec-upload.txt", 'and it landed in www/assets' );
  627. my $body = _series_page( 'file', 'specfile', $title, 1 ) or return;
  628. like( $body, qr{href='/assets/\Q$child->{id}\E\.spec-upload\.txt'}, 'title links to the asset' );
  629. like( $body, qr{id="postData-\Q$child->{id}\E"}, 'body block carries a unique id, like every other form' );
  630. like( $body, qr/Spec file body\./, 'body text rendered' );
  631. # This form used to emit <div class="postData" id="postData" class="responsive-text">
  632. # -- a duplicated class attribute, and an id shared by every file post on
  633. # the page. Neither should come back.
  634. unlike( $body, qr{<div class="postData" id="postData"}, 'no duplicated class attribute' );
  635. # text/plain, so none of the media branches fire.
  636. unlike( $body, qr/<video/, 'no video block for a text file' );
  637. unlike( $body, qr/<audio/, 'no audio block either' );
  638. };
  639. subtest 'presentation' => sub {
  640. my $title = 'Spec Presentation Series';
  641. _make_series( 'presentation', 'specpresentation', 'presentation.tx', $title ) or return;
  642. my $child = _save_post(
  643. 'presentation child',
  644. form => 'presentation.tx',
  645. title => 'Spec Presentation Child',
  646. data => [ 'Slide one body.', 'Slide two body.' ],
  647. data_is_array => 1,
  648. visibility => 'public',
  649. tags => ['specpresentation'],
  650. to => '/specpresentation',
  651. ) or return;
  652. is_deeply( $child->{data}, [ 'Slide one body.', 'Slide two body.' ], 'the multi-page data round-tripped as an array' );
  653. my $body = _series_page( 'presentation', 'specpresentation', $title, 1 ) or return;
  654. # Slides only render under nochrome; the series page just links to the deck.
  655. like( $body, qr{<a href="/posts/\Q$child->{id}\E\?embed=1&nochrome=1">Click Here to view</a>}, 'deck link rendered' );
  656. unlike( $body, qr/Slide one body\./, 'slides themselves are not rendered inline' );
  657. };
  658. subtest 'invoice' => sub {
  659. my $title = 'Spec Invoice Series';
  660. _make_series( 'invoice', 'specinvoice', 'invoice.tx', $title ) or return;
  661. my $child = _save_post(
  662. 'invoice child',
  663. form => 'invoice.tx',
  664. title => 'Spec Invoice Child',
  665. data => [ "Widget assembly\nPrice: \$420", "Shipping\nPrice: \$80" ],
  666. data_is_array => 1,
  667. payee => $PAYEE->{id},
  668. payor => $PAYOR->{id},
  669. due_days => 30,
  670. visibility => 'public',
  671. tags => ['specinvoice'],
  672. to => '/specinvoice',
  673. ) or return;
  674. my $body = _series_page( 'invoice', 'specinvoice', $title, 1 ) or return;
  675. like( $body, qr/Invoice ID# \Q$child->{id}\E/, 'invoice header rendered' );
  676. # These two only resolve because the entities subtest ran first and left
  677. # public entities.tx posts behind for the enrich hook to find.
  678. like( $body, qr/Acme Payments LLC/, 'payee entity resolved' );
  679. like( $body, qr/Wile E Coyote/, 'payor entity resolved' );
  680. like( $body, qr/ACH/, 'payee payment method pulled through' );
  681. like( $body, qr/Widget assembly/, 'line items rendered' );
  682. like( $body, qr/Total: \$500/, 'total summed from the line item prices' );
  683. };
  684. subtest 'spec_widget (the wizard-built type)' => sub {
  685. my $title = 'Spec Widget Series';
  686. _make_series( 'spec_widget', 'specwidget', 'spec_widget.tx', $title ) or return;
  687. my $child = _save_post(
  688. 'spec_widget child',
  689. form => 'spec_widget.tx',
  690. title => 'Spec Widget Child',
  691. data => 'Spec widget body.',
  692. flavor => 'Strawberry',
  693. bogus_field => 'nope',
  694. visibility => 'public',
  695. tags => ['specwidget'],
  696. to => '/specwidget',
  697. ) or return;
  698. is( $child->{flavor}, 'Strawberry', 'the custom field survived validation' );
  699. ok( !exists $child->{bogus_field}, 'an undeclared field was still stripped' );
  700. my $body = _series_page( 'spec_widget', 'specwidget', $title, 1 ) or return;
  701. # The payoff: this can only render if the wizard wrote spec_widget.json,
  702. # schema_for merged it over the base post schema, and validate() therefore
  703. # kept 'flavor' instead of deleting it as an unknown key.
  704. like( $body, qr{<span class="spec-flavor">Strawberry</span>}, 'the custom field rendered on the page' );
  705. like( $body, qr/Spec widget body\./, 'and the body came through the generated template' );
  706. };
  707. subtest 'a wizard-built type can depend on another type' => sub {
  708. # The type we will point at. The relation is what is under test, so keep
  709. # the target itself boring.
  710. my ( $code, $body, $err ) = _render(
  711. _admin(
  712. route => '/admin/wyzzerdd/save',
  713. method => 'POST',
  714. name => 'spec_target',
  715. body_form => 'form_common.tx',
  716. wrapper => 1,
  717. inc_post_title => 1,
  718. inc_title_input => 1,
  719. inc_visibility => 1,
  720. inc_tags => 1,
  721. display => q{<div><: render_it($post.data) | mark_raw :></div>},
  722. ),
  723. \&Trog::Routes::HTML::post_wizard_save,
  724. );
  725. is( $code, 200, 'target type created' ) or diag($err);
  726. # ...and the type that depends on it: one picked by id, one pulling in the
  727. # whole set.
  728. ( $code, $body, $err ) = _render(
  729. _admin(
  730. route => '/admin/wyzzerdd/save',
  731. method => 'POST',
  732. name => 'spec_relator',
  733. body_form => 'form_common.tx',
  734. wrapper => 1,
  735. inc_post_title => 1,
  736. inc_title_input => 1,
  737. inc_visibility => 1,
  738. inc_tags => 1,
  739. param_name => [ 'chosen', 'everything' ],
  740. param_type => [ 'relation', 'relation' ],
  741. param_label => [ 'Chosen One', 'All Of Them' ],
  742. param_placeholder => [ '', '' ],
  743. param_required => [ 0, 0 ],
  744. param_relation_form => [ 'spec_target.tx', 'spec_target.tx' ],
  745. param_relation_mode => [ 'one', 'all' ],
  746. display => q{<div class="rel"><span class="chosen"><: $post.chosen_post.title :></span>} . q{<: for $post.everything -> $t { :><span class="each"><: $t.title :></span><: } :></div>},
  747. ),
  748. \&Trog::Routes::HTML::post_wizard_save,
  749. );
  750. is( $code, 200, 'relating type created' ) or diag($err);
  751. my $sidecar = JSON::MaybeXS::decode_json( Path::Tiny->new('www/templates/html/components/forms/spec_relator.json')->slurp_utf8 );
  752. # 'one' is a field the post stores; 'all' is not a field at all.
  753. is( $sidecar->{properties}{chosen}{type}, 'relation', 'the picked relation is a stored property' );
  754. is( $sidecar->{properties}{chosen}{'x-tcms-relation-form'}, 'spec_target.tx', 'naming its target type' );
  755. ok( !exists $sidecar->{properties}{everything}, "the 'all' relation stores nothing" );
  756. is_deeply(
  757. $sidecar->{'x-tcms-relations'},
  758. {
  759. chosen_post => { form => 'spec_target.tx', from => 'chosen' },
  760. everything => { form => 'spec_target.tx' },
  761. },
  762. 'and both are declared for resolution at render'
  763. );
  764. # The relation pseudo-type has to become a real one before validation, or
  765. # every relation field would be stripped as an unknown type.
  766. is(
  767. Trog::DataModule::schema_for('spec_relator.tx')->{properties}{chosen}{type},
  768. 'string', "'relation' expands to a real schema type"
  769. );
  770. _reindex();
  771. # Now exercise it end to end.
  772. _make_series( 'spec_target', 'spectarget', 'spec_target.tx', 'Spec Target Series', no_topbar => 1 ) or return;
  773. my $target = _save_post(
  774. 'spec_target child',
  775. form => 'spec_target.tx',
  776. title => 'Spec Target Post',
  777. data => 'Spec target body.',
  778. visibility => 'public',
  779. tags => ['spectarget'],
  780. to => '/spectarget',
  781. ) or return;
  782. _make_series( 'spec_relator', 'specrelator', 'spec_relator.tx', 'Spec Relator Series', no_topbar => 1 ) or return;
  783. my $relator = _save_post(
  784. 'spec_relator child',
  785. form => 'spec_relator.tx',
  786. title => 'Spec Relator Post',
  787. data => 'Spec relator body.',
  788. chosen => $target->{id},
  789. visibility => 'public',
  790. tags => ['specrelator'],
  791. to => '/specrelator',
  792. ) or return;
  793. is( $relator->{chosen}, $target->{id}, 'the referenced id survived validation' );
  794. my $page = _series_page( 'spec_relator', 'specrelator', 'Spec Relator Series', 1 ) or return;
  795. # Both halves of the relation resolved: the one we picked, and the set.
  796. like( $page, qr{<span class="chosen">Spec Target Post</span>}, 'the picked post resolved into the page' );
  797. like( $page, qr{<span class="each">Spec Target Post</span>}, 'and so did the whole set' );
  798. };
  799. subtest '/api/posts_of_form feeds the relation picker' => sub {
  800. my $target = _find_post('Spec Target Post');
  801. ok( $target, 'the target post is there to be listed' ) or return;
  802. my $res = Trog::Routes::JSON::posts_of_form( _admin( route => '/api/posts_of_form', form => 'spec_target.tx' ) );
  803. is( ref $res, 'ARRAY', 'a PSGI response came back' ) or return;
  804. my ( $code, undef, $body ) = @$res;
  805. is( $code, 200, 'and it is a 200' );
  806. my $payload = JSON::MaybeXS::decode_json( join( '', @$body ) );
  807. is_deeply(
  808. $payload->{posts},
  809. [ { id => $target->{id}, title => 'Spec Target Post' } ],
  810. 'listing exactly the posts of that type, id and title only'
  811. );
  812. # An unknown type is an empty list, not an error -- a type with no posts
  813. # yet is the normal state of affairs right after you create it.
  814. $res = Trog::Routes::JSON::posts_of_form( _admin( route => '/api/posts_of_form', form => 'nosuchtype.tx' ) );
  815. $payload = JSON::MaybeXS::decode_json( join( '', @{ $res->[2] } ) );
  816. is_deeply( $payload->{posts}, [], 'an unknown type lists nothing rather than failing' );
  817. # The route's own declaration is what keeps a malformed form out; check it
  818. # matches what series.json demands of child_form.
  819. my $validator = $Trog::Routes::JSON::routes{'/api/posts_of_form'}{parameters}{form};
  820. ok( $validator->('blog.tx'), 'the parameter validator accepts a form name' );
  821. ok( !$validator->('../../etc/passwd'), 'and rejects a path' );
  822. ok( $Trog::Routes::JSON::routes{'/api/posts_of_form'}{auth}, 'the route requires a login' );
  823. };
  824. subtest 'a series resolves its relations for logged out visitors too' => sub {
  825. # The relations series() resolves land on the primary post, which is what a
  826. # datasource reads to find its hypervisors -- so assert on that rather than
  827. # on the rendered children, whose relations posts() resolves later, after
  828. # it has widened user_acls and thus by a path that was never broken.
  829. foreach my $case ( [ 'anonymously', _anon( route => '/specrelator' ) ], [ 'as an admin', _admin( route => '/specrelator' ) ] ) {
  830. my ( $label, $query ) = @$case;
  831. my ( $code, undef, $err ) = _render( $query, \&Trog::Routes::HTML::series );
  832. is( $code, 200, "the series renders $label" ) or do { diag($err); next };
  833. my $resolved = $query->{primary_post}{everything};
  834. is( ref $resolved, 'ARRAY', "$label, the series' own relation resolved" );
  835. cmp_ok( scalar @{ $resolved || [] }, '>', 0, "$label, to something rather than nothing" );
  836. }
  837. };
  838. subtest 'saves report back through the jsalert banner' => sub {
  839. # A good save redirects to where you came from, carrying the outcome.
  840. my $res = Trog::Routes::HTML::post_save(
  841. _admin(
  842. route => '/post/save',
  843. method => 'POST',
  844. to => '/specblog',
  845. form => 'blog.tx',
  846. title => 'Spec Feedback Child',
  847. data => 'Spec feedback body.',
  848. visibility => 'public',
  849. tags => ['specblog'],
  850. )
  851. );
  852. my ( $code, $headers ) = @$res;
  853. my %h = @{ $headers || [] };
  854. is( $code, 303, 'a good save redirects' );
  855. like( $h{Location}, qr{^/secure/specblog\?saved=}, 'to where we came from, flagged as saved' );
  856. unlike( $h{Location}, qr/\n/, 'and the message is one line, since it lands in a JS string' );
  857. _reindex();
  858. # Follow the redirect the way a browser would.
  859. my ($qs) = $h{Location} =~ m/\?(.*)$/;
  860. my %params = map { my ( $k, $v ) = split( /=/, $_, 2 ); ( $k => URI::Escape::uri_unescape($v) ) } split( /&/, $qs );
  861. my ( $rcode, $body, $err ) = _render(
  862. _admin( route => '/specblog', has_query => 1, %params ),
  863. \&Trog::Routes::HTML::series,
  864. );
  865. is( $rcode, 200, 'the destination renders' ) or diag($err);
  866. like( $body, qr/var loginFailure = 0;/, 'the banner is in success mode' );
  867. like( $body, qr/Saved post &#39;Spec Feedback Child&#39;\./, 'and says what was saved' );
  868. # Nothing to navigate on to, so the banner must not bounce us anywhere.
  869. unlike( $body, qr/window\.location=/, 'and does not redirect onwards' );
  870. # A rejected save comes back the same way, in red.
  871. $res = Trog::Routes::HTML::post_save(
  872. _admin(
  873. route => '/post/save',
  874. method => 'POST',
  875. to => '/specblog',
  876. form => 'blog.tx',
  877. title => 'Spec Rejected Child',
  878. visibility => 'not-a-visibility',
  879. tags => ['specblog'],
  880. )
  881. );
  882. ( $code, $headers ) = @$res;
  883. %h = @{ $headers || [] };
  884. is( $code, 303, 'a rejected save redirects too, rather than dead-ending on a 400' );
  885. like( $h{Location}, qr{^/secure/specblog\?savefailed=}, 'flagged as failed' );
  886. like( URI::Escape::uri_unescape( $h{Location} ), qr/Not in enum list/, 'carrying the validator error' );
  887. ok( !_find_post('Spec Rejected Child'), 'and the bad post was not written' );
  888. ($qs) = $h{Location} =~ m/\?(.*)$/;
  889. %params = map { my ( $k, $v ) = split( /=/, $_, 2 ); ( $k => URI::Escape::uri_unescape($v) ) } split( /&/, $qs );
  890. ( $rcode, $body, $err ) = _render(
  891. _admin( route => '/specblog', has_query => 1, %params ),
  892. \&Trog::Routes::HTML::series,
  893. );
  894. is( $rcode, 200, 'the destination still renders' ) or diag($err);
  895. like( $body, qr/var loginFailure = 1;/, 'the banner is in failure mode' );
  896. like( $body, qr/Not in enum list/, 'and shows why' );
  897. };
  898. subtest 'the topbar did not silently overflow' => sub {
  899. my ( $code, $body, $err ) = _render( _anon( route => '/' ) );
  900. is( $code, 200, '/ renders' ) or diag($err);
  901. my @titles = _topbar_titles($body);
  902. # 2 seeded series (Series, About) + the 7 we built. _get_series() caps at
  903. # 10 (HTML.pm), so an eighth post type would start silently dropping one.
  904. is( scalar @titles, 9, 'every series we made is in the topbar' )
  905. or diag( 'topbar was: ' . join( ', ', @titles ) );
  906. cmp_ok( scalar @titles, '<=', 10, 'and we are not at the _get_series limit' );
  907. };
  908. subtest 'the tpsgi side effects stayed inert' => sub {
  909. cmp_ok( $TPSGI->{restarts}, '>', 0, 'post_save did try to signal a restart' );
  910. cmp_ok( $TPSGI->{callbacks}, '>', 0, 'and did queue post-close callbacks' );
  911. # We never run the queued callbacks, which is what keeps save_render and
  912. # invalidate_renders from ever firing.
  913. is_deeply( $TPSGI->{renders}, {}, 'no static renders were written' );
  914. is_deeply( $TPSGI->{invalidated}, [], 'and nothing was invalidated' );
  915. my @statics = glob('www/statics/*');
  916. is_deeply( \@statics, [], 'www/statics is empty' );
  917. };
  918. subtest 'the real repo was not touched' => sub {
  919. my %after = map { _snapshot("$REPO/$_") } qw{config data www/templates www/assets logs totp};
  920. my @changed = grep { ( $REPO_BEFORE{$_} // '' ) ne ( $after{$_} // '' ) } keys %after;
  921. my @removed = grep { !exists $after{$_} } keys %REPO_BEFORE;
  922. is_deeply( [ sort @changed ], [], 'no repo file was added or modified' );
  923. is_deeply( [ sort @removed ], [], 'and none were removed' );
  924. ok( !-e "$REPO/www/templates/html/components/forms/spec_widget.tx", 'the wizard type is not in the repo' );
  925. };
  926. done_testing();