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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949
  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 strict;
  10. use warnings;
  11. # FindBin MUST come first. $FindBin::Bin is derived from $0, which prove hands
  12. # us relatively, and it is computed once. chdir before this loads and every
  13. # module's `use FindBin::libs` resolves against the sandbox instead of the repo.
  14. use FindBin;
  15. use lib "$FindBin::Bin/../lib";
  16. use Test::More;
  17. use Cwd ();
  18. use Encode ();
  19. use File::Copy ();
  20. use File::Find ();
  21. use File::Path ();
  22. use File::Temp ();
  23. use Time::HiRes ();
  24. use URI::Escape ();
  25. use JSON::MaybeXS ();
  26. our ( $REPO, $ROOT, $OLDCWD );
  27. our %REPO_BEFORE;
  28. # name => (size, mtime) for every file under the repo dirs this test could
  29. # plausibly disturb. Cheap enough, and it is the only real proof of isolation.
  30. sub _snapshot {
  31. my ($dir) = @_;
  32. my %seen;
  33. File::Find::find(
  34. {
  35. no_chdir => 1,
  36. wanted => sub {
  37. return unless -f $File::Find::name;
  38. my @st = stat(_);
  39. $seen{$File::Find::name} = "$st[7]:$st[9]";
  40. },
  41. },
  42. $dir
  43. );
  44. return %seen;
  45. }
  46. sub _copy_tree {
  47. my ( $from, $to ) = @_;
  48. File::Path::make_path($to);
  49. File::Find::find(
  50. {
  51. no_chdir => 1,
  52. wanted => sub {
  53. my $rel = substr( $File::Find::name, length($from) );
  54. return unless length $rel;
  55. my $dst = "$to$rel";
  56. if ( -d $File::Find::name ) { File::Path::make_path($dst) }
  57. elsif ( -f $File::Find::name ) { File::Copy::copy( $File::Find::name, $dst ) or die "copy $File::Find::name: $!" }
  58. },
  59. },
  60. $from
  61. );
  62. return;
  63. }
  64. # Everything the sandbox needs, in one BEGIN. The Trog:: modules are require()d
  65. # at runtime below, which is unconditionally after every BEGIN -- so no later
  66. # edit can accidentally load them before the chdir. That matters: TCMS.pm runs
  67. # build_routes() at file scope and FlatFile.pm reads the tag index at file
  68. # scope, both against whatever cwd happens to be current.
  69. BEGIN {
  70. $REPO = Cwd::abs_path("$FindBin::Bin/..");
  71. $OLDCWD = Cwd::getcwd();
  72. %REPO_BEFORE = map { _snapshot("$REPO/$_") } qw{config data www/templates www/assets logs totp};
  73. $ROOT = File::Temp::tempdir( 'tcms-lifecycle-XXXXXX', TMPDIR => 1, CLEANUP => 0 );
  74. # Installer.mk's tree, plus upload-src for the file.tx fixture.
  75. File::Path::make_path(
  76. map { "$ROOT/$_" } qw{
  77. config schema data/files logs totp upload-src
  78. www/assets/private www/statics www/themes www/scripts
  79. }
  80. );
  81. # A real fresh install: get() looks for config/main.cfg, doesn't find one,
  82. # and falls through to the shipped default.
  83. File::Copy::copy( "$REPO/config/default.cfg", "$ROOT/config/default.cfg" ) or die $!;
  84. # Hardcoded paths in Auth.pm, TagIndex.pm and Log.pm -- not negotiable.
  85. File::Copy::copy( "$REPO/schema/$_", "$ROOT/schema/$_" ) or die $! for qw{auth.schema flatfile.schema log.schema};
  86. # COPY, don't symlink: post_wizard_save() writes into Trog::Themes::forms_dir(),
  87. # and a symlink would land the generated post type in the real repo.
  88. _copy_tree( "$REPO/www/templates", "$ROOT/www/templates" );
  89. # posts() renders the emoji picker unconditionally, and EmojiPicker dies
  90. # outright if this file is missing. Only category and emoji are read.
  91. open( my $fh, '>', "$ROOT/www/scripts/list.min.json" ) or die $!;
  92. print {$fh} '{"emojis":[{"category":"Smileys","emoji":"X"}]}';
  93. close $fh;
  94. # Text::Xslate computes its default cache dir from $HOME once, at load time.
  95. # Without this the sandbox writes compiled templates into the real ~/.xslate_cache.
  96. $ENV{HOME} = $ROOT;
  97. chdir($ROOT) or die "could not chdir to sandbox $ROOT: $!";
  98. }
  99. END {
  100. # Never rmtree the directory you are standing in.
  101. chdir($OLDCWD) if $OLDCWD;
  102. if ( $ENV{TCMS_TEST_KEEP} ) {
  103. diag("TCMS_TEST_KEEP set, sandbox left at $ROOT");
  104. }
  105. elsif ( $ROOT && -d $ROOT ) {
  106. # SQLite handles are file-lexical in Trog::SQLite and unreachable from
  107. # here; DBI disconnects at global destruction, after these are gone.
  108. eval { File::Path::remove_tree($ROOT) };
  109. }
  110. }
  111. diag("sandbox: $ROOT");
  112. require Trog::Log;
  113. Trog::Log::log_init( 'logs/tcms.log', 'info' ); # sets $LOGDIR, hence logs/log.db
  114. require Trog::Config;
  115. require Trog::Themes;
  116. require Trog::Data;
  117. require Trog::Auth;
  118. require Trog::SQLite::TagIndex;
  119. require Trog::Routes::HTML;
  120. require Trog::Routes::JSON;
  121. #--------------------------------------------------------------------------
  122. # A stand-in for the tPSGI object the router injects as $query->{tpsgi}.
  123. #--------------------------------------------------------------------------
  124. {
  125. package Test::TPSGI;
  126. sub new {
  127. my ( $class, %args ) = @_;
  128. return bless {
  129. callbacks => 0,
  130. renders => {},
  131. invalidated => [],
  132. restarts => 0,
  133. tpsgi_dir => Cwd::getcwd(),
  134. log_dir => 'logs',
  135. gid => $),
  136. verbose => 0,
  137. %args,
  138. }, $class;
  139. }
  140. sub INFO {1}
  141. sub DEBUG {1}
  142. sub WARN {1}
  143. sub ERROR {1}
  144. sub CRIT {1}
  145. sub ALERT {1}
  146. sub EMERG {1}
  147. sub FATAL {1}
  148. sub see_also { return [ 303, [ 'Location' => $_[1], 'Content-Length' => 0 ], [''] ] }
  149. sub redirect { return [ 302, [ 'Location' => $_[1], 'Content-Length' => 0 ], [''] ] }
  150. sub redirect_permanent { return [ 301, [ 'Location' => $_[1], 'Content-Length' => 0 ], [''] ] }
  151. sub _reply { return [ $_[1], [ 'Content-type' => 'text/html' ], [ defined $_[2] ? $_[2] : '' ] ] }
  152. sub ok { return $_[0]->_reply( 200, $_[2] ) }
  153. sub notfound { return $_[0]->_reply( 404, $_[2] // 'Not Found' ) }
  154. sub forbidden { return $_[0]->_reply( 403, $_[2] // 'Forbidden' ) }
  155. sub badrequest { return $_[0]->_reply( 400, $_[2] // 'Bad Request' ) }
  156. sub error { return $_[0]->_reply( 500, $_[2] // 'Error' ) }
  157. sub serve { return [ 200, [], [''] ] }
  158. # These two must be inert.
  159. #
  160. # add_post_close_callback is the ONLY path by which Trog::Renderer and
  161. # post_save reach save_render()/invalidate_renders(). Dropping the callback
  162. # on the floor is what guarantees this test never writes into www/statics,
  163. # whatever the renderer's own skip-save logic decides.
  164. sub add_post_close_callback { $_[0]{callbacks}++; return 1 }
  165. # The real one is `kill 'HUP', getppid`. Under prove, that is prove.
  166. sub signal_restart_parent { $_[0]{restarts}++; return 1 }
  167. sub invalidate_renders { push @{ $_[0]{invalidated} }, $_[1]; return 1 }
  168. sub invalidate_render { push @{ $_[0]{invalidated} }, [ @_[ 1 .. $#_ ] ]; return 1 }
  169. sub save_render { $_[0]{renders}{"$_[1]:$_[2]"} = $_[3]; return 1 }
  170. }
  171. our $TPSGI = Test::TPSGI->new();
  172. our $ADMIN_USER = 'specadmin';
  173. our $ADMIN_DISPLAY = 'Spec Admin';
  174. our $ADMIN_EMAIL = 'specadmin@example.com';
  175. our $ADMIN_PASS = 'spec-password';
  176. #--------------------------------------------------------------------------
  177. # Harness
  178. #--------------------------------------------------------------------------
  179. # Always build a fresh query: posts() pushes onto user_acls, and series()
  180. # rewrites route/aclname/tag/in_series/primary_post in place.
  181. sub _query {
  182. my (%over) = @_;
  183. my %q = (
  184. route => '/',
  185. method => 'GET',
  186. scheme => 'http', # Renderer::Base compares this with no undef guard
  187. domain => 'tcms.test',
  188. start => [ Time::HiRes::gettimeofday() ], # tv_interval() dies on anything else
  189. deflate => 0,
  190. streaming => 0,
  191. ranges => [],
  192. last_fetched => undef,
  193. has_query => 0,
  194. social_meta => 0,
  195. acls => [],
  196. user_acls => [],
  197. body => undef,
  198. tpsgi => $TPSGI,
  199. %over,
  200. );
  201. $q{fullpath} //= $q{route};
  202. return \%q;
  203. }
  204. sub _anon { return _query( user => undef, user_acls => [], @_ ) }
  205. sub _admin { return _query( user => $ADMIN_USER, user_acls => ['admin'], @_ ) }
  206. # Returns ($code, $body, $error). Never dies, so one bad post type cannot take
  207. # the rest of the file with it -- which matters because a failed render inside
  208. # index() dies rather than returning a 500 (there is no www/templates/html/500.tx).
  209. sub _render {
  210. my ( $query, $how ) = @_;
  211. $how ||= \&Trog::Routes::HTML::index;
  212. my $res = eval { $how->($query) };
  213. return ( 0, '', "died: $@" ) if !$res;
  214. return ( 0, '', 'returned a ' . ( ref($res) || 'plain scalar' ) ) if ref $res ne 'ARRAY';
  215. my ( $code, $headers, $body ) = @$res;
  216. $body = ref $body eq 'ARRAY' ? join( '', @$body ) : ( $body // '' );
  217. return ( $code, Encode::decode_utf8($body), '', $headers );
  218. }
  219. # FlatFile snapshots the tag list at load time and then filters each query's
  220. # tags against it IN PLACE -- so a tag created later isn't merely unindexed, it
  221. # is deleted from the query, and the filter silently degrades to "every public
  222. # post". Production gets away with it because a save HUPs the parent and the
  223. # worker re-execs. We have to do it by hand.
  224. sub _reindex {
  225. no warnings 'once';
  226. @Trog::Data::FlatFile::tags = Trog::SQLite::TagIndex::tags();
  227. %Trog::Data::FlatFile::posts_by_tag = ();
  228. return;
  229. }
  230. sub _data { return Trog::Data->new( Trog::Config::get() ) }
  231. # categories.tx renders into <span id="categories">. Scope to it -- index.tx
  232. # emits other class="topbar" anchors outside that span.
  233. sub _topbar_titles {
  234. my ($body) = @_;
  235. my ($span) = $body =~ m{<span id="categories">(.*?)</span>}s;
  236. return () unless defined $span;
  237. return $span =~ m{class="topbar">([^<]*)</a>}g;
  238. }
  239. # post_title.tx emits exactly one of these per displayed post.
  240. sub _post_count {
  241. my $n = () = $_[0] =~ m{<h3 class='blogtitles'>}g;
  242. return $n;
  243. }
  244. # The rendered page is ~40KB and mostly JavaScript. Show the content well.
  245. sub _kontent {
  246. my ($body) = @_;
  247. my ($k) = $body =~ m{<div id="kontent" class="kontained">(.*?)<div id="rightbar"}s;
  248. $k //= $body;
  249. $k =~ s/<script\b.*?<\/script>//gs;
  250. return length($k) > 2500 ? substr( $k, 0, 2500 ) . "\n...[truncated]" : $k;
  251. }
  252. # Save through post_save() rather than $data->add(): add() dies with an
  253. # arrayref of validator errors, whereas post_save catches them and hands back a
  254. # 400 with the field-level detail in the body -- which is the single most
  255. # useful thing to see when a fixture is wrong.
  256. sub _save_post {
  257. my ( $label, %post ) = @_;
  258. my $to = delete $post{to};
  259. my $res = eval { Trog::Routes::HTML::post_save( _admin( route => '/post/save', method => 'POST', to => $to, %post ) ) };
  260. if ( !$res || ref $res ne 'ARRAY' ) {
  261. fail("$label: saved");
  262. diag( $@ || 'post_save returned nothing' );
  263. return undef;
  264. }
  265. my ( $code, $headers, $body ) = @$res;
  266. my %h = @{ $headers || [] };
  267. # Both outcomes redirect now, so the status alone proves nothing -- the
  268. # outcome is in the query string post_save hands to the destination.
  269. if ( $code != 303 || ( $h{Location} // '' ) =~ m/savefailed=/ ) {
  270. fail("$label: saved");
  271. diag( "post_save returned $code, Location: " . ( $h{Location} // '(none)' ) );
  272. diag( join( '', @{ $body || [''] } ) ) if $body && @$body;
  273. return undef;
  274. }
  275. pass("$label: saved");
  276. _reindex(); # mandatory: see the comment on _reindex
  277. my $saved = _find_post( $post{title} );
  278. ok( $saved, "$label: readable back out of the datastore" ) or return undef;
  279. return $saved;
  280. }
  281. sub _find_post {
  282. my ($title) = @_;
  283. # filter() short-circuits on title; the admin acl skips the visibility filter.
  284. my @posts = _data()->get( title => $title, acls => ['admin'], limit => 0 );
  285. return $posts[0];
  286. }
  287. #--------------------------------------------------------------------------
  288. subtest 'the sandbox is what we are actually running against' => sub {
  289. is( Cwd::getcwd(), Cwd::abs_path($ROOT), 'cwd is the sandbox' );
  290. ok( -d 'data/files', 'datastore dir exists' );
  291. ok( -f 'config/default.cfg', 'config was seeded' );
  292. ok( !-f 'config/main.cfg', 'and there is no main.cfg, so we fall through to the default' );
  293. my $conf = Trog::Config::get();
  294. is( $conf->param('general.data_model'), 'FlatFile', 'config resolves inside the sandbox' );
  295. like( Trog::Themes::forms_dir(), qr/^www\/templates/, 'forms dir is relative, hence sandboxed' );
  296. ok( -d Cwd::abs_path( Trog::Themes::forms_dir() ), 'and it exists' );
  297. like( Cwd::abs_path( Trog::Themes::forms_dir() ), qr/^\Q$ROOT\E/, 'and it is under the sandbox, not the repo' );
  298. };
  299. subtest 'registering the first admin bootstraps the install' => sub {
  300. ok( !-f 'config/has_users', 'no users yet, so login() is in register mode' );
  301. my ( $code, $body, $err, $headers ) = _render(
  302. _anon(
  303. route => '/login',
  304. method => 'POST',
  305. username => $ADMIN_USER,
  306. display_name => $ADMIN_DISPLAY,
  307. contact_email => $ADMIN_EMAIL,
  308. password => $ADMIN_PASS,
  309. to => '/',
  310. ),
  311. \&Trog::Routes::HTML::login,
  312. );
  313. is( $code, 200, 'login() rendered' ) or diag($err);
  314. my %h = @{ $headers || [] };
  315. like( $h{'Set-Cookie'} // '', qr/^tcmslogin=[0-9a-f-]{36};/, 'a session cookie came back' );
  316. ok( -f 'config/has_users', 'registration is now closed' );
  317. is_deeply( Trog::Auth::acls4user($ADMIN_USER), ['admin'], 'the new user is an admin' );
  318. _reindex();
  319. my @seeded = _data()->get( acls => ['admin'], limit => 0 );
  320. is( scalar @seeded, 4, 'the four seed posts were written' )
  321. or diag( 'got: ' . join( ', ', map { "$_->{title} ($_->{form})" } @seeded ) );
  322. };
  323. subtest 'the post wizard invents a new post type' => sub {
  324. my %wizard = (
  325. name => 'spec_widget',
  326. title_placeholder => 'Widget Name',
  327. body_form => 'form_common.tx',
  328. wrapper => 1,
  329. inc_post_title => 1,
  330. inc_post_tags => 1,
  331. inc_title_input => 1,
  332. inc_visibility => 1,
  333. inc_tags => 1,
  334. inc_aliases => 1,
  335. param_name => ['flavor'],
  336. param_type => ['text'],
  337. param_label => ['Flavor'],
  338. param_placeholder => ['Strawberry'],
  339. param_required => [0],
  340. display => q{<div class="postData responsive-text" id="postData-<: $post.id :>">}
  341. . q{<span class="spec-flavor"><: $post.flavor :></span>}
  342. . q{<: render_it($post.data) | mark_raw :></div>},
  343. );
  344. my ( $code, $body, $err ) = _render(
  345. _admin( route => '/admin/wyzzerdd/save', method => 'POST', %wizard ),
  346. \&Trog::Routes::HTML::post_wizard_save,
  347. );
  348. is( $code, 200, 'wizard save rendered' ) or diag($err);
  349. ok( -f 'www/templates/html/components/forms/spec_widget.tx', 'the template was written' );
  350. ok( -f 'www/templates/html/components/forms/spec_widget.json', 'the schema sidecar was written' );
  351. like( $body, qr{<li>spec_widget\.tx</li>}, 'and the new type is listed back to us' );
  352. # This is the assertion that the sandbox is real: a symlinked template tree
  353. # would have put these in the developer's actual checkout.
  354. ok( !-e "$REPO/www/templates/html/components/forms/spec_widget.tx", 'nothing was written into the repo' );
  355. # The relation controls have to be present in every row and always submit,
  356. # or the parallel param_* arrays de-align server side.
  357. like( $body, qr/name="param_relation_form"/, 'the relation target select is in the row template' );
  358. like( $body, qr/name="param_relation_mode"/, 'so is the relation mode select' );
  359. like( $body, qr/<option value="relation">/, 'and relation is offered as a field type' );
  360. };
  361. #--------------------------------------------------------------------------
  362. # The matrix.
  363. #
  364. # Per type: build a topbar series whose child_form is that type, check it shows
  365. # up in the nav, add a child post, check the child renders on the series page.
  366. #
  367. # Everything is verified ANONYMOUSLY. can_edit is then false, so the editor
  368. # half of each form never renders and a title appears exactly once -- which is
  369. # what makes like($body, qr/$title/) mean anything. It also sidesteps the
  370. # /secure prefixing that both _post_helper and categories.tx apply when a user
  371. # is set.
  372. #--------------------------------------------------------------------------
  373. sub _make_series {
  374. my ( $label, $aclname, $child_form, $title, %opt ) = @_;
  375. # _get_series caps the bar at 10 and the seeds already use two, so only the
  376. # series whose topbar behaviour we actually care about get tagged.
  377. my @tags = $opt{no_topbar} ? ('series') : ( 'series', 'topbar' );
  378. my $series = _save_post(
  379. "$label series",
  380. form => 'series.tx',
  381. title => $title,
  382. aclname => $aclname, # required by series.json
  383. child_form => $child_form, # required by series.json
  384. local_href => "/$aclname",
  385. href => "/$aclname",
  386. data => "$title subhead",
  387. callback => 'Trog::Routes::HTML::series',
  388. visibility => 'public',
  389. tags => \@tags,
  390. tiled => 0,
  391. to => '/',
  392. ) or return undef;
  393. return $series if $opt{no_topbar};
  394. # The topbar comes from _get_series(), which index() renders through
  395. # categories.tx. Check it on / -- the series has no children yet, and
  396. # posts() 404s on an empty series.
  397. my ( $code, $body, $err ) = _render( _anon( route => '/' ) );
  398. is( $code, 200, "$label: / renders" ) or diag($err);
  399. my @titles = _topbar_titles($body);
  400. ok( ( grep { $_ eq $title } @titles ), "$label: series is in the topbar" )
  401. or diag( 'topbar was: ' . join( ', ', @titles ) );
  402. return $series;
  403. }
  404. sub _series_page {
  405. my ( $label, $aclname, $series_title, $expected_posts ) = @_;
  406. my ( $code, $body, $err ) = _render( _anon( route => "/$aclname" ), \&Trog::Routes::HTML::series );
  407. is( $code, 200, "$label: series page renders" ) or do { diag($err); return '' };
  408. like( $body, qr{<title>[^<]*\Q$series_title\E}, "$label: series page is the right series" );
  409. is( _post_count($body), $expected_posts, "$label: exactly $expected_posts post(s) listed" )
  410. or diag( _kontent($body) );
  411. return $body;
  412. }
  413. # Entities first: the invoice type resolves payee/payor against existing public
  414. # entities.tx posts, so those have to be in the datastore before we get there.
  415. our ( $PAYEE, $PAYOR );
  416. subtest 'entities' => sub {
  417. my $title = 'Spec Entities Series';
  418. _make_series( 'entities', 'specentities', 'entities.tx', $title ) or return;
  419. $PAYEE = _save_post(
  420. 'entities payee child',
  421. form => 'entities.tx',
  422. title => 'Spec Payee Entity',
  423. data => 'Acme Payments LLC, 1 Road, Metropolis',
  424. payment_method => 'ACH',
  425. payment_details => 'Routing 0000 Account 1111',
  426. visibility => 'public',
  427. tags => ['specentities'],
  428. to => '/specentities',
  429. ) or return;
  430. $PAYOR = _save_post(
  431. 'entities payor child',
  432. form => 'entities.tx',
  433. title => 'Spec Payor Entity',
  434. data => 'Wile E Coyote, PO Box 9',
  435. payment_method => 'Carrier Pigeon',
  436. payment_details => 'none',
  437. visibility => 'public',
  438. tags => ['specentities'],
  439. to => '/specentities',
  440. ) or return;
  441. my $body = _series_page( 'entities', 'specentities', $title, 2 ) or return;
  442. like( $body, qr{id="postData-\Q$PAYEE->{id}\E"}, 'payee body rendered' );
  443. like( $body, qr/Acme Payments LLC/, 'payee data rendered' );
  444. like( $body, qr/Wile E Coyote/, 'payor data rendered' );
  445. # entity_details.tx is included only in the editor half, so these are stored
  446. # but never displayed. Pinning that so a template change is noticed.
  447. unlike( $body, qr/Carrier Pigeon/, 'payment details are not shown to anonymous readers' );
  448. is( _find_post('Spec Payee Entity')->{payment_method}, 'ACH', 'but payment_method did survive the schema' );
  449. };
  450. subtest 'blog' => sub {
  451. my $title = 'Spec Blog Series';
  452. _make_series( 'blog', 'specblog', 'blog.tx', $title ) or return;
  453. my $child = _save_post(
  454. 'blog child',
  455. form => 'blog.tx',
  456. title => 'Spec Blog Child',
  457. data => 'Spec blog body text.',
  458. visibility => 'public',
  459. tags => ['specblog'],
  460. to => '/specblog',
  461. ) or return;
  462. my $body = _series_page( 'blog', 'specblog', $title, 1 ) or return;
  463. like( $body, qr/Spec Blog Child/, 'child title rendered' );
  464. like( $body, qr{href='/posts/\Q$child->{id}\E'}, 'child permalink rendered' );
  465. like( $body, qr{id="postData-\Q$child->{id}\E"}, 'child body block rendered' );
  466. like( $body, qr/Spec blog body text\./, 'child body text rendered' );
  467. unlike( $body, qr/Spec Payee Entity/, 'no bleed from the entities series' );
  468. };
  469. subtest 'microblog' => sub {
  470. my $title = 'Spec Microblog Series';
  471. _make_series( 'microblog', 'specmicroblog', 'microblog.tx', $title ) or return;
  472. my $child = _save_post(
  473. 'microblog child',
  474. form => 'microblog.tx',
  475. title => 'Spec Microblog Child',
  476. href => 'https://example.com/spec',
  477. data => 'Spec microblog body.',
  478. visibility => 'public',
  479. tags => ['specmicroblog'],
  480. to => '/specmicroblog',
  481. ) or return;
  482. my $body = _series_page( 'microblog', 'specmicroblog', $title, 1 ) or return;
  483. like( $body, qr{href='https://example\.com/spec' >Spec Microblog Child</a>}, 'title links out to href' );
  484. like( $body, qr{id="postData-\Q$child->{id}\E"}, 'body block rendered' );
  485. like( $body, qr/Spec microblog body\./, 'body text rendered' );
  486. };
  487. subtest 'file' => sub {
  488. my $title = 'Spec File Series';
  489. _make_series( 'file', 'specfile', 'file.tx', $title ) or return;
  490. # _handle_upload MOVES the file, so it has to be created fresh here.
  491. my $src = "$ROOT/upload-src/spec-upload.txt";
  492. open( my $fh, '>', $src ) or die $!;
  493. print {$fh} "spec upload contents\n";
  494. close $fh;
  495. my $child = _save_post(
  496. 'file child',
  497. form => 'file.tx',
  498. title => 'Spec File Child',
  499. data => 'Spec file body.',
  500. file => { tempname => $src, filename => 'spec-upload.txt' },
  501. visibility => 'public',
  502. tags => ['specfile'],
  503. to => '/specfile',
  504. ) or return;
  505. ok( !-e $src, 'the upload was moved out of its temp location, not copied' );
  506. ok( -f "www/assets/$child->{id}.spec-upload.txt", 'and it landed in www/assets' );
  507. my $body = _series_page( 'file', 'specfile', $title, 1 ) or return;
  508. like( $body, qr{href='/assets/\Q$child->{id}\E\.spec-upload\.txt'}, 'title links to the asset' );
  509. like( $body, qr{id="postData-\Q$child->{id}\E"}, 'body block carries a unique id, like every other form' );
  510. like( $body, qr/Spec file body\./, 'body text rendered' );
  511. # This form used to emit <div class="postData" id="postData" class="responsive-text">
  512. # -- a duplicated class attribute, and an id shared by every file post on
  513. # the page. Neither should come back.
  514. unlike( $body, qr{<div class="postData" id="postData"}, 'no duplicated class attribute' );
  515. # text/plain, so none of the media branches fire.
  516. unlike( $body, qr/<video/, 'no video block for a text file' );
  517. unlike( $body, qr/<audio/, 'no audio block either' );
  518. };
  519. subtest 'presentation' => sub {
  520. my $title = 'Spec Presentation Series';
  521. _make_series( 'presentation', 'specpresentation', 'presentation.tx', $title ) or return;
  522. my $child = _save_post(
  523. 'presentation child',
  524. form => 'presentation.tx',
  525. title => 'Spec Presentation Child',
  526. data => [ 'Slide one body.', 'Slide two body.' ],
  527. data_is_array => 1,
  528. visibility => 'public',
  529. tags => ['specpresentation'],
  530. to => '/specpresentation',
  531. ) or return;
  532. is_deeply( $child->{data}, [ 'Slide one body.', 'Slide two body.' ], 'the multi-page data round-tripped as an array' );
  533. my $body = _series_page( 'presentation', 'specpresentation', $title, 1 ) or return;
  534. # Slides only render under nochrome; the series page just links to the deck.
  535. like( $body, qr{<a href="/posts/\Q$child->{id}\E\?embed=1&nochrome=1">Click Here to view</a>}, 'deck link rendered' );
  536. unlike( $body, qr/Slide one body\./, 'slides themselves are not rendered inline' );
  537. };
  538. subtest 'invoice' => sub {
  539. my $title = 'Spec Invoice Series';
  540. _make_series( 'invoice', 'specinvoice', 'invoice.tx', $title ) or return;
  541. my $child = _save_post(
  542. 'invoice child',
  543. form => 'invoice.tx',
  544. title => 'Spec Invoice Child',
  545. data => [ "Widget assembly\nPrice: \$420", "Shipping\nPrice: \$80" ],
  546. data_is_array => 1,
  547. payee => $PAYEE->{id},
  548. payor => $PAYOR->{id},
  549. due_days => 30,
  550. visibility => 'public',
  551. tags => ['specinvoice'],
  552. to => '/specinvoice',
  553. ) or return;
  554. my $body = _series_page( 'invoice', 'specinvoice', $title, 1 ) or return;
  555. like( $body, qr/Invoice ID# \Q$child->{id}\E/, 'invoice header rendered' );
  556. # These two only resolve because the entities subtest ran first and left
  557. # public entities.tx posts behind for the enrich hook to find.
  558. like( $body, qr/Acme Payments LLC/, 'payee entity resolved' );
  559. like( $body, qr/Wile E Coyote/, 'payor entity resolved' );
  560. like( $body, qr/ACH/, 'payee payment method pulled through' );
  561. like( $body, qr/Widget assembly/, 'line items rendered' );
  562. like( $body, qr/Total: \$500/, 'total summed from the line item prices' );
  563. };
  564. subtest 'spec_widget (the wizard-built type)' => sub {
  565. my $title = 'Spec Widget Series';
  566. _make_series( 'spec_widget', 'specwidget', 'spec_widget.tx', $title ) or return;
  567. my $child = _save_post(
  568. 'spec_widget child',
  569. form => 'spec_widget.tx',
  570. title => 'Spec Widget Child',
  571. data => 'Spec widget body.',
  572. flavor => 'Strawberry',
  573. bogus_field => 'nope',
  574. visibility => 'public',
  575. tags => ['specwidget'],
  576. to => '/specwidget',
  577. ) or return;
  578. is( $child->{flavor}, 'Strawberry', 'the custom field survived validation' );
  579. ok( !exists $child->{bogus_field}, 'an undeclared field was still stripped' );
  580. my $body = _series_page( 'spec_widget', 'specwidget', $title, 1 ) or return;
  581. # The payoff: this can only render if the wizard wrote spec_widget.json,
  582. # schema_for merged it over the base post schema, and validate() therefore
  583. # kept 'flavor' instead of deleting it as an unknown key.
  584. like( $body, qr{<span class="spec-flavor">Strawberry</span>}, 'the custom field rendered on the page' );
  585. like( $body, qr/Spec widget body\./, 'and the body came through the generated template' );
  586. };
  587. subtest 'a wizard-built type can depend on another type' => sub {
  588. # The type we will point at. The relation is what is under test, so keep
  589. # the target itself boring.
  590. my ( $code, $body, $err ) = _render(
  591. _admin(
  592. route => '/admin/wyzzerdd/save',
  593. method => 'POST',
  594. name => 'spec_target',
  595. body_form => 'form_common.tx',
  596. wrapper => 1,
  597. inc_post_title => 1,
  598. inc_title_input => 1,
  599. inc_visibility => 1,
  600. inc_tags => 1,
  601. display => q{<div><: render_it($post.data) | mark_raw :></div>},
  602. ),
  603. \&Trog::Routes::HTML::post_wizard_save,
  604. );
  605. is( $code, 200, 'target type created' ) or diag($err);
  606. # ...and the type that depends on it: one picked by id, one pulling in the
  607. # whole set.
  608. ( $code, $body, $err ) = _render(
  609. _admin(
  610. route => '/admin/wyzzerdd/save',
  611. method => 'POST',
  612. name => 'spec_relator',
  613. body_form => 'form_common.tx',
  614. wrapper => 1,
  615. inc_post_title => 1,
  616. inc_title_input => 1,
  617. inc_visibility => 1,
  618. inc_tags => 1,
  619. param_name => [ 'chosen', 'everything' ],
  620. param_type => [ 'relation', 'relation' ],
  621. param_label => [ 'Chosen One', 'All Of Them' ],
  622. param_placeholder => [ '', '' ],
  623. param_required => [ 0, 0 ],
  624. param_relation_form => [ 'spec_target.tx', 'spec_target.tx' ],
  625. param_relation_mode => [ 'one', 'all' ],
  626. display => q{<div class="rel"><span class="chosen"><: $post.chosen_post.title :></span>}
  627. . q{<: for $post.everything -> $t { :><span class="each"><: $t.title :></span><: } :></div>},
  628. ),
  629. \&Trog::Routes::HTML::post_wizard_save,
  630. );
  631. is( $code, 200, 'relating type created' ) or diag($err);
  632. my $sidecar = JSON::MaybeXS::decode_json(
  633. Path::Tiny->new('www/templates/html/components/forms/spec_relator.json')->slurp_utf8 );
  634. # 'one' is a field the post stores; 'all' is not a field at all.
  635. is( $sidecar->{properties}{chosen}{type}, 'relation', 'the picked relation is a stored property' );
  636. is( $sidecar->{properties}{chosen}{'x-tcms-relation-form'}, 'spec_target.tx', 'naming its target type' );
  637. ok( !exists $sidecar->{properties}{everything}, "the 'all' relation stores nothing" );
  638. is_deeply(
  639. $sidecar->{'x-tcms-relations'},
  640. {
  641. chosen_post => { form => 'spec_target.tx', from => 'chosen' },
  642. everything => { form => 'spec_target.tx' },
  643. },
  644. 'and both are declared for resolution at render'
  645. );
  646. # The relation pseudo-type has to become a real one before validation, or
  647. # every relation field would be stripped as an unknown type.
  648. is( Trog::DataModule::schema_for('spec_relator.tx')->{properties}{chosen}{type},
  649. 'string', "'relation' expands to a real schema type" );
  650. _reindex();
  651. # Now exercise it end to end.
  652. _make_series( 'spec_target', 'spectarget', 'spec_target.tx', 'Spec Target Series', no_topbar => 1 ) or return;
  653. my $target = _save_post(
  654. 'spec_target child',
  655. form => 'spec_target.tx',
  656. title => 'Spec Target Post',
  657. data => 'Spec target body.',
  658. visibility => 'public',
  659. tags => ['spectarget'],
  660. to => '/spectarget',
  661. ) or return;
  662. _make_series( 'spec_relator', 'specrelator', 'spec_relator.tx', 'Spec Relator Series', no_topbar => 1 ) or return;
  663. my $relator = _save_post(
  664. 'spec_relator child',
  665. form => 'spec_relator.tx',
  666. title => 'Spec Relator Post',
  667. data => 'Spec relator body.',
  668. chosen => $target->{id},
  669. visibility => 'public',
  670. tags => ['specrelator'],
  671. to => '/specrelator',
  672. ) or return;
  673. is( $relator->{chosen}, $target->{id}, 'the referenced id survived validation' );
  674. my $page = _series_page( 'spec_relator', 'specrelator', 'Spec Relator Series', 1 ) or return;
  675. # Both halves of the relation resolved: the one we picked, and the set.
  676. like( $page, qr{<span class="chosen">Spec Target Post</span>}, 'the picked post resolved into the page' );
  677. like( $page, qr{<span class="each">Spec Target Post</span>}, 'and so did the whole set' );
  678. };
  679. subtest '/api/posts_of_form feeds the relation picker' => sub {
  680. my $target = _find_post('Spec Target Post');
  681. ok( $target, 'the target post is there to be listed' ) or return;
  682. my $res = Trog::Routes::JSON::posts_of_form( _admin( route => '/api/posts_of_form', form => 'spec_target.tx' ) );
  683. is( ref $res, 'ARRAY', 'a PSGI response came back' ) or return;
  684. my ( $code, undef, $body ) = @$res;
  685. is( $code, 200, 'and it is a 200' );
  686. my $payload = JSON::MaybeXS::decode_json( join( '', @$body ) );
  687. is_deeply(
  688. $payload->{posts},
  689. [ { id => $target->{id}, title => 'Spec Target Post' } ],
  690. 'listing exactly the posts of that type, id and title only'
  691. );
  692. # An unknown type is an empty list, not an error -- a type with no posts
  693. # yet is the normal state of affairs right after you create it.
  694. $res = Trog::Routes::JSON::posts_of_form( _admin( route => '/api/posts_of_form', form => 'nosuchtype.tx' ) );
  695. $payload = JSON::MaybeXS::decode_json( join( '', @{ $res->[2] } ) );
  696. is_deeply( $payload->{posts}, [], 'an unknown type lists nothing rather than failing' );
  697. # The route's own declaration is what keeps a malformed form out; check it
  698. # matches what series.json demands of child_form.
  699. my $validator = $Trog::Routes::JSON::routes{'/api/posts_of_form'}{parameters}{form};
  700. ok( $validator->('blog.tx'), 'the parameter validator accepts a form name' );
  701. ok( !$validator->('../../etc/passwd'), 'and rejects a path' );
  702. ok( $Trog::Routes::JSON::routes{'/api/posts_of_form'}{auth}, 'the route requires a login' );
  703. };
  704. subtest 'saves report back through the jsalert banner' => sub {
  705. # A good save redirects to where you came from, carrying the outcome.
  706. my $res = Trog::Routes::HTML::post_save(
  707. _admin(
  708. route => '/post/save',
  709. method => 'POST',
  710. to => '/specblog',
  711. form => 'blog.tx',
  712. title => 'Spec Feedback Child',
  713. data => 'Spec feedback body.',
  714. visibility => 'public',
  715. tags => ['specblog'],
  716. )
  717. );
  718. my ( $code, $headers ) = @$res;
  719. my %h = @{ $headers || [] };
  720. is( $code, 303, 'a good save redirects' );
  721. like( $h{Location}, qr{^/secure/specblog\?saved=}, 'to where we came from, flagged as saved' );
  722. unlike( $h{Location}, qr/\n/, 'and the message is one line, since it lands in a JS string' );
  723. _reindex();
  724. # Follow the redirect the way a browser would.
  725. my ($qs) = $h{Location} =~ m/\?(.*)$/;
  726. my %params = map { my ( $k, $v ) = split( /=/, $_, 2 ); ( $k => URI::Escape::uri_unescape($v) ) } split( /&/, $qs );
  727. my ( $rcode, $body, $err ) = _render(
  728. _admin( route => '/specblog', has_query => 1, %params ),
  729. \&Trog::Routes::HTML::series,
  730. );
  731. is( $rcode, 200, 'the destination renders' ) or diag($err);
  732. like( $body, qr/var loginFailure = 0;/, 'the banner is in success mode' );
  733. like( $body, qr/Saved post &#39;Spec Feedback Child&#39;\./, 'and says what was saved' );
  734. # Nothing to navigate on to, so the banner must not bounce us anywhere.
  735. unlike( $body, qr/window\.location=/, 'and does not redirect onwards' );
  736. # A rejected save comes back the same way, in red.
  737. $res = Trog::Routes::HTML::post_save(
  738. _admin(
  739. route => '/post/save',
  740. method => 'POST',
  741. to => '/specblog',
  742. form => 'blog.tx',
  743. title => 'Spec Rejected Child',
  744. visibility => 'not-a-visibility',
  745. tags => ['specblog'],
  746. )
  747. );
  748. ( $code, $headers ) = @$res;
  749. %h = @{ $headers || [] };
  750. is( $code, 303, 'a rejected save redirects too, rather than dead-ending on a 400' );
  751. like( $h{Location}, qr{^/secure/specblog\?savefailed=}, 'flagged as failed' );
  752. like( URI::Escape::uri_unescape( $h{Location} ), qr/Not in enum list/, 'carrying the validator error' );
  753. ok( !_find_post('Spec Rejected Child'), 'and the bad post was not written' );
  754. ($qs) = $h{Location} =~ m/\?(.*)$/;
  755. %params = map { my ( $k, $v ) = split( /=/, $_, 2 ); ( $k => URI::Escape::uri_unescape($v) ) } split( /&/, $qs );
  756. ( $rcode, $body, $err ) = _render(
  757. _admin( route => '/specblog', has_query => 1, %params ),
  758. \&Trog::Routes::HTML::series,
  759. );
  760. is( $rcode, 200, 'the destination still renders' ) or diag($err);
  761. like( $body, qr/var loginFailure = 1;/, 'the banner is in failure mode' );
  762. like( $body, qr/Not in enum list/, 'and shows why' );
  763. };
  764. subtest 'the topbar did not silently overflow' => sub {
  765. my ( $code, $body, $err ) = _render( _anon( route => '/' ) );
  766. is( $code, 200, '/ renders' ) or diag($err);
  767. my @titles = _topbar_titles($body);
  768. # 2 seeded series (Series, About) + the 7 we built. _get_series() caps at
  769. # 10 (HTML.pm), so an eighth post type would start silently dropping one.
  770. is( scalar @titles, 9, 'every series we made is in the topbar' )
  771. or diag( 'topbar was: ' . join( ', ', @titles ) );
  772. cmp_ok( scalar @titles, '<=', 10, 'and we are not at the _get_series limit' );
  773. };
  774. subtest 'the tpsgi side effects stayed inert' => sub {
  775. cmp_ok( $TPSGI->{restarts}, '>', 0, 'post_save did try to signal a restart' );
  776. cmp_ok( $TPSGI->{callbacks}, '>', 0, 'and did queue post-close callbacks' );
  777. # We never run the queued callbacks, which is what keeps save_render and
  778. # invalidate_renders from ever firing.
  779. is_deeply( $TPSGI->{renders}, {}, 'no static renders were written' );
  780. is_deeply( $TPSGI->{invalidated}, [], 'and nothing was invalidated' );
  781. my @statics = glob('www/statics/*');
  782. is_deeply( \@statics, [], 'www/statics is empty' );
  783. };
  784. subtest 'the real repo was not touched' => sub {
  785. my %after = map { _snapshot("$REPO/$_") } qw{config data www/templates www/assets logs totp};
  786. my @changed = grep { ( $REPO_BEFORE{$_} // '' ) ne ( $after{$_} // '' ) } keys %after;
  787. my @removed = grep { !exists $after{$_} } keys %REPO_BEFORE;
  788. is_deeply( [ sort @changed ], [], 'no repo file was added or modified' );
  789. is_deeply( [ sort @removed ], [], 'and none were removed' );
  790. ok( !-e "$REPO/www/templates/html/components/forms/spec_widget.tx", 'the wizard type is not in the repo' );
  791. };
  792. done_testing();