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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  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. our ( $REPO, $ROOT, $OLDCWD );
  25. our %REPO_BEFORE;
  26. # name => (size, mtime) for every file under the repo dirs this test could
  27. # plausibly disturb. Cheap enough, and it is the only real proof of isolation.
  28. sub _snapshot {
  29. my ($dir) = @_;
  30. my %seen;
  31. File::Find::find(
  32. {
  33. no_chdir => 1,
  34. wanted => sub {
  35. return unless -f $File::Find::name;
  36. my @st = stat(_);
  37. $seen{$File::Find::name} = "$st[7]:$st[9]";
  38. },
  39. },
  40. $dir
  41. );
  42. return %seen;
  43. }
  44. sub _copy_tree {
  45. my ( $from, $to ) = @_;
  46. File::Path::make_path($to);
  47. File::Find::find(
  48. {
  49. no_chdir => 1,
  50. wanted => sub {
  51. my $rel = substr( $File::Find::name, length($from) );
  52. return unless length $rel;
  53. my $dst = "$to$rel";
  54. if ( -d $File::Find::name ) { File::Path::make_path($dst) }
  55. elsif ( -f $File::Find::name ) { File::Copy::copy( $File::Find::name, $dst ) or die "copy $File::Find::name: $!" }
  56. },
  57. },
  58. $from
  59. );
  60. return;
  61. }
  62. # Everything the sandbox needs, in one BEGIN. The Trog:: modules are require()d
  63. # at runtime below, which is unconditionally after every BEGIN -- so no later
  64. # edit can accidentally load them before the chdir. That matters: TCMS.pm runs
  65. # build_routes() at file scope and FlatFile.pm reads the tag index at file
  66. # scope, both against whatever cwd happens to be current.
  67. BEGIN {
  68. $REPO = Cwd::abs_path("$FindBin::Bin/..");
  69. $OLDCWD = Cwd::getcwd();
  70. %REPO_BEFORE = map { _snapshot("$REPO/$_") } qw{config data www/templates www/assets logs totp};
  71. $ROOT = File::Temp::tempdir( 'tcms-lifecycle-XXXXXX', TMPDIR => 1, CLEANUP => 0 );
  72. # Installer.mk's tree, plus upload-src for the file.tx fixture.
  73. File::Path::make_path(
  74. map { "$ROOT/$_" } qw{
  75. config schema data/files logs totp upload-src
  76. www/assets/private www/statics www/themes www/scripts
  77. }
  78. );
  79. # A real fresh install: get() looks for config/main.cfg, doesn't find one,
  80. # and falls through to the shipped default.
  81. File::Copy::copy( "$REPO/config/default.cfg", "$ROOT/config/default.cfg" ) or die $!;
  82. # Hardcoded paths in Auth.pm, TagIndex.pm and Log.pm -- not negotiable.
  83. File::Copy::copy( "$REPO/schema/$_", "$ROOT/schema/$_" ) or die $! for qw{auth.schema flatfile.schema log.schema};
  84. # COPY, don't symlink: post_wizard_save() writes into Trog::Themes::forms_dir(),
  85. # and a symlink would land the generated post type in the real repo.
  86. _copy_tree( "$REPO/www/templates", "$ROOT/www/templates" );
  87. # posts() renders the emoji picker unconditionally, and EmojiPicker dies
  88. # outright if this file is missing. Only category and emoji are read.
  89. open( my $fh, '>', "$ROOT/www/scripts/list.min.json" ) or die $!;
  90. print {$fh} '{"emojis":[{"category":"Smileys","emoji":"X"}]}';
  91. close $fh;
  92. # Text::Xslate computes its default cache dir from $HOME once, at load time.
  93. # Without this the sandbox writes compiled templates into the real ~/.xslate_cache.
  94. $ENV{HOME} = $ROOT;
  95. chdir($ROOT) or die "could not chdir to sandbox $ROOT: $!";
  96. }
  97. END {
  98. # Never rmtree the directory you are standing in.
  99. chdir($OLDCWD) if $OLDCWD;
  100. if ( $ENV{TCMS_TEST_KEEP} ) {
  101. diag("TCMS_TEST_KEEP set, sandbox left at $ROOT");
  102. }
  103. elsif ( $ROOT && -d $ROOT ) {
  104. # SQLite handles are file-lexical in Trog::SQLite and unreachable from
  105. # here; DBI disconnects at global destruction, after these are gone.
  106. eval { File::Path::remove_tree($ROOT) };
  107. }
  108. }
  109. diag("sandbox: $ROOT");
  110. require Trog::Log;
  111. Trog::Log::log_init( 'logs/tcms.log', 'info' ); # sets $LOGDIR, hence logs/log.db
  112. require Trog::Config;
  113. require Trog::Themes;
  114. require Trog::Data;
  115. require Trog::Auth;
  116. require Trog::SQLite::TagIndex;
  117. require Trog::Routes::HTML;
  118. #--------------------------------------------------------------------------
  119. # A stand-in for the tPSGI object the router injects as $query->{tpsgi}.
  120. #--------------------------------------------------------------------------
  121. {
  122. package Test::TPSGI;
  123. sub new {
  124. my ( $class, %args ) = @_;
  125. return bless {
  126. callbacks => 0,
  127. renders => {},
  128. invalidated => [],
  129. restarts => 0,
  130. tpsgi_dir => Cwd::getcwd(),
  131. log_dir => 'logs',
  132. gid => $),
  133. verbose => 0,
  134. %args,
  135. }, $class;
  136. }
  137. sub INFO {1}
  138. sub DEBUG {1}
  139. sub WARN {1}
  140. sub ERROR {1}
  141. sub CRIT {1}
  142. sub ALERT {1}
  143. sub EMERG {1}
  144. sub FATAL {1}
  145. sub see_also { return [ 303, [ 'Location' => $_[1], 'Content-Length' => 0 ], [''] ] }
  146. sub redirect { return [ 302, [ 'Location' => $_[1], 'Content-Length' => 0 ], [''] ] }
  147. sub redirect_permanent { return [ 301, [ 'Location' => $_[1], 'Content-Length' => 0 ], [''] ] }
  148. sub _reply { return [ $_[1], [ 'Content-type' => 'text/html' ], [ defined $_[2] ? $_[2] : '' ] ] }
  149. sub ok { return $_[0]->_reply( 200, $_[2] ) }
  150. sub notfound { return $_[0]->_reply( 404, $_[2] // 'Not Found' ) }
  151. sub forbidden { return $_[0]->_reply( 403, $_[2] // 'Forbidden' ) }
  152. sub badrequest { return $_[0]->_reply( 400, $_[2] // 'Bad Request' ) }
  153. sub error { return $_[0]->_reply( 500, $_[2] // 'Error' ) }
  154. sub serve { return [ 200, [], [''] ] }
  155. # These two must be inert.
  156. #
  157. # add_post_close_callback is the ONLY path by which Trog::Renderer and
  158. # post_save reach save_render()/invalidate_renders(). Dropping the callback
  159. # on the floor is what guarantees this test never writes into www/statics,
  160. # whatever the renderer's own skip-save logic decides.
  161. sub add_post_close_callback { $_[0]{callbacks}++; return 1 }
  162. # The real one is `kill 'HUP', getppid`. Under prove, that is prove.
  163. sub signal_restart_parent { $_[0]{restarts}++; return 1 }
  164. sub invalidate_renders { push @{ $_[0]{invalidated} }, $_[1]; return 1 }
  165. sub invalidate_render { push @{ $_[0]{invalidated} }, [ @_[ 1 .. $#_ ] ]; return 1 }
  166. sub save_render { $_[0]{renders}{"$_[1]:$_[2]"} = $_[3]; return 1 }
  167. }
  168. our $TPSGI = Test::TPSGI->new();
  169. our $ADMIN_USER = 'specadmin';
  170. our $ADMIN_DISPLAY = 'Spec Admin';
  171. our $ADMIN_EMAIL = 'specadmin@example.com';
  172. our $ADMIN_PASS = 'spec-password';
  173. #--------------------------------------------------------------------------
  174. # Harness
  175. #--------------------------------------------------------------------------
  176. # Always build a fresh query: posts() pushes onto user_acls, and series()
  177. # rewrites route/aclname/tag/in_series/primary_post in place.
  178. sub _query {
  179. my (%over) = @_;
  180. my %q = (
  181. route => '/',
  182. method => 'GET',
  183. scheme => 'http', # Renderer::Base compares this with no undef guard
  184. domain => 'tcms.test',
  185. start => [ Time::HiRes::gettimeofday() ], # tv_interval() dies on anything else
  186. deflate => 0,
  187. streaming => 0,
  188. ranges => [],
  189. last_fetched => undef,
  190. has_query => 0,
  191. social_meta => 0,
  192. acls => [],
  193. user_acls => [],
  194. body => undef,
  195. tpsgi => $TPSGI,
  196. %over,
  197. );
  198. $q{fullpath} //= $q{route};
  199. return \%q;
  200. }
  201. sub _anon { return _query( user => undef, user_acls => [], @_ ) }
  202. sub _admin { return _query( user => $ADMIN_USER, user_acls => ['admin'], @_ ) }
  203. # Returns ($code, $body, $error). Never dies, so one bad post type cannot take
  204. # the rest of the file with it -- which matters because a failed render inside
  205. # index() dies rather than returning a 500 (there is no www/templates/html/500.tx).
  206. sub _render {
  207. my ( $query, $how ) = @_;
  208. $how ||= \&Trog::Routes::HTML::index;
  209. my $res = eval { $how->($query) };
  210. return ( 0, '', "died: $@" ) if !$res;
  211. return ( 0, '', 'returned a ' . ( ref($res) || 'plain scalar' ) ) if ref $res ne 'ARRAY';
  212. my ( $code, $headers, $body ) = @$res;
  213. $body = ref $body eq 'ARRAY' ? join( '', @$body ) : ( $body // '' );
  214. return ( $code, Encode::decode_utf8($body), '', $headers );
  215. }
  216. # FlatFile snapshots the tag list at load time and then filters each query's
  217. # tags against it IN PLACE -- so a tag created later isn't merely unindexed, it
  218. # is deleted from the query, and the filter silently degrades to "every public
  219. # post". Production gets away with it because a save HUPs the parent and the
  220. # worker re-execs. We have to do it by hand.
  221. sub _reindex {
  222. no warnings 'once';
  223. @Trog::Data::FlatFile::tags = Trog::SQLite::TagIndex::tags();
  224. %Trog::Data::FlatFile::posts_by_tag = ();
  225. return;
  226. }
  227. sub _data { return Trog::Data->new( Trog::Config::get() ) }
  228. # categories.tx renders into <span id="categories">. Scope to it -- index.tx
  229. # emits other class="topbar" anchors outside that span.
  230. sub _topbar_titles {
  231. my ($body) = @_;
  232. my ($span) = $body =~ m{<span id="categories">(.*?)</span>}s;
  233. return () unless defined $span;
  234. return $span =~ m{class="topbar">([^<]*)</a>}g;
  235. }
  236. # post_title.tx emits exactly one of these per displayed post.
  237. sub _post_count {
  238. my $n = () = $_[0] =~ m{<h3 class='blogtitles'>}g;
  239. return $n;
  240. }
  241. # The rendered page is ~40KB and mostly JavaScript. Show the content well.
  242. sub _kontent {
  243. my ($body) = @_;
  244. my ($k) = $body =~ m{<div id="kontent" class="kontained">(.*?)<div id="rightbar"}s;
  245. $k //= $body;
  246. $k =~ s/<script\b.*?<\/script>//gs;
  247. return length($k) > 2500 ? substr( $k, 0, 2500 ) . "\n...[truncated]" : $k;
  248. }
  249. # Save through post_save() rather than $data->add(): add() dies with an
  250. # arrayref of validator errors, whereas post_save catches them and hands back a
  251. # 400 with the field-level detail in the body -- which is the single most
  252. # useful thing to see when a fixture is wrong.
  253. sub _save_post {
  254. my ( $label, %post ) = @_;
  255. my $to = delete $post{to};
  256. my $res = eval { Trog::Routes::HTML::post_save( _admin( route => '/post/save', method => 'POST', to => $to, %post ) ) };
  257. if ( !$res || ref $res ne 'ARRAY' ) {
  258. fail("$label: saved");
  259. diag( $@ || 'post_save returned nothing' );
  260. return undef;
  261. }
  262. my ( $code, undef, $body ) = @$res;
  263. if ( $code != 303 ) {
  264. fail("$label: saved");
  265. diag( "post_save returned $code:\n" . join( '', @{ $body || [''] } ) );
  266. return undef;
  267. }
  268. pass("$label: saved");
  269. _reindex(); # mandatory: see the comment on _reindex
  270. my $saved = _find_post( $post{title} );
  271. ok( $saved, "$label: readable back out of the datastore" ) or return undef;
  272. return $saved;
  273. }
  274. sub _find_post {
  275. my ($title) = @_;
  276. # filter() short-circuits on title; the admin acl skips the visibility filter.
  277. my @posts = _data()->get( title => $title, acls => ['admin'], limit => 0 );
  278. return $posts[0];
  279. }
  280. #--------------------------------------------------------------------------
  281. subtest 'the sandbox is what we are actually running against' => sub {
  282. is( Cwd::getcwd(), Cwd::abs_path($ROOT), 'cwd is the sandbox' );
  283. ok( -d 'data/files', 'datastore dir exists' );
  284. ok( -f 'config/default.cfg', 'config was seeded' );
  285. ok( !-f 'config/main.cfg', 'and there is no main.cfg, so we fall through to the default' );
  286. my $conf = Trog::Config::get();
  287. is( $conf->param('general.data_model'), 'FlatFile', 'config resolves inside the sandbox' );
  288. like( Trog::Themes::forms_dir(), qr/^www\/templates/, 'forms dir is relative, hence sandboxed' );
  289. ok( -d Cwd::abs_path( Trog::Themes::forms_dir() ), 'and it exists' );
  290. like( Cwd::abs_path( Trog::Themes::forms_dir() ), qr/^\Q$ROOT\E/, 'and it is under the sandbox, not the repo' );
  291. };
  292. subtest 'registering the first admin bootstraps the install' => sub {
  293. ok( !-f 'config/has_users', 'no users yet, so login() is in register mode' );
  294. my ( $code, $body, $err, $headers ) = _render(
  295. _anon(
  296. route => '/login',
  297. method => 'POST',
  298. username => $ADMIN_USER,
  299. display_name => $ADMIN_DISPLAY,
  300. contact_email => $ADMIN_EMAIL,
  301. password => $ADMIN_PASS,
  302. to => '/',
  303. ),
  304. \&Trog::Routes::HTML::login,
  305. );
  306. is( $code, 200, 'login() rendered' ) or diag($err);
  307. my %h = @{ $headers || [] };
  308. like( $h{'Set-Cookie'} // '', qr/^tcmslogin=[0-9a-f-]{36};/, 'a session cookie came back' );
  309. ok( -f 'config/has_users', 'registration is now closed' );
  310. is_deeply( Trog::Auth::acls4user($ADMIN_USER), ['admin'], 'the new user is an admin' );
  311. _reindex();
  312. my @seeded = _data()->get( acls => ['admin'], limit => 0 );
  313. is( scalar @seeded, 4, 'the four seed posts were written' )
  314. or diag( 'got: ' . join( ', ', map { "$_->{title} ($_->{form})" } @seeded ) );
  315. };
  316. subtest 'the post wizard invents a new post type' => sub {
  317. my %wizard = (
  318. name => 'spec_widget',
  319. title_placeholder => 'Widget Name',
  320. body_form => 'form_common.tx',
  321. wrapper => 1,
  322. inc_post_title => 1,
  323. inc_post_tags => 1,
  324. inc_title_input => 1,
  325. inc_visibility => 1,
  326. inc_tags => 1,
  327. inc_aliases => 1,
  328. param_name => ['flavor'],
  329. param_type => ['text'],
  330. param_label => ['Flavor'],
  331. param_placeholder => ['Strawberry'],
  332. param_required => [0],
  333. display => q{<div class="postData responsive-text" id="postData-<: $post.id :>">}
  334. . q{<span class="spec-flavor"><: $post.flavor :></span>}
  335. . q{<: render_it($post.data) | mark_raw :></div>},
  336. );
  337. my ( $code, $body, $err ) = _render(
  338. _admin( route => '/admin/wyzzerdd/save', method => 'POST', %wizard ),
  339. \&Trog::Routes::HTML::post_wizard_save,
  340. );
  341. is( $code, 200, 'wizard save rendered' ) or diag($err);
  342. ok( -f 'www/templates/html/components/forms/spec_widget.tx', 'the template was written' );
  343. ok( -f 'www/templates/html/components/forms/spec_widget.json', 'the schema sidecar was written' );
  344. like( $body, qr{<li>spec_widget\.tx</li>}, 'and the new type is listed back to us' );
  345. # This is the assertion that the sandbox is real: a symlinked template tree
  346. # would have put these in the developer's actual checkout.
  347. ok( !-e "$REPO/www/templates/html/components/forms/spec_widget.tx", 'nothing was written into the repo' );
  348. };
  349. #--------------------------------------------------------------------------
  350. # The matrix.
  351. #
  352. # Per type: build a topbar series whose child_form is that type, check it shows
  353. # up in the nav, add a child post, check the child renders on the series page.
  354. #
  355. # Everything is verified ANONYMOUSLY. can_edit is then false, so the editor
  356. # half of each form never renders and a title appears exactly once -- which is
  357. # what makes like($body, qr/$title/) mean anything. It also sidesteps the
  358. # /secure prefixing that both _post_helper and categories.tx apply when a user
  359. # is set.
  360. #--------------------------------------------------------------------------
  361. sub _make_series {
  362. my ( $label, $aclname, $child_form, $title ) = @_;
  363. my $series = _save_post(
  364. "$label series",
  365. form => 'series.tx',
  366. title => $title,
  367. aclname => $aclname, # required by series.json
  368. child_form => $child_form, # required by series.json
  369. local_href => "/$aclname",
  370. href => "/$aclname",
  371. data => "$title subhead",
  372. callback => 'Trog::Routes::HTML::series',
  373. visibility => 'public',
  374. tags => [ 'series', 'topbar' ],
  375. tiled => 0,
  376. to => '/',
  377. ) or return undef;
  378. # The topbar comes from _get_series(), which index() renders through
  379. # categories.tx. Check it on / -- the series has no children yet, and
  380. # posts() 404s on an empty series.
  381. my ( $code, $body, $err ) = _render( _anon( route => '/' ) );
  382. is( $code, 200, "$label: / renders" ) or diag($err);
  383. my @titles = _topbar_titles($body);
  384. ok( ( grep { $_ eq $title } @titles ), "$label: series is in the topbar" )
  385. or diag( 'topbar was: ' . join( ', ', @titles ) );
  386. return $series;
  387. }
  388. sub _series_page {
  389. my ( $label, $aclname, $series_title, $expected_posts ) = @_;
  390. my ( $code, $body, $err ) = _render( _anon( route => "/$aclname" ), \&Trog::Routes::HTML::series );
  391. is( $code, 200, "$label: series page renders" ) or do { diag($err); return '' };
  392. like( $body, qr{<title>[^<]*\Q$series_title\E}, "$label: series page is the right series" );
  393. is( _post_count($body), $expected_posts, "$label: exactly $expected_posts post(s) listed" )
  394. or diag( _kontent($body) );
  395. return $body;
  396. }
  397. # Entities first: the invoice type resolves payee/payor against existing public
  398. # entities.tx posts, so those have to be in the datastore before we get there.
  399. our ( $PAYEE, $PAYOR );
  400. subtest 'entities' => sub {
  401. my $title = 'Spec Entities Series';
  402. _make_series( 'entities', 'specentities', 'entities.tx', $title ) or return;
  403. $PAYEE = _save_post(
  404. 'entities payee child',
  405. form => 'entities.tx',
  406. title => 'Spec Payee Entity',
  407. data => 'Acme Payments LLC, 1 Road, Metropolis',
  408. payment_method => 'ACH',
  409. payment_details => 'Routing 0000 Account 1111',
  410. visibility => 'public',
  411. tags => ['specentities'],
  412. to => '/specentities',
  413. ) or return;
  414. $PAYOR = _save_post(
  415. 'entities payor child',
  416. form => 'entities.tx',
  417. title => 'Spec Payor Entity',
  418. data => 'Wile E Coyote, PO Box 9',
  419. payment_method => 'Carrier Pigeon',
  420. payment_details => 'none',
  421. visibility => 'public',
  422. tags => ['specentities'],
  423. to => '/specentities',
  424. ) or return;
  425. my $body = _series_page( 'entities', 'specentities', $title, 2 ) or return;
  426. like( $body, qr{id="postData-\Q$PAYEE->{id}\E"}, 'payee body rendered' );
  427. like( $body, qr/Acme Payments LLC/, 'payee data rendered' );
  428. like( $body, qr/Wile E Coyote/, 'payor data rendered' );
  429. # entity_details.tx is included only in the editor half, so these are stored
  430. # but never displayed. Pinning that so a template change is noticed.
  431. unlike( $body, qr/Carrier Pigeon/, 'payment details are not shown to anonymous readers' );
  432. is( _find_post('Spec Payee Entity')->{payment_method}, 'ACH', 'but payment_method did survive the schema' );
  433. };
  434. subtest 'blog' => sub {
  435. my $title = 'Spec Blog Series';
  436. _make_series( 'blog', 'specblog', 'blog.tx', $title ) or return;
  437. my $child = _save_post(
  438. 'blog child',
  439. form => 'blog.tx',
  440. title => 'Spec Blog Child',
  441. data => 'Spec blog body text.',
  442. visibility => 'public',
  443. tags => ['specblog'],
  444. to => '/specblog',
  445. ) or return;
  446. my $body = _series_page( 'blog', 'specblog', $title, 1 ) or return;
  447. like( $body, qr/Spec Blog Child/, 'child title rendered' );
  448. like( $body, qr{href='/posts/\Q$child->{id}\E'}, 'child permalink rendered' );
  449. like( $body, qr{id="postData-\Q$child->{id}\E"}, 'child body block rendered' );
  450. like( $body, qr/Spec blog body text\./, 'child body text rendered' );
  451. unlike( $body, qr/Spec Payee Entity/, 'no bleed from the entities series' );
  452. };
  453. subtest 'microblog' => sub {
  454. my $title = 'Spec Microblog Series';
  455. _make_series( 'microblog', 'specmicroblog', 'microblog.tx', $title ) or return;
  456. my $child = _save_post(
  457. 'microblog child',
  458. form => 'microblog.tx',
  459. title => 'Spec Microblog Child',
  460. href => 'https://example.com/spec',
  461. data => 'Spec microblog body.',
  462. visibility => 'public',
  463. tags => ['specmicroblog'],
  464. to => '/specmicroblog',
  465. ) or return;
  466. my $body = _series_page( 'microblog', 'specmicroblog', $title, 1 ) or return;
  467. like( $body, qr{href='https://example\.com/spec' >Spec Microblog Child</a>}, 'title links out to href' );
  468. like( $body, qr{id="postData-\Q$child->{id}\E"}, 'body block rendered' );
  469. like( $body, qr/Spec microblog body\./, 'body text rendered' );
  470. };
  471. subtest 'file' => sub {
  472. my $title = 'Spec File Series';
  473. _make_series( 'file', 'specfile', 'file.tx', $title ) or return;
  474. # _handle_upload MOVES the file, so it has to be created fresh here.
  475. my $src = "$ROOT/upload-src/spec-upload.txt";
  476. open( my $fh, '>', $src ) or die $!;
  477. print {$fh} "spec upload contents\n";
  478. close $fh;
  479. my $child = _save_post(
  480. 'file child',
  481. form => 'file.tx',
  482. title => 'Spec File Child',
  483. data => 'Spec file body.',
  484. file => { tempname => $src, filename => 'spec-upload.txt' },
  485. visibility => 'public',
  486. tags => ['specfile'],
  487. to => '/specfile',
  488. ) or return;
  489. ok( !-e $src, 'the upload was moved out of its temp location, not copied' );
  490. ok( -f "www/assets/$child->{id}.spec-upload.txt", 'and it landed in www/assets' );
  491. my $body = _series_page( 'file', 'specfile', $title, 1 ) or return;
  492. like( $body, qr{href='/assets/\Q$child->{id}\E\.spec-upload\.txt'}, 'title links to the asset' );
  493. like( $body, qr{id="postData-\Q$child->{id}\E"}, 'body block carries a unique id, like every other form' );
  494. like( $body, qr/Spec file body\./, 'body text rendered' );
  495. # This form used to emit <div class="postData" id="postData" class="responsive-text">
  496. # -- a duplicated class attribute, and an id shared by every file post on
  497. # the page. Neither should come back.
  498. unlike( $body, qr{<div class="postData" id="postData"}, 'no duplicated class attribute' );
  499. # text/plain, so none of the media branches fire.
  500. unlike( $body, qr/<video/, 'no video block for a text file' );
  501. unlike( $body, qr/<audio/, 'no audio block either' );
  502. };
  503. subtest 'presentation' => sub {
  504. my $title = 'Spec Presentation Series';
  505. _make_series( 'presentation', 'specpresentation', 'presentation.tx', $title ) or return;
  506. my $child = _save_post(
  507. 'presentation child',
  508. form => 'presentation.tx',
  509. title => 'Spec Presentation Child',
  510. data => [ 'Slide one body.', 'Slide two body.' ],
  511. data_is_array => 1,
  512. visibility => 'public',
  513. tags => ['specpresentation'],
  514. to => '/specpresentation',
  515. ) or return;
  516. is_deeply( $child->{data}, [ 'Slide one body.', 'Slide two body.' ], 'the multi-page data round-tripped as an array' );
  517. my $body = _series_page( 'presentation', 'specpresentation', $title, 1 ) or return;
  518. # Slides only render under nochrome; the series page just links to the deck.
  519. like( $body, qr{<a href="/posts/\Q$child->{id}\E\?embed=1&nochrome=1">Click Here to view</a>}, 'deck link rendered' );
  520. unlike( $body, qr/Slide one body\./, 'slides themselves are not rendered inline' );
  521. };
  522. subtest 'invoice' => sub {
  523. my $title = 'Spec Invoice Series';
  524. _make_series( 'invoice', 'specinvoice', 'invoice.tx', $title ) or return;
  525. my $child = _save_post(
  526. 'invoice child',
  527. form => 'invoice.tx',
  528. title => 'Spec Invoice Child',
  529. data => [ "Widget assembly\nPrice: \$420", "Shipping\nPrice: \$80" ],
  530. data_is_array => 1,
  531. payee => $PAYEE->{id},
  532. payor => $PAYOR->{id},
  533. due_days => 30,
  534. visibility => 'public',
  535. tags => ['specinvoice'],
  536. to => '/specinvoice',
  537. ) or return;
  538. my $body = _series_page( 'invoice', 'specinvoice', $title, 1 ) or return;
  539. like( $body, qr/Invoice ID# \Q$child->{id}\E/, 'invoice header rendered' );
  540. # These two only resolve because the entities subtest ran first and left
  541. # public entities.tx posts behind for the enrich hook to find.
  542. like( $body, qr/Acme Payments LLC/, 'payee entity resolved' );
  543. like( $body, qr/Wile E Coyote/, 'payor entity resolved' );
  544. like( $body, qr/ACH/, 'payee payment method pulled through' );
  545. like( $body, qr/Widget assembly/, 'line items rendered' );
  546. like( $body, qr/Total: \$500/, 'total summed from the line item prices' );
  547. };
  548. subtest 'spec_widget (the wizard-built type)' => sub {
  549. my $title = 'Spec Widget Series';
  550. _make_series( 'spec_widget', 'specwidget', 'spec_widget.tx', $title ) or return;
  551. my $child = _save_post(
  552. 'spec_widget child',
  553. form => 'spec_widget.tx',
  554. title => 'Spec Widget Child',
  555. data => 'Spec widget body.',
  556. flavor => 'Strawberry',
  557. bogus_field => 'nope',
  558. visibility => 'public',
  559. tags => ['specwidget'],
  560. to => '/specwidget',
  561. ) or return;
  562. is( $child->{flavor}, 'Strawberry', 'the custom field survived validation' );
  563. ok( !exists $child->{bogus_field}, 'an undeclared field was still stripped' );
  564. my $body = _series_page( 'spec_widget', 'specwidget', $title, 1 ) or return;
  565. # The payoff: this can only render if the wizard wrote spec_widget.json,
  566. # schema_for merged it over the base post schema, and validate() therefore
  567. # kept 'flavor' instead of deleting it as an unknown key.
  568. like( $body, qr{<span class="spec-flavor">Strawberry</span>}, 'the custom field rendered on the page' );
  569. like( $body, qr/Spec widget body\./, 'and the body came through the generated template' );
  570. };
  571. subtest 'the topbar did not silently overflow' => sub {
  572. my ( $code, $body, $err ) = _render( _anon( route => '/' ) );
  573. is( $code, 200, '/ renders' ) or diag($err);
  574. my @titles = _topbar_titles($body);
  575. # 2 seeded series (Series, About) + the 7 we built. _get_series() caps at
  576. # 10 (HTML.pm), so an eighth post type would start silently dropping one.
  577. is( scalar @titles, 9, 'every series we made is in the topbar' )
  578. or diag( 'topbar was: ' . join( ', ', @titles ) );
  579. cmp_ok( scalar @titles, '<=', 10, 'and we are not at the _get_series limit' );
  580. };
  581. subtest 'the tpsgi side effects stayed inert' => sub {
  582. cmp_ok( $TPSGI->{restarts}, '>', 0, 'post_save did try to signal a restart' );
  583. cmp_ok( $TPSGI->{callbacks}, '>', 0, 'and did queue post-close callbacks' );
  584. # We never run the queued callbacks, which is what keeps save_render and
  585. # invalidate_renders from ever firing.
  586. is_deeply( $TPSGI->{renders}, {}, 'no static renders were written' );
  587. is_deeply( $TPSGI->{invalidated}, [], 'and nothing was invalidated' );
  588. my @statics = glob('www/statics/*');
  589. is_deeply( \@statics, [], 'www/statics is empty' );
  590. };
  591. subtest 'the real repo was not touched' => sub {
  592. my %after = map { _snapshot("$REPO/$_") } qw{config data www/templates www/assets logs totp};
  593. my @changed = grep { ( $REPO_BEFORE{$_} // '' ) ne ( $after{$_} // '' ) } keys %after;
  594. my @removed = grep { !exists $after{$_} } keys %REPO_BEFORE;
  595. is_deeply( [ sort @changed ], [], 'no repo file was added or modified' );
  596. is_deeply( [ sort @removed ], [], 'and none were removed' );
  597. ok( !-e "$REPO/www/templates/html/components/forms/spec_widget.tx", 'the wizard type is not in the repo' );
  598. };
  599. done_testing();