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

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