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

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