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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576
  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. use File::Slurper ();
  27. our ( $REPO, $ROOT, $OLDCWD );
  28. our %REPO_BEFORE;
  29. # Which data model this run exercises. Every assertion in this file is about
  30. # what the app does, not how it stores anything, so all of them have to hold for
  31. # any of them.
  32. our $MODEL;
  33. # In BEGIN because the sandbox is built in one, before file scope runs.
  34. BEGIN { $MODEL = $ENV{TCMS_TEST_DATA_MODEL} || 'FlatFile' }
  35. # name => (size, mtime) for every file under the repo dirs this test could
  36. # plausibly disturb. Cheap enough, and it is the only real proof of isolation.
  37. sub _snapshot {
  38. my ($dir) = @_;
  39. my %seen;
  40. File::Find::find(
  41. {
  42. no_chdir => 1,
  43. wanted => sub {
  44. return unless -f $File::Find::name;
  45. my @st = stat(_);
  46. $seen{$File::Find::name} = "$st[7]:$st[9]";
  47. },
  48. },
  49. $dir
  50. );
  51. return %seen;
  52. }
  53. sub _copy_tree {
  54. my ( $from, $to ) = @_;
  55. File::Path::make_path($to);
  56. File::Find::find(
  57. {
  58. no_chdir => 1,
  59. wanted => sub {
  60. my $rel = substr( $File::Find::name, length($from) );
  61. return unless length $rel;
  62. my $dst = "$to$rel";
  63. if ( -d $File::Find::name ) { File::Path::make_path($dst) }
  64. elsif ( -f $File::Find::name ) { File::Copy::copy( $File::Find::name, $dst ) or die "copy $File::Find::name: $!" }
  65. },
  66. },
  67. $from
  68. );
  69. return;
  70. }
  71. # Everything the sandbox needs, in one BEGIN. The Trog:: modules are require()d
  72. # at runtime below, which is unconditionally after every BEGIN -- so no later
  73. # edit can accidentally load them before the chdir. That matters: TCMS.pm runs
  74. # build_routes() at file scope and FlatFile.pm reads the tag index at file
  75. # scope, both against whatever cwd happens to be current.
  76. BEGIN {
  77. $REPO = Cwd::abs_path("$FindBin::Bin/..");
  78. $OLDCWD = Cwd::getcwd();
  79. %REPO_BEFORE = map { _snapshot("$REPO/$_") } qw{config data www/templates www/assets logs totp};
  80. $ROOT = File::Temp::tempdir( 'tcms-lifecycle-XXXXXX', TMPDIR => 1, CLEANUP => 0 );
  81. # Installer.mk's tree, plus upload-src for the file.tx fixture.
  82. File::Path::make_path(
  83. map { "$ROOT/$_" }
  84. qw{
  85. config schema data/files logs totp upload-src
  86. www/assets/private www/statics www/themes www/scripts
  87. }
  88. );
  89. # A real fresh install: get() looks for config/main.cfg, doesn't find one,
  90. # and falls through to the shipped default. The data model is the shipped
  91. # one unless the environment names another, which is how this whole file
  92. # gets run against each of them -- the point being that a data model is only
  93. # finished when the app cannot tell which one it is talking to.
  94. my $stock = File::Slurper::read_text("$REPO/config/default.cfg");
  95. $stock =~ s/^(\s*data_model=).*$/$1$MODEL/m or die "could not set the data model in default.cfg";
  96. File::Slurper::write_text( "$ROOT/config/default.cfg", $stock );
  97. # Hardcoded paths in Auth.pm, TagIndex.pm, the data models and Log.pm -- not negotiable.
  98. File::Copy::copy( "$REPO/schema/$_", "$ROOT/schema/$_" ) or die $! for qw{auth.schema flatfile.schema sqlite.schema log.schema};
  99. # COPY, don't symlink: post_wizard_save() writes into Trog::Themes::forms_dir(),
  100. # and a symlink would land the generated post type in the real repo.
  101. _copy_tree( "$REPO/www/templates", "$ROOT/www/templates" );
  102. # posts.tx pulls in the EmojiPicker component for an editor, and EmojiPicker
  103. # dies outright if this file is missing. Only category and emoji are read.
  104. open( my $fh, '>', "$ROOT/www/scripts/list.min.json" ) or die $!;
  105. print {$fh} '{"emojis":[{"category":"Smileys","emoji":"X"}]}';
  106. close $fh;
  107. # Text::Xslate computes its default cache dir from $HOME once, at load time.
  108. # Without this the sandbox writes compiled templates into the real ~/.xslate_cache.
  109. $ENV{HOME} = $ROOT;
  110. chdir($ROOT) or die "could not chdir to sandbox $ROOT: $!";
  111. }
  112. END {
  113. # Never rmtree the directory you are standing in.
  114. chdir($OLDCWD) if $OLDCWD;
  115. if ( $ENV{TCMS_TEST_KEEP} ) {
  116. diag("TCMS_TEST_KEEP set, sandbox left at $ROOT");
  117. }
  118. elsif ( $ROOT && -d $ROOT ) {
  119. # SQLite handles are file-lexical in Trog::SQLite and unreachable from
  120. # here; DBI disconnects at global destruction, after these are gone.
  121. eval { File::Path::remove_tree($ROOT) };
  122. }
  123. }
  124. diag("sandbox: $ROOT");
  125. require Trog::Log;
  126. Trog::Log::log_init( 'logs/tcms.log', 'info' ); # sets $LOGDIR, hence logs/log.db
  127. require Trog::Config;
  128. require Trog::Themes;
  129. require Trog::Data;
  130. require Trog::Auth;
  131. require Trog::SQLite::TagIndex if $MODEL eq 'FlatFile';
  132. require Trog::Routes::HTML;
  133. require Trog::Routes::JSON;
  134. #--------------------------------------------------------------------------
  135. # A stand-in for the tPSGI object the router injects as $query->{tpsgi}.
  136. #--------------------------------------------------------------------------
  137. {
  138. package Test::TPSGI;
  139. sub new {
  140. my ( $class, %args ) = @_;
  141. return bless {
  142. callbacks => 0,
  143. run_callbacks => 0,
  144. renders => {},
  145. invalidated => [],
  146. watches => [],
  147. restarts => 0,
  148. tpsgi_dir => Cwd::getcwd(),
  149. log_dir => 'logs',
  150. gid => $),
  151. verbose => 0,
  152. %args,
  153. }, $class;
  154. }
  155. sub INFO { 1 }
  156. sub DEBUG { 1 }
  157. sub WARN { 1 }
  158. sub ERROR { 1 }
  159. sub CRIT { 1 }
  160. sub ALERT { 1 }
  161. sub EMERG { 1 }
  162. sub FATAL { 1 }
  163. sub see_also { return [ 303, [ 'Location' => $_[1], 'Content-Length' => 0 ], [''] ] }
  164. sub redirect { return [ 302, [ 'Location' => $_[1], 'Content-Length' => 0 ], [''] ] }
  165. sub redirect_permanent { return [ 301, [ 'Location' => $_[1], 'Content-Length' => 0 ], [''] ] }
  166. sub _reply { return [ $_[1], [ 'Content-type' => 'text/html' ], [ defined $_[2] ? $_[2] : '' ] ] }
  167. sub ok { return $_[0]->_reply( 200, $_[2] ) }
  168. sub notfound { return $_[0]->_reply( 404, $_[2] // 'Not Found' ) }
  169. sub forbidden { return $_[0]->_reply( 403, $_[2] // 'Forbidden' ) }
  170. sub badrequest { return $_[0]->_reply( 400, $_[2] // 'Bad Request' ) }
  171. sub error { return $_[0]->_reply( 500, $_[2] // 'Error' ) }
  172. sub serve { return [ 200, [], [''] ] }
  173. # These two must be inert.
  174. #
  175. # add_post_close_callback is the ONLY path by which Trog::Renderer and
  176. # post_save reach save_render()/invalidate_renders(). Dropping the callback
  177. # on the floor is what guarantees this test never writes into www/statics,
  178. # whatever the renderer's own skip-save logic decides.
  179. # ...unless a test explicitly asks, which is how the one test that is about
  180. # what gets cached gets to see it. Still nowhere near www/statics:
  181. # save_render below only records what it was handed.
  182. sub add_post_close_callback {
  183. my ( $self, $callback ) = @_;
  184. $self->{callbacks}++;
  185. $callback->() if $self->{run_callbacks} && ref $callback eq 'CODE';
  186. return 1;
  187. }
  188. # The real one is `kill 'HUP', getppid`. Under prove, that is prove.
  189. sub signal_restart_parent { $_[0]{restarts}++; return 1 }
  190. # Recorded rather than inert: a datasource that watches something is
  191. # supposed to register here, and the lifecycle test is where we find out
  192. # whether it did through the real route.
  193. sub add_watch {
  194. my ( $self, $path, $callback, %options ) = @_;
  195. push( @{ $self->{watches} }, { path => $path, callback => $callback, %options } );
  196. return 1;
  197. }
  198. sub invalidate_renders { push @{ $_[0]{invalidated} }, $_[1]; return 1 }
  199. sub invalidate_render { push @{ $_[0]{invalidated} }, [ @_[ 1 .. $#_ ] ]; return 1 }
  200. sub save_render { $_[0]{renders}{"$_[1]:$_[2]"} = $_[3]; return 1 }
  201. }
  202. our $TPSGI = Test::TPSGI->new();
  203. our $ADMIN_USER = 'specadmin';
  204. our $ADMIN_DISPLAY = 'Spec Admin';
  205. our $ADMIN_EMAIL = 'specadmin@example.com';
  206. our $ADMIN_PASS = 'spec-password';
  207. #--------------------------------------------------------------------------
  208. # Harness
  209. #--------------------------------------------------------------------------
  210. # Always build a fresh query: posts() pushes onto user_acls, and series()
  211. # rewrites route/aclname/tag/in_series/primary_post in place.
  212. sub _query {
  213. my (%over) = @_;
  214. my %q = (
  215. route => '/',
  216. method => 'GET',
  217. scheme => 'http', # Renderer::Base compares this with no undef guard
  218. domain => 'tcms.test',
  219. start => [ Time::HiRes::gettimeofday() ], # tv_interval() dies on anything else
  220. deflate => 0,
  221. streaming => 0,
  222. ranges => [],
  223. last_fetched => undef,
  224. has_query => 0,
  225. social_meta => 0,
  226. acls => [],
  227. user_acls => [],
  228. body => undef,
  229. tpsgi => $TPSGI,
  230. %over,
  231. );
  232. $q{fullpath} //= $q{route};
  233. return \%q;
  234. }
  235. sub _anon { return _query( user => undef, user_acls => [], @_ ) }
  236. sub _admin { return _query( user => $ADMIN_USER, user_acls => ['admin'], @_ ) }
  237. # Returns ($code, $body, $error). Never dies, so one bad post type cannot take
  238. # the rest of the file with it -- which matters because a failed render inside
  239. # index() dies rather than returning a 500 (there is no www/templates/html/500.tx).
  240. sub _render {
  241. my ( $query, $how ) = @_;
  242. $how ||= \&Trog::Routes::HTML::index;
  243. my $res = eval { $how->($query) };
  244. return ( 0, '', "died: $@" ) if !$res;
  245. return ( 0, '', 'returned a ' . ( ref($res) || 'plain scalar' ) ) if ref $res ne 'ARRAY';
  246. my ( $code, $headers, $body ) = @$res;
  247. $body = ref $body eq 'ARRAY' ? join( '', @$body ) : ( $body // '' );
  248. return ( $code, Encode::decode_utf8($body), '', $headers );
  249. }
  250. # FlatFile snapshots the tag list at load time and then filters each query's
  251. # tags against it IN PLACE -- so a tag created later isn't merely unindexed, it
  252. # is deleted from the query, and the filter silently degrades to "every public
  253. # post". Production gets away with it because a save HUPs the parent and the
  254. # worker re-execs. We have to do it by hand.
  255. #
  256. # Nothing to do for a model that asks the database each time, which is the
  257. # point: this helper exists to paper over a cache, and a model without one
  258. # needs no paper.
  259. sub _reindex {
  260. return unless $MODEL eq 'FlatFile';
  261. no warnings 'once';
  262. @Trog::Data::FlatFile::tags = Trog::SQLite::TagIndex::tags();
  263. %Trog::Data::FlatFile::posts_by_tag = ();
  264. return;
  265. }
  266. sub _data { return Trog::Data->new( Trog::Config::get() ) }
  267. # categories.tx renders into <span id="categories">. Scope to it -- index.tx
  268. # emits other class="topbar" anchors outside that span.
  269. sub _topbar_titles {
  270. my ($body) = @_;
  271. my ($span) = $body =~ m{<span id="categories">(.*?)</span>}s;
  272. return () unless defined $span;
  273. return $span =~ m{class="topbar">([^<]*)</a>}g;
  274. }
  275. # post_title.tx emits exactly one of these per displayed post.
  276. sub _post_count {
  277. my $n = () = $_[0] =~ m{<h3 class='blogtitles'>}g;
  278. return $n;
  279. }
  280. # The rendered page is ~40KB and mostly JavaScript. Show the content well.
  281. sub _kontent {
  282. my ($body) = @_;
  283. my ($k) = $body =~ m{<div id="kontent" class="kontained">(.*?)<div id="rightbar"}s;
  284. $k //= $body;
  285. $k =~ s/<script\b.*?<\/script>//gs;
  286. return length($k) > 2500 ? substr( $k, 0, 2500 ) . "\n...[truncated]" : $k;
  287. }
  288. # Save through post_save() rather than $data->add(): add() dies with an
  289. # arrayref of validator errors, whereas post_save catches them and hands back a
  290. # 400 with the field-level detail in the body -- which is the single most
  291. # useful thing to see when a fixture is wrong.
  292. sub _save_post {
  293. my ( $label, %post ) = @_;
  294. my $to = delete $post{to};
  295. my $res = eval { Trog::Routes::HTML::post_save( _admin( route => '/post/save', method => 'POST', to => $to, %post ) ) };
  296. if ( !$res || ref $res ne 'ARRAY' ) {
  297. fail("$label: saved");
  298. diag( $@ || 'post_save returned nothing' );
  299. return undef;
  300. }
  301. my ( $code, $headers, $body ) = @$res;
  302. my %h = @{ $headers || [] };
  303. # Both outcomes redirect now, so the status alone proves nothing -- the
  304. # outcome is in the query string post_save hands to the destination.
  305. if ( $code != 303 || ( $h{Location} // '' ) =~ m/savefailed=/ ) {
  306. fail("$label: saved");
  307. diag( "post_save returned $code, Location: " . ( $h{Location} // '(none)' ) );
  308. diag( join( '', @{ $body || [''] } ) ) if $body && @$body;
  309. return undef;
  310. }
  311. pass("$label: saved");
  312. _reindex(); # mandatory: see the comment on _reindex
  313. my $saved = _find_post( $post{title} );
  314. ok( $saved, "$label: readable back out of the datastore" ) or return undef;
  315. return $saved;
  316. }
  317. sub _find_post {
  318. my ($title) = @_;
  319. # filter() short-circuits on title; the admin acl skips the visibility filter.
  320. my @posts = _data()->get( title => $title, acls => ['admin'], limit => 0 );
  321. return $posts[0];
  322. }
  323. #--------------------------------------------------------------------------
  324. subtest 'the sandbox is what we are actually running against' => sub {
  325. is( Cwd::getcwd(), Cwd::abs_path($ROOT), 'cwd is the sandbox' );
  326. ok( -d 'data/files', 'datastore dir exists' );
  327. ok( -f 'config/default.cfg', 'config was seeded' );
  328. ok( !-f 'config/main.cfg', 'and there is no main.cfg, so we fall through to the default' );
  329. my $conf = Trog::Config::get();
  330. is( $conf->param('general.data_model'), $MODEL, 'config resolves inside the sandbox' );
  331. like( Trog::Themes::forms_dir(), qr/^www\/templates/, 'forms dir is relative, hence sandboxed' );
  332. ok( -d Cwd::abs_path( Trog::Themes::forms_dir() ), 'and it exists' );
  333. like( Cwd::abs_path( Trog::Themes::forms_dir() ), qr/^\Q$ROOT\E/, 'and it is under the sandbox, not the repo' );
  334. };
  335. subtest 'registering the first admin bootstraps the install' => sub {
  336. ok( !-f 'config/has_users', 'no users yet, so login() is in register mode' );
  337. my ( $code, $body, $err, $headers ) = _render(
  338. _anon(
  339. route => '/login',
  340. method => 'POST',
  341. username => $ADMIN_USER,
  342. display_name => $ADMIN_DISPLAY,
  343. contact_email => $ADMIN_EMAIL,
  344. password => $ADMIN_PASS,
  345. to => '/',
  346. ),
  347. \&Trog::Routes::HTML::login,
  348. );
  349. is( $code, 200, 'login() rendered' ) or diag($err);
  350. my %h = @{ $headers || [] };
  351. like( $h{'Set-Cookie'} // '', qr/^tcmslogin=[0-9a-f-]{36};/, 'a session cookie came back' );
  352. ok( -f 'config/has_users', 'registration is now closed' );
  353. is_deeply( Trog::Auth::acls4user($ADMIN_USER), ['admin'], 'the new user is an admin' );
  354. _reindex();
  355. my @seeded = _data()->get( acls => ['admin'], limit => 0 );
  356. is( scalar @seeded, 4, 'the four seed posts were written' )
  357. or diag( 'got: ' . join( ', ', map { "$_->{title} ($_->{form})" } @seeded ) );
  358. };
  359. subtest 'the post wizard invents a new post type' => sub {
  360. my %wizard = (
  361. name => 'spec_widget',
  362. title_placeholder => 'Widget Name',
  363. body_form => 'form_common.tx',
  364. wrapper => 1,
  365. inc_post_title => 1,
  366. inc_post_tags => 1,
  367. inc_title_input => 1,
  368. inc_visibility => 1,
  369. inc_tags => 1,
  370. inc_aliases => 1,
  371. param_name => ['flavor'],
  372. param_type => ['text'],
  373. param_label => ['Flavor'],
  374. param_placeholder => ['Strawberry'],
  375. param_required => [0],
  376. 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>},
  377. );
  378. my ( $code, $body, $err ) = _render(
  379. _admin( route => '/admin/wyzzerdd/save', method => 'POST', %wizard ),
  380. \&Trog::Routes::HTML::post_wizard_save,
  381. );
  382. is( $code, 200, 'wizard save rendered' ) or diag($err);
  383. ok( -f 'www/templates/html/components/forms/spec_widget.tx', 'the template was written' );
  384. ok( -f 'www/templates/html/components/forms/spec_widget.json', 'the schema sidecar was written' );
  385. # The existing types are a dropdown now, not a list.
  386. like( $body, qr{<option value="spec_widget\.tx">}, 'and the new type is listed back to us' );
  387. # This is the assertion that the sandbox is real: a symlinked template tree
  388. # would have put these in the developer's actual checkout.
  389. ok( !-e "$REPO/www/templates/html/components/forms/spec_widget.tx", 'nothing was written into the repo' );
  390. # The relation controls have to be present in every row and always submit,
  391. # or the parallel param_* arrays de-align server side.
  392. like( $body, qr/name="param_relation_form"/, 'the relation target select is in the row template' );
  393. like( $body, qr/name="param_relation_mode"/, 'so is the relation mode select' );
  394. like( $body, qr/<option value="relation">/, 'and relation is offered as a field type' );
  395. # A series can ask for its children to be tiled. A generated type has to
  396. # carry that on its wrapper like the hand-written forms do, or it is the
  397. # one kind of post that silently ignores the setting.
  398. my $generated = Path::Tiny->new('www/templates/html/components/forms/spec_widget.tx')->slurp_utf8;
  399. # Single quoted: the wrapper is Kolon source, so every sigil in it is
  400. # literal and must not be interpolated by the test that checks for it.
  401. my $wrapper = q{<div class="post <: $style :> <: $tiled ? 'tile' : '' :>">};
  402. ok( index( $generated, $wrapper ) >= 0, 'the generated wrapper carries the tile class when the series asks for it' )
  403. or diag( "wanted: $wrapper\ngot: " . ( split( /\n/, $generated ) )[1] );
  404. # Every post has a title, a visibility and acls. The wizard used to let a
  405. # type opt out of collecting them, which is how a hypervisor post ended up
  406. # stored with no visibility and an undef in its tags.
  407. foreach my $required ( 'visibility.tx', 'acls.tx' ) {
  408. like( $generated, qr/\Q: include "$required";\E/, "$required is included whether or not it was asked for" );
  409. }
  410. like( $generated, qr/name="title"/, 'and so is the title input' );
  411. foreach my $gone (qw{inc_title_input inc_visibility inc_acls}) {
  412. unlike( $body, qr/name="\Q$gone\E"/, "the wizard no longer offers '$gone' as a choice" );
  413. }
  414. like( $body, qr/name="param_private"/, 'and it offers per-field privacy' );
  415. like( $body, qr/name="datasource"/, 'and a datasource to draw the posts from' );
  416. like( $body, qr/Trog::DataSource::Virt/, 'listing the ones that exist' );
  417. };
  418. subtest 'a datasource-backed type gets no editor' => sub {
  419. # A datasource whose posts are built rather than written has nothing behind
  420. # a form to save, so generating one would produce an editor that writes
  421. # real posts to sit alongside the synthesized ones.
  422. my ( $code, $body, $err ) = _render(
  423. _admin(
  424. route => '/admin/wyzzerdd/save',
  425. method => 'POST',
  426. name => 'spec_sourced',
  427. datasource => 'Trog::DataSource::Virt',
  428. body_form => 'form_common.tx',
  429. wrapper => 1,
  430. inc_post_title => 1,
  431. display => q{<div class="s"><: $post.title :></div>},
  432. ),
  433. \&Trog::Routes::HTML::post_wizard_save,
  434. );
  435. is( $code, 200, 'the type was created' ) or diag($err);
  436. my $generated = Path::Tiny->new('www/templates/html/components/forms/spec_sourced.tx')->slurp_utf8;
  437. unlike( $generated, qr{action="/post/save"}, 'no editor was generated' );
  438. unlike( $generated, qr/\$can_edit/, 'and nothing guards one' );
  439. like( $generated, qr/class="s"/, 'but the display half is there' );
  440. my $sidecar = JSON::MaybeXS::decode_json( Path::Tiny->new('www/templates/html/components/forms/spec_sourced.json')->slurp_utf8 );
  441. is( $sidecar->{'x-tcms-datasource'}, 'Trog::DataSource::Virt', 'and the sidecar records the datasource' );
  442. # The same type without one keeps its editor.
  443. _render(
  444. _admin(
  445. route => '/admin/wyzzerdd/save',
  446. method => 'POST',
  447. name => 'spec_stored',
  448. body_form => 'form_common.tx',
  449. wrapper => 1,
  450. inc_post_title => 1,
  451. display => q{<div class="s"><: $post.title :></div>},
  452. ),
  453. \&Trog::Routes::HTML::post_wizard_save,
  454. );
  455. my $stored = Path::Tiny->new('www/templates/html/components/forms/spec_stored.tx')->slurp_utf8;
  456. like( $stored, qr{action="/post/save"}, 'a type on the datastore still gets one' );
  457. # The name is require()d later, so it has to be one we found.
  458. ( $code, $body ) = _render(
  459. _admin( route => '/admin/wyzzerdd/save', method => 'POST', name => 'spec_bogus', datasource => 'Evil::Module' ),
  460. \&Trog::Routes::HTML::post_wizard_save,
  461. );
  462. like( $body, qr/not a datasource I can find/, 'a datasource we did not find is refused' );
  463. ok( !-e 'www/templates/html/components/forms/spec_bogus.tx', 'and nothing was written' );
  464. };
  465. subtest 'a datasource-backed series searches and paginates' => sub {
  466. # The whole point of a datasource is that its posts are built rather than
  467. # stored, so nothing the datastore does to a query ever touches them. Stand
  468. # one up with enough guests to page through, and drive it through the real
  469. # route rather than calling the helpers.
  470. require Test::MockModule;
  471. require Trog::DataSource::Virt;
  472. my ( $code, $body, $err ) = _render(
  473. _admin(
  474. route => '/admin/wyzzerdd/save',
  475. method => 'POST',
  476. name => 'spec_guests',
  477. datasource => 'Trog::DataSource::Virt',
  478. body_form => 'form_common.tx',
  479. wrapper => 1,
  480. inc_post_title => 1,
  481. display => q{<div class="guest"><: $post.title :> is <: $post.state :></div>},
  482. ),
  483. \&Trog::Routes::HTML::post_wizard_save,
  484. );
  485. is( $code, 200, 'the datasource-backed type was created' ) or diag($err);
  486. _reindex();
  487. my $series = _make_series( 'spec_guests', 'specguests', 'spec_guests.tx', 'Spec Guests Series', no_topbar => 1 ) or return;
  488. # Twelve guests, every one stamped with the same created -- which is what
  489. # libvirt guests really are, and precisely what the cursor paginator cannot
  490. # page through.
  491. my $built = time();
  492. my $virt = Test::MockModule->new('Trog::DataSource::Virt');
  493. $virt->redefine(
  494. posts => sub {
  495. my ( $s, $q ) = @_;
  496. return map {
  497. {
  498. id => "guest-$_",
  499. title => sprintf( 'guest%02d', $_ ),
  500. form => $s->{child_form},
  501. data => '',
  502. state => $_ % 2 ? 'running' : 'shut off',
  503. local_href => "/guest/hv/guest$_",
  504. href => '',
  505. tags => $s->{tags} // [],
  506. visibility => $s->{visibility} // 'private',
  507. created => $built,
  508. version => 0,
  509. user => $s->{user},
  510. method => 'GET',
  511. }
  512. } 1 .. 12;
  513. }
  514. );
  515. my $page_of = sub {
  516. my (%q) = @_;
  517. my ( $c, $b, $e ) = _render( _anon( route => '/specguests', %q ), \&Trog::Routes::HTML::series );
  518. is( $c, 200, 'guests page renders' ) or diag($e);
  519. return $b // '';
  520. };
  521. my $titles = sub {
  522. my ($html) = @_;
  523. return [ $html =~ m{<div class="guest">(guest\d+) is}g ];
  524. };
  525. my $first = $page_of->( limit => 5 );
  526. is_deeply( $titles->($first), [qw{guest01 guest02 guest03 guest04 guest05}], 'the first page holds the first five, in a settled order' );
  527. like( $first, qr/Page 1 of 3/, 'and says which page it is' );
  528. like( $first, qr{href="\?page=2&limit=5}, 'offering the next one' );
  529. unlike( $first, qr/rel="prev"/, 'and no previous one' );
  530. my $second = $page_of->( limit => 5, page => 2 );
  531. is_deeply( $titles->($second), [qw{guest06 guest07 guest08 guest09 guest10}], 'the second page carries on where the first stopped' );
  532. like( $second, qr/Page 2 of 3/, 'and says so' );
  533. my $third = $page_of->( limit => 5, page => 3 );
  534. is_deeply( $titles->($third), [qw{guest11 guest12}], 'the last page holds the remainder' );
  535. unlike( $third, qr/rel="next"/, 'and offers nothing after it' );
  536. # A guest's state is the point of the page, and nothing could invalidate a
  537. # cached copy: a guest starting is not a post being saved, and libvirt is
  538. # not going to tell us about it.
  539. my $vtpsgi = Test::TPSGI->new( run_callbacks => 1 );
  540. _render( _anon( route => '/specguests', tpsgi => $vtpsgi ), \&Trog::Routes::HTML::series );
  541. is_deeply( [ keys %{ $vtpsgi->{renders} } ], [], 'a guests page is never saved as a static' );
  542. # The cursor paginator would be worse than useless here: every guest shares
  543. # a created, so Prev would ask for everything older than that one instant.
  544. unlike( $first, qr/older=$built/, 'no cursor is offered on a page that cannot use one' );
  545. # Search, which before this reached the datastore and was thrown away along
  546. # with the posts it filtered.
  547. my $searched = $page_of->( limit => 25, like => 'guest1' );
  548. is_deeply( $titles->($searched), [qw{guest10 guest11 guest12}], 'searching a datasource page searches the page' );
  549. # Virt searches what its posts carry, not just a title and an empty body.
  550. my $by_state = $page_of->( limit => 25, like => 'shut' );
  551. is_deeply( $titles->($by_state), [qw{guest02 guest04 guest06 guest08 guest10 guest12}], 'including a field only it knows about' );
  552. # And the two compose, which is what a reader paging through a search does.
  553. my $searched_page = $page_of->( limit => 4, like => 'shut', page => 2 );
  554. is_deeply( $titles->($searched_page), [qw{guest10 guest12}], 'paging through a search stays inside it' );
  555. like( $searched_page, qr/Page 2 of 2/, 'and pages against the matches, not everything' );
  556. like( $searched_page, qr/like=shut/, 'carrying the search into the links' );
  557. };
  558. subtest 'an ordinary series survives a page number in its URL' => sub {
  559. # series() looks its own post up with the reader's query, so a ?page= meant
  560. # for the children used to page the lookup of the series itself -- page two
  561. # of one post being nothing, the series could not find itself and 404'd on
  562. # its own page. Latent until the datasource paginator started emitting page
  563. # numbers, and it was never about datasources.
  564. _reindex();
  565. _make_series( 'spec_paged', 'specpaged', 'blog.tx', 'Spec Paged Series', no_topbar => 1 ) or return;
  566. foreach my $n ( 1, 2 ) {
  567. _save_post(
  568. "spec_paged child $n",
  569. form => 'blog.tx',
  570. title => "Spec Paged Child $n",
  571. data => "child $n body",
  572. visibility => 'public',
  573. tags => ['specpaged'],
  574. to => '/specpaged',
  575. ) or return;
  576. }
  577. # One child a page, so page two exists and holds the other one.
  578. my ( $code, $body, $err ) = _render( _anon( route => '/specpaged', limit => 1, page => 2 ), \&Trog::Routes::HTML::series );
  579. is( $code, 200, 'a series page with ?page=2 still finds its series' ) or diag($err);
  580. like( $body, qr/Spec Paged Series/, 'and is the right one' );
  581. ( $code, $body, $err ) = _render( _anon( route => '/specpaged', limit => 1, page => 1 ), \&Trog::Routes::HTML::series );
  582. is( $code, 200, 'as does page one' ) or diag($err);
  583. # A stored series still pages by cursor, not by number: nothing about this
  584. # fix moves it onto the datasource paginator.
  585. unlike( $body, qr/Page 1 of/, 'and it still pages by cursor rather than by number' );
  586. };
  587. subtest 'a directory index series' => sub {
  588. # A wizard-built type drawing its posts from a directory, through the real
  589. # route, on whichever data model this run is using.
  590. require Trog::DataSource::DirIndex;
  591. my ( $code, $body, $err ) = _render(
  592. _admin(
  593. route => '/admin/wyzzerdd/save',
  594. method => 'POST',
  595. name => 'spec_files',
  596. datasource => 'Trog::DataSource::DirIndex',
  597. body_form => 'form_common.tx',
  598. wrapper => 1,
  599. inc_post_title => 1,
  600. display => q{<div class="entry"><: $post.name :> (<: $post.size_human :>)</div>},
  601. ),
  602. \&Trog::Routes::HTML::post_wizard_save,
  603. );
  604. is( $code, 200, 'the directory-backed type was created' ) or diag($err);
  605. File::Path::make_path('www/assets/spec_downloads');
  606. foreach my $n ( 1 .. 7 ) {
  607. open( my $fh, '>', "www/assets/spec_downloads/file$n.txt" ) or die $!;
  608. print {$fh} ( 'x' x ( $n * 10 ) );
  609. close $fh;
  610. }
  611. _reindex();
  612. my $series = _make_series(
  613. 'spec_files', 'specfiles', 'spec_files.tx', 'Spec Files Series',
  614. no_topbar => 1,
  615. directory => 'assets/spec_downloads',
  616. ) or return;
  617. is( $series->{directory}, 'assets/spec_downloads', 'the series remembers which directory it indexes' );
  618. my $names = sub {
  619. my ($html) = @_;
  620. return [ $html =~ m{<div class="entry">(file\d+\.txt) \(}g ];
  621. };
  622. ( $code, $body, $err ) = _render( _anon( route => '/specfiles' ), \&Trog::Routes::HTML::series );
  623. is( $code, 200, 'the listing renders' ) or diag($err);
  624. is_deeply( $names->($body), [ map { "file$_.txt" } 1 .. 7 ], 'listing the directory, in name order' );
  625. like( $body, qr/\(10 B\)/, 'with each entry\'s size' );
  626. # post_title.tx quotes with single quotes; the point is the target, not the quoting.
  627. like( $body, qr{href=['"]/assets/spec_downloads/file1\.txt['"]}, 'and a link to the file itself' );
  628. # It paginates like any other datasource page.
  629. ( $code, $body, $err ) = _render( _anon( route => '/specfiles', limit => 3, page => 2 ), \&Trog::Routes::HTML::series );
  630. is( $code, 200, 'page two renders' ) or diag($err);
  631. is_deeply( $names->($body), [qw{file4.txt file5.txt file6.txt}], 'holding the next three' );
  632. like( $body, qr/Page 2 of 3/, 'and saying so' );
  633. # And searches like one.
  634. ( $code, $body, $err ) = _render( _anon( route => '/specfiles', limit => 25, like => 'file3' ), \&Trog::Routes::HTML::series );
  635. is_deeply( $names->($body), ['file3.txt'], 'searching the listing searches the filenames' );
  636. # The point of the exercise: this page is cached like any other, and
  637. # nothing else would ever throw that cache away, because no post is saved
  638. # when somebody drops a file in a directory.
  639. my $tpsgi = Test::TPSGI->new( run_callbacks => 1 );
  640. _render( _anon( route => '/specfiles', tpsgi => $tpsgi ), \&Trog::Routes::HTML::series );
  641. # And it really is cached, rather than merely being cacheable in principle:
  642. # the renderer hands anonymous, unparameterised, successful renders to tPSGI
  643. # to save, and a directory listing is one. Which it may be, unlike the
  644. # guests page above, precisely because it registers the watch below.
  645. ok( scalar( keys %{ $tpsgi->{renders} } ), 'the listing was handed to tPSGI to save as a static' );
  646. ok( ( grep { m{^/specfiles:} } keys %{ $tpsgi->{renders} } ), 'under its own route' );
  647. my ($watch) = grep { $_->{path} =~ m/spec_downloads/ } @{ $tpsgi->{watches} };
  648. ok( $watch, 'rendering it registers a watch on the directory' );
  649. like( $watch->{key}, qr/DirIndex/, 'under a stable key, so a view does not stack another' );
  650. $watch->{callback}->( $tpsgi, { path => 'www/assets/spec_downloads/file8.txt', events => ['CREATE'] } );
  651. is_deeply( $tpsgi->{invalidated}, ['html'], 'and a change to the directory invalidates the renders' );
  652. };
  653. subtest 'the wizard offers the types that exist, and can reopen one' => sub {
  654. # Make a type with everything the form can carry, then check the wizard
  655. # hands it back as the form that would have produced it.
  656. my ( $code, $body, $err ) = _render(
  657. _admin(
  658. route => '/admin/wyzzerdd/save',
  659. method => 'POST',
  660. name => 'spec_reopen',
  661. body_form => 'form_common.tx',
  662. wrapper => 1,
  663. inc_post_title => 1,
  664. inc_tags => 1,
  665. title_placeholder => 'A Widget',
  666. description => 'A widget, with the size it comes in.',
  667. param_name => ['widget_size'],
  668. param_type => ['number'],
  669. param_label => ['Size'],
  670. param_placeholder => ['12'],
  671. param_required => [1],
  672. param_private => [0],
  673. param_indexed => [1],
  674. param_relation_form => ['blog.tx'],
  675. param_relation_mode => ['one'],
  676. display => q{<div class="w"><: $post.widget_size :></div>},
  677. ),
  678. \&Trog::Routes::HTML::post_wizard_save,
  679. );
  680. is( $code, 200, 'the type was created' ) or diag($err);
  681. # The description goes in the sidecar, under the key the validator strips.
  682. my $sidecar = JSON::MaybeXS::decode_json( Path::Tiny->new('www/templates/html/components/forms/spec_reopen.json')->slurp_utf8 );
  683. is( $sidecar->{'x-tcms-post-type'}{description}, 'A widget, with the size it comes in.', 'the description is stored' );
  684. like( $sidecar->{'x-tcms-post-type'}{display}, qr/widget_size/, 'and so is the display template' );
  685. # Now the wizard page itself.
  686. ( $code, $body, $err ) = _render( _admin( route => '/admin/wyzzerdd' ), \&Trog::Routes::HTML::post_wizard );
  687. is( $code, 200, 'the wizard renders' ) or diag($err);
  688. like( $body, qr/id="wizard-existing"/, 'the existing types are a dropdown' );
  689. like( $body, qr/<option value="">A new post type/, 'defaulting to a new one' );
  690. like( $body, qr/<option value="spec_reopen\.tx">/, 'and offering the one we just made' );
  691. like( $body, qr/id="wizard-description-editor"/, 'with a collapsed editor for the description' );
  692. my ($json) = $body =~ m{id="wizard-types"[^>]*>(.*?)</script>}s;
  693. ok( $json, 'the page carries what each type was made from' ) or return;
  694. unlike( $json, qr/</, 'as JSON with no bare < in it, so it cannot end its own script element' );
  695. my $types = JSON::MaybeXS::decode_json($json);
  696. my $mine = $types->{'spec_reopen.tx'};
  697. ok( $mine, 'including the new type' ) or return;
  698. is( $mine->{name}, 'spec_reopen', 'named without the extension' );
  699. is( $mine->{description}, 'A widget, with the size it comes in.', 'with its description' );
  700. like( $mine->{display}, qr/widget_size/, 'and its display template' );
  701. is( $mine->{title_placeholder}, 'A Widget', 'and its placeholder' );
  702. is( $mine->{wrapper}, 1, 'the boxes that were ticked' );
  703. is( $mine->{inc_tags}, 1, 'includes and all' );
  704. is( $mine->{inc_aliases}, 0, 'and only those' );
  705. is( scalar( @{ $mine->{fields} } ), 1, 'and its custom field' );
  706. my $field = $mine->{fields}[0];
  707. is( $field->{name}, 'widget_size', 'by name' );
  708. is( $field->{type}, 'number', 'with the input it was given' );
  709. is( $field->{required}, 1, 'whether it was required' );
  710. is( $field->{indexed}, 1, 'and whether it was indexed' );
  711. # Which is to say: reopening it and saving it back is a round trip, not a
  712. # form somebody has to fill in again from memory.
  713. };
  714. subtest 'a field can be declared indexed' => sub {
  715. my ( $code, $body, $err ) = _render(
  716. _admin(
  717. route => '/admin/wyzzerdd/save',
  718. method => 'POST',
  719. name => 'spec_indexed',
  720. body_form => 'form_common.tx',
  721. wrapper => 1,
  722. inc_post_title => 1,
  723. # The middle row is the one that matters: its box is clear, and the
  724. # wizard zips these arrays together positionally, so if a clear box
  725. # ever submitted nothing the flag would land on the wrong field.
  726. param_name => [ 'cook_time', 'garnish', 'serves' ],
  727. param_type => [ 'text', 'text', 'number' ],
  728. param_label => [ 'Cook Time', 'Garnish', 'Serves' ],
  729. param_placeholder => [ '', '', '' ],
  730. param_required => [ 0, 0, 0 ],
  731. param_private => [ 0, 0, 0 ],
  732. param_indexed => [ 1, 0, 1 ],
  733. param_relation_form => [ 'blog.tx', 'blog.tx', 'blog.tx' ],
  734. param_relation_mode => [ 'one', 'one', 'one' ],
  735. display => q{<div class="ct"><: $post.cook_time :></div>},
  736. ),
  737. \&Trog::Routes::HTML::post_wizard_save,
  738. );
  739. is( $code, 200, 'the type was created' ) or diag($err);
  740. my $sidecar = JSON::MaybeXS::decode_json( Path::Tiny->new('www/templates/html/components/forms/spec_indexed.json')->slurp_utf8 );
  741. ok( $sidecar->{properties}{cook_time}{'x-tcms-indexed'}, 'the ticked field is marked indexed' );
  742. ok( $sidecar->{properties}{serves}{'x-tcms-indexed'}, 'and so is the one after the clear box' );
  743. ok( !exists $sidecar->{properties}{garnish}{'x-tcms-indexed'}, 'the field between them is not' );
  744. ok( !exists $sidecar->{properties}{cook_time}{'x-tcms-private'}, 'and indexing is not privacy' );
  745. is_deeply(
  746. Trog::DataModule::indexed_fields_for('spec_indexed.tx'),
  747. [ sort qw{cook_time serves} ],
  748. 'and the model reads them back out of the sidecar'
  749. );
  750. SKIP: {
  751. skip( "the $MODEL model has nothing to index with", 3 ) unless $MODEL eq 'SQLite';
  752. my $dbh = Trog::SQLite::dbh( undef, 'data/posts.sqlite' );
  753. my %columns = map { $_->{name} => 1 } @{ $dbh->selectall_arrayref( 'PRAGMA table_xinfo(posts)', { Slice => {} } ) };
  754. my %indexes = map { $_->{name} => 1 } @{ $dbh->selectall_arrayref( "SELECT name FROM sqlite_master WHERE type='index' AND tbl_name='posts'", { Slice => {} } ) };
  755. ok( $columns{cook_time}, 'saving the type gave the ticked field a column' );
  756. ok( $indexes{'posts_custom_cook_time'}, 'and an index' );
  757. ok( !$indexes{'posts_custom_garnish'}, 'and left the unticked one alone' );
  758. }
  759. # A post of the type still saves and reads back the same as any other.
  760. _reindex();
  761. _make_series( 'spec_indexed', 'specindexed', 'spec_indexed.tx', 'Spec Indexed Series', no_topbar => 1 ) or return;
  762. my $child = _save_post(
  763. 'spec_indexed child',
  764. form => 'spec_indexed.tx',
  765. title => 'Spec Indexed Child',
  766. cook_time => '45 minutes',
  767. garnish => 'parsley',
  768. visibility => 'public',
  769. tags => ['specindexed'],
  770. to => '/specindexed',
  771. ) or return;
  772. is( $child->{cook_time}, '45 minutes', 'an indexed field stores like any other' );
  773. is( $child->{garnish}, 'parsley', 'and so does the one beside it' );
  774. };
  775. subtest 'a field can be declared editors-only' => sub {
  776. my ( $code, $body, $err ) = _render(
  777. _admin(
  778. route => '/admin/wyzzerdd/save',
  779. method => 'POST',
  780. name => 'spec_secretive',
  781. body_form => 'form_common.tx',
  782. wrapper => 1,
  783. inc_post_title => 1,
  784. inc_tags => 1,
  785. param_name => [ 'shown', 'hidden' ],
  786. param_type => [ 'text', 'text' ],
  787. param_label => [ 'Shown', 'Hidden' ],
  788. param_placeholder => [ '', '' ],
  789. param_required => [ 0, 0 ],
  790. param_private => [ 0, 1 ],
  791. param_relation_form => [ 'blog.tx', 'blog.tx' ],
  792. param_relation_mode => [ 'one', 'one' ],
  793. # Deliberately unguarded: declaring the field private is supposed
  794. # to be enough, so an author does not have to remember.
  795. display => q{<div class="s"><: $post.shown :></div><div class="h"><: $post.hidden :></div>},
  796. ),
  797. \&Trog::Routes::HTML::post_wizard_save,
  798. );
  799. is( $code, 200, 'the type was created' ) or diag($err);
  800. my $sidecar = JSON::MaybeXS::decode_json( Path::Tiny->new('www/templates/html/components/forms/spec_secretive.json')->slurp_utf8 );
  801. ok( $sidecar->{properties}{hidden}{'x-tcms-private'}, 'the private field is marked so' );
  802. ok( !exists $sidecar->{properties}{shown}{'x-tcms-private'}, 'and a public one carries no flag at all' );
  803. _reindex();
  804. _make_series( 'spec_secretive', 'specsecretive', 'spec_secretive.tx', 'Spec Secretive Series', no_topbar => 1 ) or return;
  805. my $child = _save_post(
  806. 'spec_secretive child',
  807. form => 'spec_secretive.tx',
  808. title => 'Spec Secretive Child',
  809. shown => 'public value',
  810. hidden => 'private value',
  811. visibility => 'public',
  812. tags => ['specsecretive'],
  813. to => '/specsecretive',
  814. ) or return;
  815. is( $child->{hidden}, 'private value', 'the value is stored like any other' );
  816. # An editor sees both.
  817. my ( $acode, $abody ) = _render( _admin( route => '/specsecretive' ), \&Trog::Routes::HTML::series );
  818. is( $acode, 200, 'the series renders for an admin' );
  819. like( $abody, qr{<div class="h">private value</div>}, 'who sees the private field' );
  820. # A logged out reader sees only the public one, without the template
  821. # having guarded anything.
  822. my ( $ncode, $nbody ) = _render( _anon( route => '/specsecretive' ), \&Trog::Routes::HTML::series );
  823. is( $ncode, 200, 'and for everyone else' );
  824. like( $nbody, qr{<div class="s">public value</div>}, 'who still sees the public field' );
  825. unlike( $nbody, qr/private value/, 'but not the private one' );
  826. };
  827. #--------------------------------------------------------------------------
  828. # The matrix.
  829. #
  830. # Per type: build a topbar series whose child_form is that type, check it shows
  831. # up in the nav, add a child post, check the child renders on the series page.
  832. #
  833. # Everything is verified ANONYMOUSLY. can_edit is then false, so the editor
  834. # half of each form never renders and a title appears exactly once -- which is
  835. # what makes like($body, qr/$title/) mean anything. It also sidesteps the
  836. # /secure prefixing that both _post_helper and categories.tx apply when a user
  837. # is set.
  838. #--------------------------------------------------------------------------
  839. sub _make_series {
  840. my ( $label, $aclname, $child_form, $title, %opt ) = @_;
  841. # _get_series caps the bar at 10 and the seeds already use two, so only the
  842. # series whose topbar behaviour we actually care about get tagged.
  843. my @tags = $opt{no_topbar} ? ('series') : ( 'series', 'topbar' );
  844. my %extra = map { $_ => $opt{$_} } grep { $_ ne 'no_topbar' } keys(%opt);
  845. my $series = _save_post(
  846. "$label series",
  847. %extra,
  848. form => 'series.tx',
  849. title => $title,
  850. aclname => $aclname, # required by series.json
  851. child_form => $child_form, # required by series.json
  852. local_href => "/$aclname",
  853. href => "/$aclname",
  854. data => "$title subhead",
  855. callback => 'Trog::Routes::HTML::series',
  856. visibility => 'public',
  857. tags => \@tags,
  858. tiled => 0,
  859. to => '/',
  860. ) or return undef;
  861. return $series if $opt{no_topbar};
  862. # The topbar comes from _get_series(), which index() renders through
  863. # categories.tx. Check it on / -- the series has no children yet, and
  864. # posts() 404s on an empty series.
  865. my ( $code, $body, $err ) = _render( _anon( route => '/' ) );
  866. is( $code, 200, "$label: / renders" ) or diag($err);
  867. my @titles = _topbar_titles($body);
  868. ok( ( grep { $_ eq $title } @titles ), "$label: series is in the topbar" )
  869. or diag( 'topbar was: ' . join( ', ', @titles ) );
  870. return $series;
  871. }
  872. sub _series_page {
  873. my ( $label, $aclname, $series_title, $expected_posts ) = @_;
  874. my ( $code, $body, $err ) = _render( _anon( route => "/$aclname" ), \&Trog::Routes::HTML::series );
  875. is( $code, 200, "$label: series page renders" ) or do { diag($err); return '' };
  876. like( $body, qr{<title>[^<]*\Q$series_title\E}, "$label: series page is the right series" );
  877. is( _post_count($body), $expected_posts, "$label: exactly $expected_posts post(s) listed" )
  878. or diag( _kontent($body) );
  879. return $body;
  880. }
  881. # Entities first: the invoice type resolves payee/payor against existing public
  882. # entities.tx posts, so those have to be in the datastore before we get there.
  883. our ( $PAYEE, $PAYOR );
  884. subtest 'entities' => sub {
  885. my $title = 'Spec Entities Series';
  886. _make_series( 'entities', 'specentities', 'entities.tx', $title ) or return;
  887. $PAYEE = _save_post(
  888. 'entities payee child',
  889. form => 'entities.tx',
  890. title => 'Spec Payee Entity',
  891. data => 'Acme Payments LLC, 1 Road, Metropolis',
  892. payment_method => 'ACH',
  893. payment_details => 'Routing 0000 Account 1111',
  894. visibility => 'public',
  895. tags => ['specentities'],
  896. to => '/specentities',
  897. ) or return;
  898. $PAYOR = _save_post(
  899. 'entities payor child',
  900. form => 'entities.tx',
  901. title => 'Spec Payor Entity',
  902. data => 'Wile E Coyote, PO Box 9',
  903. payment_method => 'Carrier Pigeon',
  904. payment_details => 'none',
  905. visibility => 'public',
  906. tags => ['specentities'],
  907. to => '/specentities',
  908. ) or return;
  909. my $body = _series_page( 'entities', 'specentities', $title, 2 ) or return;
  910. like( $body, qr{id="postData-\Q$PAYEE->{id}\E"}, 'payee body rendered' );
  911. like( $body, qr/Acme Payments LLC/, 'payee data rendered' );
  912. like( $body, qr/Wile E Coyote/, 'payor data rendered' );
  913. # entity_details.tx is included only in the editor half, so these are stored
  914. # but never displayed. Pinning that so a template change is noticed.
  915. unlike( $body, qr/Carrier Pigeon/, 'payment details are not shown to anonymous readers' );
  916. is( _find_post('Spec Payee Entity')->{payment_method}, 'ACH', 'but payment_method did survive the schema' );
  917. };
  918. subtest 'blog' => sub {
  919. my $title = 'Spec Blog Series';
  920. _make_series( 'blog', 'specblog', 'blog.tx', $title ) or return;
  921. my $child = _save_post(
  922. 'blog child',
  923. form => 'blog.tx',
  924. title => 'Spec Blog Child',
  925. data => 'Spec blog body text.',
  926. visibility => 'public',
  927. tags => ['specblog'],
  928. to => '/specblog',
  929. ) or return;
  930. my $body = _series_page( 'blog', 'specblog', $title, 1 ) or return;
  931. like( $body, qr/Spec Blog Child/, 'child title rendered' );
  932. like( $body, qr{href='/posts/\Q$child->{id}\E'}, 'child permalink rendered' );
  933. like( $body, qr{id="postData-\Q$child->{id}\E"}, 'child body block rendered' );
  934. like( $body, qr/Spec blog body text\./, 'child body text rendered' );
  935. unlike( $body, qr/Spec Payee Entity/, 'no bleed from the entities series' );
  936. };
  937. subtest 'microblog' => sub {
  938. my $title = 'Spec Microblog Series';
  939. _make_series( 'microblog', 'specmicroblog', 'microblog.tx', $title ) or return;
  940. my $child = _save_post(
  941. 'microblog child',
  942. form => 'microblog.tx',
  943. title => 'Spec Microblog Child',
  944. href => 'https://example.com/spec',
  945. data => 'Spec microblog body.',
  946. visibility => 'public',
  947. tags => ['specmicroblog'],
  948. to => '/specmicroblog',
  949. ) or return;
  950. my $body = _series_page( 'microblog', 'specmicroblog', $title, 1 ) or return;
  951. like( $body, qr{href='https://example\.com/spec' >Spec Microblog Child</a>}, 'title links out to href' );
  952. like( $body, qr{id="postData-\Q$child->{id}\E"}, 'body block rendered' );
  953. like( $body, qr/Spec microblog body\./, 'body text rendered' );
  954. };
  955. subtest 'file' => sub {
  956. my $title = 'Spec File Series';
  957. _make_series( 'file', 'specfile', 'file.tx', $title ) or return;
  958. # _handle_upload MOVES the file, so it has to be created fresh here.
  959. my $src = "$ROOT/upload-src/spec-upload.txt";
  960. open( my $fh, '>', $src ) or die $!;
  961. print {$fh} "spec upload contents\n";
  962. close $fh;
  963. my $child = _save_post(
  964. 'file child',
  965. form => 'file.tx',
  966. title => 'Spec File Child',
  967. data => 'Spec file body.',
  968. file => { tempname => $src, filename => 'spec-upload.txt' },
  969. visibility => 'public',
  970. tags => ['specfile'],
  971. to => '/specfile',
  972. ) or return;
  973. ok( !-e $src, 'the upload was moved out of its temp location, not copied' );
  974. ok( -f "www/assets/$child->{id}.spec-upload.txt", 'and it landed in www/assets' );
  975. my $body = _series_page( 'file', 'specfile', $title, 1 ) or return;
  976. like( $body, qr{href='/assets/\Q$child->{id}\E\.spec-upload\.txt'}, 'title links to the asset' );
  977. like( $body, qr{id="postData-\Q$child->{id}\E"}, 'body block carries a unique id, like every other form' );
  978. like( $body, qr/Spec file body\./, 'body text rendered' );
  979. # This form used to emit <div class="postData" id="postData" class="responsive-text">
  980. # -- a duplicated class attribute, and an id shared by every file post on
  981. # the page. Neither should come back.
  982. unlike( $body, qr{<div class="postData" id="postData"}, 'no duplicated class attribute' );
  983. # text/plain, so none of the media branches fire.
  984. unlike( $body, qr/<video/, 'no video block for a text file' );
  985. unlike( $body, qr/<audio/, 'no audio block either' );
  986. };
  987. subtest 'presentation' => sub {
  988. my $title = 'Spec Presentation Series';
  989. _make_series( 'presentation', 'specpresentation', 'presentation.tx', $title ) or return;
  990. my $child = _save_post(
  991. 'presentation child',
  992. form => 'presentation.tx',
  993. title => 'Spec Presentation Child',
  994. data => [ 'Slide one body.', 'Slide two body.' ],
  995. data_is_array => 1,
  996. visibility => 'public',
  997. tags => ['specpresentation'],
  998. to => '/specpresentation',
  999. ) or return;
  1000. is_deeply( $child->{data}, [ 'Slide one body.', 'Slide two body.' ], 'the multi-page data round-tripped as an array' );
  1001. my $body = _series_page( 'presentation', 'specpresentation', $title, 1 ) or return;
  1002. # Slides only render under nochrome; the series page just links to the deck.
  1003. like( $body, qr{<a href="/posts/\Q$child->{id}\E\?embed=1&nochrome=1">Click Here to view</a>}, 'deck link rendered' );
  1004. unlike( $body, qr/Slide one body\./, 'slides themselves are not rendered inline' );
  1005. };
  1006. subtest 'invoice' => sub {
  1007. my $title = 'Spec Invoice Series';
  1008. _make_series( 'invoice', 'specinvoice', 'invoice.tx', $title ) or return;
  1009. my $child = _save_post(
  1010. 'invoice child',
  1011. form => 'invoice.tx',
  1012. title => 'Spec Invoice Child',
  1013. data => [ "Widget assembly\nPrice: \$420", "Shipping\nPrice: \$80" ],
  1014. data_is_array => 1,
  1015. payee => $PAYEE->{id},
  1016. payor => $PAYOR->{id},
  1017. due_days => 30,
  1018. visibility => 'public',
  1019. tags => ['specinvoice'],
  1020. to => '/specinvoice',
  1021. ) or return;
  1022. my $body = _series_page( 'invoice', 'specinvoice', $title, 1 ) or return;
  1023. like( $body, qr/Invoice ID# \Q$child->{id}\E/, 'invoice header rendered' );
  1024. # These two only resolve because the entities subtest ran first and left
  1025. # public entities.tx posts behind for the enrich hook to find.
  1026. like( $body, qr/Acme Payments LLC/, 'payee entity resolved' );
  1027. like( $body, qr/Wile E Coyote/, 'payor entity resolved' );
  1028. like( $body, qr/ACH/, 'payee payment method pulled through' );
  1029. like( $body, qr/Widget assembly/, 'line items rendered' );
  1030. like( $body, qr/Total: \$500/, 'total summed from the line item prices' );
  1031. };
  1032. subtest 'spec_widget (the wizard-built type)' => sub {
  1033. my $title = 'Spec Widget Series';
  1034. _make_series( 'spec_widget', 'specwidget', 'spec_widget.tx', $title ) or return;
  1035. my $child = _save_post(
  1036. 'spec_widget child',
  1037. form => 'spec_widget.tx',
  1038. title => 'Spec Widget Child',
  1039. data => 'Spec widget body.',
  1040. flavor => 'Strawberry',
  1041. bogus_field => 'nope',
  1042. visibility => 'public',
  1043. tags => ['specwidget'],
  1044. to => '/specwidget',
  1045. ) or return;
  1046. is( $child->{flavor}, 'Strawberry', 'the custom field survived validation' );
  1047. ok( !exists $child->{bogus_field}, 'an undeclared field was still stripped' );
  1048. my $body = _series_page( 'spec_widget', 'specwidget', $title, 1 ) or return;
  1049. # The payoff: this can only render if the wizard wrote spec_widget.json,
  1050. # schema_for merged it over the base post schema, and validate() therefore
  1051. # kept 'flavor' instead of deleting it as an unknown key.
  1052. like( $body, qr{<span class="spec-flavor">Strawberry</span>}, 'the custom field rendered on the page' );
  1053. like( $body, qr/Spec widget body\./, 'and the body came through the generated template' );
  1054. };
  1055. subtest 'a wizard-built type can depend on another type' => sub {
  1056. # The type we will point at. The relation is what is under test, so keep
  1057. # the target itself boring.
  1058. my ( $code, $body, $err ) = _render(
  1059. _admin(
  1060. route => '/admin/wyzzerdd/save',
  1061. method => 'POST',
  1062. name => 'spec_target',
  1063. body_form => 'form_common.tx',
  1064. wrapper => 1,
  1065. inc_post_title => 1,
  1066. inc_title_input => 1,
  1067. inc_visibility => 1,
  1068. inc_tags => 1,
  1069. display => q{<div><: render_it($post.data) | mark_raw :></div>},
  1070. ),
  1071. \&Trog::Routes::HTML::post_wizard_save,
  1072. );
  1073. is( $code, 200, 'target type created' ) or diag($err);
  1074. # ...and the type that depends on it: one picked by id, one pulling in the
  1075. # whole set.
  1076. ( $code, $body, $err ) = _render(
  1077. _admin(
  1078. route => '/admin/wyzzerdd/save',
  1079. method => 'POST',
  1080. name => 'spec_relator',
  1081. body_form => 'form_common.tx',
  1082. wrapper => 1,
  1083. inc_post_title => 1,
  1084. inc_title_input => 1,
  1085. inc_visibility => 1,
  1086. inc_tags => 1,
  1087. param_name => [ 'chosen', 'everything' ],
  1088. param_type => [ 'relation', 'relation' ],
  1089. param_label => [ 'Chosen One', 'All Of Them' ],
  1090. param_placeholder => [ '', '' ],
  1091. param_required => [ 0, 0 ],
  1092. param_relation_form => [ 'spec_target.tx', 'spec_target.tx' ],
  1093. param_relation_mode => [ 'one', 'all' ],
  1094. 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>},
  1095. ),
  1096. \&Trog::Routes::HTML::post_wizard_save,
  1097. );
  1098. is( $code, 200, 'relating type created' ) or diag($err);
  1099. my $sidecar = JSON::MaybeXS::decode_json( Path::Tiny->new('www/templates/html/components/forms/spec_relator.json')->slurp_utf8 );
  1100. # 'one' is a field the post stores; 'all' is not a field at all.
  1101. is( $sidecar->{properties}{chosen}{type}, 'relation', 'the picked relation is a stored property' );
  1102. is( $sidecar->{properties}{chosen}{'x-tcms-relation-form'}, 'spec_target.tx', 'naming its target type' );
  1103. ok( !exists $sidecar->{properties}{everything}, "the 'all' relation stores nothing" );
  1104. is_deeply(
  1105. $sidecar->{'x-tcms-relations'},
  1106. {
  1107. chosen_post => { form => 'spec_target.tx', from => 'chosen' },
  1108. everything => { form => 'spec_target.tx' },
  1109. },
  1110. 'and both are declared for resolution at render'
  1111. );
  1112. # The relation pseudo-type has to become a real one before validation, or
  1113. # every relation field would be stripped as an unknown type.
  1114. is(
  1115. Trog::DataModule::schema_for('spec_relator.tx')->{properties}{chosen}{type},
  1116. 'string', "'relation' expands to a real schema type"
  1117. );
  1118. _reindex();
  1119. # Now exercise it end to end.
  1120. _make_series( 'spec_target', 'spectarget', 'spec_target.tx', 'Spec Target Series', no_topbar => 1 ) or return;
  1121. my $target = _save_post(
  1122. 'spec_target child',
  1123. form => 'spec_target.tx',
  1124. title => 'Spec Target Post',
  1125. data => 'Spec target body.',
  1126. visibility => 'public',
  1127. tags => ['spectarget'],
  1128. to => '/spectarget',
  1129. ) or return;
  1130. _make_series( 'spec_relator', 'specrelator', 'spec_relator.tx', 'Spec Relator Series', no_topbar => 1 ) or return;
  1131. my $relator = _save_post(
  1132. 'spec_relator child',
  1133. form => 'spec_relator.tx',
  1134. title => 'Spec Relator Post',
  1135. data => 'Spec relator body.',
  1136. chosen => $target->{id},
  1137. visibility => 'public',
  1138. tags => ['specrelator'],
  1139. to => '/specrelator',
  1140. ) or return;
  1141. is( $relator->{chosen}, $target->{id}, 'the referenced id survived validation' );
  1142. my $page = _series_page( 'spec_relator', 'specrelator', 'Spec Relator Series', 1 ) or return;
  1143. # Both halves of the relation resolved: the one we picked, and the set.
  1144. like( $page, qr{<span class="chosen">Spec Target Post</span>}, 'the picked post resolved into the page' );
  1145. like( $page, qr{<span class="each">Spec Target Post</span>}, 'and so did the whole set' );
  1146. };
  1147. subtest '/api/posts_of_form feeds the relation picker' => sub {
  1148. my $target = _find_post('Spec Target Post');
  1149. ok( $target, 'the target post is there to be listed' ) or return;
  1150. my $res = Trog::Routes::JSON::posts_of_form( _admin( route => '/api/posts_of_form', form => 'spec_target.tx' ) );
  1151. is( ref $res, 'ARRAY', 'a PSGI response came back' ) or return;
  1152. my ( $code, undef, $body ) = @$res;
  1153. is( $code, 200, 'and it is a 200' );
  1154. my $payload = JSON::MaybeXS::decode_json( join( '', @$body ) );
  1155. is_deeply(
  1156. $payload->{posts},
  1157. [ { id => $target->{id}, title => 'Spec Target Post' } ],
  1158. 'listing exactly the posts of that type, id and title only'
  1159. );
  1160. # An unknown type is an empty list, not an error -- a type with no posts
  1161. # yet is the normal state of affairs right after you create it.
  1162. $res = Trog::Routes::JSON::posts_of_form( _admin( route => '/api/posts_of_form', form => 'nosuchtype.tx' ) );
  1163. $payload = JSON::MaybeXS::decode_json( join( '', @{ $res->[2] } ) );
  1164. is_deeply( $payload->{posts}, [], 'an unknown type lists nothing rather than failing' );
  1165. # The route's own declaration is what keeps a malformed form out; check it
  1166. # matches what series.json demands of child_form.
  1167. my $validator = $Trog::Routes::JSON::routes{'/api/posts_of_form'}{parameters}{form};
  1168. ok( $validator->('blog.tx'), 'the parameter validator accepts a form name' );
  1169. ok( !$validator->('../../etc/passwd'), 'and rejects a path' );
  1170. ok( $Trog::Routes::JSON::routes{'/api/posts_of_form'}{auth}, 'the route requires a login' );
  1171. };
  1172. subtest 'a series resolves its relations for logged out visitors too' => sub {
  1173. # The relations series() resolves land on the primary post, which is what a
  1174. # datasource reads to find its hypervisors -- so assert on that rather than
  1175. # on the rendered children, whose relations posts() resolves later, after
  1176. # it has widened user_acls and thus by a path that was never broken.
  1177. foreach my $case ( [ 'anonymously', _anon( route => '/specrelator' ) ], [ 'as an admin', _admin( route => '/specrelator' ) ] ) {
  1178. my ( $label, $query ) = @$case;
  1179. my ( $code, undef, $err ) = _render( $query, \&Trog::Routes::HTML::series );
  1180. is( $code, 200, "the series renders $label" ) or do { diag($err); next };
  1181. my $resolved = $query->{primary_post}{everything};
  1182. is( ref $resolved, 'ARRAY', "$label, the series' own relation resolved" );
  1183. cmp_ok( scalar @{ $resolved || [] }, '>', 0, "$label, to something rather than nothing" );
  1184. }
  1185. };
  1186. subtest 'saves report back through the jsalert banner' => sub {
  1187. # A good save redirects to where you came from, carrying the outcome.
  1188. my $res = Trog::Routes::HTML::post_save(
  1189. _admin(
  1190. route => '/post/save',
  1191. method => 'POST',
  1192. to => '/specblog',
  1193. form => 'blog.tx',
  1194. title => 'Spec Feedback Child',
  1195. data => 'Spec feedback body.',
  1196. visibility => 'public',
  1197. tags => ['specblog'],
  1198. )
  1199. );
  1200. my ( $code, $headers ) = @$res;
  1201. my %h = @{ $headers || [] };
  1202. is( $code, 303, 'a good save redirects' );
  1203. is( $h{Location}, '/secure/specblog', 'to where we came from, and nowhere else' );
  1204. # The outcome rides in a cookie, not the URL. It used to be a query
  1205. # parameter, and a save which failed with a stack trace attached built a URL
  1206. # of several thousand characters that tPSGI answered with a 419 -- so the
  1207. # user saw neither the page nor the error.
  1208. unlike( $h{Location}, qr/[?&]/, 'the URL carries no message at all' );
  1209. ok( length( $h{Location} ) < 2048, 'so it cannot outgrow what a server will accept' );
  1210. like( $h{'Set-Cookie'}, qr/^tcmsfeedback=0:/, 'the outcome is in a cookie instead' );
  1211. unlike( $h{'Set-Cookie'}, qr/\n/, 'and the message is one line, since it lands in a JS string' );
  1212. _reindex();
  1213. # Follow the redirect the way a browser would: same destination, carrying
  1214. # the cookie it was just handed.
  1215. my $feedback = ( split( /;/, $h{'Set-Cookie'} ) )[0];
  1216. my ( $rcode, $body, $err ) = _render(
  1217. _admin( route => '/specblog', cookies => $feedback ),
  1218. \&Trog::Routes::HTML::series,
  1219. );
  1220. is( $rcode, 200, 'the destination renders' ) or diag($err);
  1221. like( $body, qr/var loginFailure = 0;/, 'the banner is in success mode' );
  1222. like( $body, qr/Saved post &#39;Spec Feedback Child&#39;\./, 'and says what was saved' );
  1223. # Nothing to navigate on to, so the banner must not bounce us anywhere.
  1224. unlike( $body, qr/window\.location=/, 'and does not redirect onwards' );
  1225. # A rejected save comes back the same way, in red.
  1226. $res = Trog::Routes::HTML::post_save(
  1227. _admin(
  1228. route => '/post/save',
  1229. method => 'POST',
  1230. to => '/specblog',
  1231. form => 'blog.tx',
  1232. title => 'Spec Rejected Child',
  1233. visibility => 'not-a-visibility',
  1234. tags => ['specblog'],
  1235. )
  1236. );
  1237. ( $code, $headers ) = @$res;
  1238. %h = @{ $headers || [] };
  1239. is( $code, 303, 'a rejected save redirects too, rather than dead-ending on a 400' );
  1240. is( $h{Location}, '/secure/specblog', 'to the same place a good one goes' );
  1241. like( $h{'Set-Cookie'}, qr/^tcmsfeedback=1:/, 'flagged as failed' );
  1242. like( URI::Escape::uri_unescape( $h{'Set-Cookie'} ), qr/Not in enum list/, 'carrying the validator error' );
  1243. ok( !_find_post('Spec Rejected Child'), 'and the bad post was not written' );
  1244. $feedback = ( split( /;/, $h{'Set-Cookie'} ) )[0];
  1245. ( $rcode, $body, $err ) = _render(
  1246. _admin( route => '/specblog', cookies => $feedback ),
  1247. \&Trog::Routes::HTML::series,
  1248. );
  1249. is( $rcode, 200, 'the destination still renders' ) or diag($err);
  1250. like( $body, qr/var loginFailure = 1;/, 'the banner is in failure mode' );
  1251. like( $body, qr/Not in enum list/, 'and shows why' );
  1252. # Read once: the cookie is expired by the page that rendered it, or the
  1253. # banner follows the reader around until it times out on its own.
  1254. my ( undef, undef, undef, $rheaders ) = _render(
  1255. _admin( route => '/specblog', cookies => $feedback ),
  1256. \&Trog::Routes::HTML::series,
  1257. );
  1258. my %rh = @{ $rheaders || [] };
  1259. like( $rh{'Set-Cookie'}, qr/^tcmsfeedback=;.*Max-Age=0/, 'and the page that shows it expires it' );
  1260. # A page showing a banner must not be cached, or the one person who saved
  1261. # something has their message served to everybody. The query parameter
  1262. # form was accidentally safe here; a cookie is not.
  1263. my $tpsgi = Test::TPSGI->new( run_callbacks => 1 );
  1264. _render( _anon( route => '/specblog', cookies => $feedback, tpsgi => $tpsgi ), \&Trog::Routes::HTML::series );
  1265. is_deeply( [ keys %{ $tpsgi->{renders} } ], [], 'and it is never saved as a static' );
  1266. };
  1267. subtest 'a hidden id that was never filled in' => sub {
  1268. # Every editor posts <input type="hidden" name="id"> and it is empty for a
  1269. # new post. validate() keeps an empty string for a field the schema types
  1270. # as a string, which id is, so //= saw a defined value and left it -- and
  1271. # the flat file model wrote the post to 'data/files/', the datastore
  1272. # directory rather than a post in it. The error named File::Slurper, and
  1273. # its stack trace then went into the redirect URL and produced a 419.
  1274. my $res = Trog::Routes::HTML::post_save(
  1275. _admin(
  1276. route => '/post/save',
  1277. method => 'POST',
  1278. to => '/specblog',
  1279. id => '',
  1280. form => 'blog.tx',
  1281. title => 'Spec Empty Id Child',
  1282. data => 'Saved despite an empty hidden id.',
  1283. visibility => 'public',
  1284. tags => ['specblog'],
  1285. )
  1286. );
  1287. my ( $code, $headers ) = @$res;
  1288. my %h = @{ $headers || [] };
  1289. is( $code, 303, 'the save succeeds' );
  1290. like( $h{'Set-Cookie'}, qr/^tcmsfeedback=0:/, 'and reports success' );
  1291. _reindex();
  1292. my $saved = _find_post('Spec Empty Id Child');
  1293. ok( $saved, 'the post was written' ) or return;
  1294. ok( length( $saved->{id} // '' ), 'with an id of its own' );
  1295. isnt( $saved->{id}, '', 'rather than the empty one it was handed' );
  1296. # And the datastore directory is still a directory.
  1297. ok( -d 'data/files', 'the datastore was not written over' );
  1298. };
  1299. subtest 'the topbar did not silently overflow' => sub {
  1300. my ( $code, $body, $err ) = _render( _anon( route => '/' ) );
  1301. is( $code, 200, '/ renders' ) or diag($err);
  1302. my @titles = _topbar_titles($body);
  1303. # 2 seeded series (Series, About) + the 7 we built. _get_series() caps at
  1304. # 10 (HTML.pm), so an eighth post type would start silently dropping one.
  1305. is( scalar @titles, 9, 'every series we made is in the topbar' )
  1306. or diag( 'topbar was: ' . join( ', ', @titles ) );
  1307. cmp_ok( scalar @titles, '<=', 10, 'and we are not at the _get_series limit' );
  1308. };
  1309. subtest 'the tpsgi side effects stayed inert' => sub {
  1310. cmp_ok( $TPSGI->{restarts}, '>', 0, 'post_save did try to signal a restart' );
  1311. cmp_ok( $TPSGI->{callbacks}, '>', 0, 'and did queue post-close callbacks' );
  1312. # We never run the queued callbacks, which is what keeps save_render and
  1313. # invalidate_renders from ever firing.
  1314. is_deeply( $TPSGI->{renders}, {}, 'no static renders were written' );
  1315. is_deeply( $TPSGI->{invalidated}, [], 'and nothing was invalidated' );
  1316. my @statics = glob('www/statics/*');
  1317. is_deeply( \@statics, [], 'www/statics is empty' );
  1318. };
  1319. subtest 'the real repo was not touched' => sub {
  1320. my %after = map { _snapshot("$REPO/$_") } qw{config data www/templates www/assets logs totp};
  1321. my @changed = grep { ( $REPO_BEFORE{$_} // '' ) ne ( $after{$_} // '' ) } keys %after;
  1322. my @removed = grep { !exists $after{$_} } keys %REPO_BEFORE;
  1323. is_deeply( [ sort @changed ], [], 'no repo file was added or modified' );
  1324. is_deeply( [ sort @removed ], [], 'and none were removed' );
  1325. ok( !-e "$REPO/www/templates/html/components/forms/spec_widget.tx", 'the wizard type is not in the repo' );
  1326. };
  1327. done_testing();