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

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