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

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