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

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