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

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