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

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