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

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