fix all the tests (for sqlite, php7.4, osx, at least)

This commit is contained in:
Shish 2020-01-28 21:19:59 +00:00
parent ac1076b3f3
commit 615da9e9d2
57 changed files with 665 additions and 859 deletions

View File

@ -113,7 +113,7 @@ class BasePage
// ============================================== // ==============================================
/** @var string */ /** @var string */
private $redirect = ""; public $redirect = "";
/** /**
* Set the URL to redirect to (remember to use make_link() if linking * Set the URL to redirect to (remember to use make_link() if linking
@ -256,6 +256,19 @@ class BasePage
$this->blocks[] = $block; $this->blocks[] = $block;
} }
/**
* Find a block which contains the given text
* (Useful for unit tests)
*/
public function find_block(string $text): ?Block {
foreach($this->blocks as $block) {
if($block->header == $text) {
return $block;
}
}
return null;
}
// ============================================== // ==============================================
/** /**
@ -298,8 +311,7 @@ class BasePage
# header('Expires: ' . gmdate('D, d M Y H:i:s', time() - 600) . ' GMT'); # header('Expires: ' . gmdate('D, d M Y H:i:s', time() - 600) . ' GMT');
#} #}
usort($this->blocks, "blockcmp"); usort($this->blocks, "blockcmp");
$pnbe = new PageNavBuildingEvent(); $pnbe = send_event(new PageNavBuildingEvent());
send_event($pnbe);
$nav_links = $pnbe->links; $nav_links = $pnbe->links;
@ -314,14 +326,12 @@ class BasePage
$sub_links = null; $sub_links = null;
// If one is, we just query for sub-menu options under that one tab // If one is, we just query for sub-menu options under that one tab
if ($active_link!==null) { if ($active_link!==null) {
$psnbe = new PageSubNavBuildingEvent($active_link->name); $psnbe = send_event(new PageSubNavBuildingEvent($active_link->name));
send_event($psnbe);
$sub_links = $psnbe->links; $sub_links = $psnbe->links;
} else { } else {
// Otherwise we query for the sub-items under each of the tabs // Otherwise we query for the sub-items under each of the tabs
foreach ($nav_links as $link) { foreach ($nav_links as $link) {
$psnbe = new PageSubNavBuildingEvent($link->name); $psnbe = send_event(new PageSubNavBuildingEvent($link->name));
send_event($psnbe);
// Now we check for a current link so we can identify the sub-links to show // Now we check for a current link so we can identify the sub-links to show
foreach ($psnbe->links as $sub_link) { foreach ($psnbe->links as $sub_link) {
@ -338,8 +348,6 @@ class BasePage
} }
} }
$sub_links = $sub_links??[]; $sub_links = $sub_links??[];
usort($nav_links, "sort_nav_links"); usort($nav_links, "sort_nav_links");
usort($sub_links, "sort_nav_links"); usort($sub_links, "sort_nav_links");

View File

@ -228,7 +228,9 @@ class CommandEvent extends Event
} }
} }
define("CLI_LOG_LEVEL", $log_level); if(!defined("CLI_LOG_LEVEL")) {
define("CLI_LOG_LEVEL", $log_level);
}
if (count($opts) > 0) { if (count($opts) > 0) {
$this->cmd = $opts[0]; $this->cmd = $opts[0];

View File

@ -8,8 +8,7 @@
* return data to the extension which sent them, for example: * return data to the extension which sent them, for example:
* *
* \code * \code
* $tfe = new TextFormattingEvent($original_text); * $tfe = send_event(new TextFormattingEvent($original_text));
* send_event($tfe);
* $formatted_text = $tfe->formatted; * $formatted_text = $tfe->formatted;
* \endcode * \endcode
* *
@ -381,16 +380,14 @@ abstract class DataHandlerExtension extends Extension
throw new UploadException("Data handler failed to create image object from data"); throw new UploadException("Data handler failed to create image object from data");
} }
$ire = new ImageReplaceEvent($image_id, $image); $ire = send_event(new ImageReplaceEvent($image_id, $image));
send_event($ire);
$event->image_id = $image_id; $event->image_id = $image_id;
} else { } else {
$image = $this->create_image_from_data(warehouse_path(Image::IMAGE_DIR, $event->hash), $event->metadata); $image = $this->create_image_from_data(warehouse_path(Image::IMAGE_DIR, $event->hash), $event->metadata);
if (is_null($image)) { if (is_null($image)) {
throw new UploadException("Data handler failed to create image object from data"); throw new UploadException("Data handler failed to create image object from data");
} }
$iae = new ImageAdditionEvent($image); $iae = send_event(new ImageAdditionEvent($image));
send_event($iae);
$event->image_id = $iae->image->id; $event->image_id = $iae->image->id;
$event->merged = $iae->merged; $event->merged = $iae->merged;

View File

@ -247,8 +247,7 @@ class Image
* Turn a bunch of strings into a bunch of TagCondition * Turn a bunch of strings into a bunch of TagCondition
* and ImgCondition objects * and ImgCondition objects
*/ */
$stpe = new SearchTermParseEvent(null, $terms); $stpe = send_event(new SearchTermParseEvent(null, $terms));
send_event($stpe);
if ($stpe->is_querylet_set()) { if ($stpe->is_querylet_set()) {
foreach ($stpe->get_querylets() as $querylet) { foreach ($stpe->get_querylets() as $querylet) {
$img_conditions[] = new ImgCondition($querylet, true); $img_conditions[] = new ImgCondition($querylet, true);
@ -265,8 +264,7 @@ class Image
continue; continue;
} }
$stpe = new SearchTermParseEvent($term, $terms); $stpe = send_event(new SearchTermParseEvent($term, $terms));
send_event($stpe);
if ($stpe->is_querylet_set()) { if ($stpe->is_querylet_set()) {
foreach ($stpe->get_querylets() as $querylet) { foreach ($stpe->get_querylets() as $querylet) {
$img_conditions[] = new ImgCondition($querylet, $positive); $img_conditions[] = new ImgCondition($querylet, $positive);
@ -674,8 +672,7 @@ class Image
public function parse_metatags(array $metatags, int $image_id): void public function parse_metatags(array $metatags, int $image_id): void
{ {
foreach ($metatags as $tag) { foreach ($metatags as $tag) {
$ttpe = new TagTermParseEvent($tag, $image_id, true); send_event(new TagTermParseEvent($tag, $image_id, true));
send_event($ttpe);
} }
} }
@ -735,8 +732,7 @@ class Image
// nothing seems to use this, sending the event out to 50 exts is a lot of overhead // nothing seems to use this, sending the event out to 50 exts is a lot of overhead
if (!SPEED_HAX) { if (!SPEED_HAX) {
$plte = new ParseLinkTemplateEvent($tmpl, $this); $plte = send_event(new ParseLinkTemplateEvent($tmpl, $this));
send_event($plte);
$tmpl = $plte->link; $tmpl = $plte->link;
} }

View File

@ -68,11 +68,10 @@ function add_image(string $tmpname, string $filename, string $tags): void
if (array_key_exists('extension', $pathinfo)) { if (array_key_exists('extension', $pathinfo)) {
$metadata['extension'] = $pathinfo['extension']; $metadata['extension'] = $pathinfo['extension'];
} }
$metadata['tags'] = Tag::explode($tags); $metadata['tags'] = Tag::explode($tags);
$metadata['source'] = null; $metadata['source'] = null;
$event = new DataUploadEvent($tmpname, $metadata); send_event(new DataUploadEvent($tmpname, $metadata));
send_event($event);
} }
/** /**

View File

@ -93,13 +93,13 @@ $_shm_event_count = 0;
/** /**
* Send an event to all registered Extensions. * Send an event to all registered Extensions.
*/ */
function send_event(Event $event): void function send_event(Event $event): Event
{ {
global $tracer_enabled; global $tracer_enabled;
global $_shm_event_listeners, $_shm_event_count, $_tracer; global $_shm_event_listeners, $_shm_event_count, $_tracer;
if (!isset($_shm_event_listeners[get_class($event)])) { if (!isset($_shm_event_listeners[get_class($event)])) {
return; return $event;
} }
$method_name = "on".str_replace("Event", "", get_class($event)); $method_name = "on".str_replace("Event", "", get_class($event));
@ -130,4 +130,6 @@ function send_event(Event $event): void
if ($tracer_enabled) { if ($tracer_enabled) {
$_tracer->end(); $_tracer->end();
} }
return $event;
} }

View File

@ -178,8 +178,7 @@ function get_session_ip(Config $config): string
*/ */
function format_text(string $string): string function format_text(string $string): string
{ {
$tfe = new TextFormattingEvent($string); $tfe = send_event(new TextFormattingEvent($string));
send_event($tfe);
return $tfe->formatted; return $tfe->formatted;
} }

View File

@ -171,105 +171,4 @@ class AdminPage extends Extension
log_warning("admin", "Re-counted tags", "Re-counted tags"); log_warning("admin", "Re-counted tags", "Re-counted tags");
return true; return true;
} }
private function database_dump()
{
global $page;
$matches = [];
preg_match("#^(?P<proto>\w+)\:(?:user=(?P<user>\w+)(?:;|$)|password=(?P<password>\w*)(?:;|$)|host=(?P<host>[\w\.\-]+)(?:;|$)|dbname=(?P<dbname>[\w_]+)(?:;|$))+#", DATABASE_DSN, $matches);
$software = $matches['proto'];
$username = $matches['user'];
$password = $matches['password'];
$hostname = $matches['host'];
$database = $matches['dbname'];
switch ($software) {
case DatabaseDriver::MYSQL:
$cmd = "mysqldump -h$hostname -u$username -p$password $database";
break;
case DatabaseDriver::PGSQL:
putenv("PGPASSWORD=$password");
$cmd = "pg_dump -h $hostname -U $username $database";
break;
case DatabaseDriver::SQLITE:
$cmd = "sqlite3 $database .dump";
break;
default:
$cmd = false;
}
//FIXME: .SQL dump is empty if cmd doesn't exist
if ($cmd) {
$page->set_mode(PageMode::DATA);
$page->set_type("application/x-unknown");
$page->set_filename('shimmie-'.date('Ymd').'.sql');
$page->set_data(shell_exec($cmd));
}
return false;
}
private function download_all_images()
{
global $database, $page;
$images = $database->get_all("SELECT hash, ext FROM images");
$filename = data_path('imgdump-'.date('Ymd').'.zip');
$zip = new ZipArchive;
if ($zip->open($filename, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) === true) {
foreach ($images as $img) {
$img_loc = warehouse_path(Image::IMAGE_DIR, $img["hash"], false);
$zip->addFile($img_loc, $img["hash"].".".$img["ext"]);
}
$zip->close();
}
$page->set_mode(PageMode::REDIRECT);
$page->set_redirect(make_link($filename)); //TODO: Delete file after downloaded?
return false; // we do want a redirect, but a manual one
}
private function reset_image_ids()
{
global $database;
//TODO: Make work with PostgreSQL + SQLite
//TODO: Update score_log (Having an optional ID column for score_log would be nice..)
preg_match("#^(?P<proto>\w+)\:(?:user=(?P<user>\w+)(?:;|$)|password=(?P<password>\w*)(?:;|$)|host=(?P<host>[\w\.\-]+)(?:;|$)|dbname=(?P<dbname>[\w_]+)(?:;|$))+#", DATABASE_DSN, $matches);
if ($matches['proto'] == DatabaseDriver::MYSQL) {
$tables = $database->get_col("SELECT TABLE_NAME
FROM information_schema.KEY_COLUMN_USAGE
WHERE TABLE_SCHEMA = :db
AND REFERENCED_COLUMN_NAME = 'id'
AND REFERENCED_TABLE_NAME = 'images'", ["db" => $matches['dbname']]);
$i = 1;
$ids = $database->get_col("SELECT id FROM images ORDER BY images.id ASC");
foreach ($ids as $id) {
$sql = "SET FOREIGN_KEY_CHECKS=0;
UPDATE images SET id={$i} WHERE image_id={$id};";
foreach ($tables as $table) {
$sql .= "UPDATE {$table} SET image_id={$i} WHERE image_id={$id};";
}
$sql .= " SET FOREIGN_KEY_CHECKS=1;";
$database->execute($sql);
$i++;
}
$database->execute("ALTER TABLE images AUTO_INCREMENT=".(count($ids) + 1));
} elseif ($matches['proto'] == DatabaseDriver::PGSQL) {
throw new SCoreException("TODO: Make this work with PostgreSQL");
} elseif ($matches['proto'] == DatabaseDriver::SQLITE) {
throw new SCoreException("TODO: Make this work with SQLite");
}
return true;
}
} }

View File

@ -3,62 +3,84 @@ class AdminPageTest extends ShimmiePHPUnitTestCase
{ {
public function testAuth() public function testAuth()
{ {
$this->get_page('admin'); send_event(new UserLoginEvent(User::by_name($this->anon_name)));
$this->assert_response(403); $page = $this->get_page('admin');
$this->assert_title("Permission Denied"); $this->assertEquals(403, $page->code);
$this->assertEquals("Permission Denied", $page->title);
$this->log_in_as_user(); send_event(new UserLoginEvent(User::by_name($this->user_name)));
$this->get_page('admin'); $page = $this->get_page('admin');
$this->assert_response(403); $this->assertEquals(403, $page->code);
$this->assert_title("Permission Denied"); $this->assertEquals("Permission Denied", $page->title);
$this->log_in_as_admin(); send_event(new UserLoginEvent(User::by_name($this->admin_name)));
$this->get_page('admin'); $page = $this->get_page('admin');
$this->assert_response(200); $this->assertEquals(200, $page->code);
$this->assert_title("Admin Tools"); $this->assertEquals("Admin Tools", $page->title);
} }
public function testLowercase() public function testLowercaseAndSetCase()
{ {
// Create a problem
$ts = time(); // we need a tag that hasn't been used before $ts = time(); // we need a tag that hasn't been used before
send_event(new UserLoginEvent(User::by_name($this->admin_name)));
$this->log_in_as_admin();
$image_id_1 = $this->post_image("tests/pbx_screenshot.jpg", "TeStCase$ts"); $image_id_1 = $this->post_image("tests/pbx_screenshot.jpg", "TeStCase$ts");
$this->get_page("post/view/$image_id_1"); // Validate problem
$this->assert_title("Image $image_id_1: TeStCase$ts"); $page = $this->get_page("post/view/$image_id_1");
$this->assertEquals("Image $image_id_1: TeStCase$ts", $page->title);
$this->get_page('admin'); // Fix
$this->assert_title("Admin Tools");
//$this->click("All tags to lowercase");
send_event(new AdminActionEvent('lowercase_all_tags')); send_event(new AdminActionEvent('lowercase_all_tags'));
// Validate fix
$this->get_page("post/view/$image_id_1"); $this->get_page("post/view/$image_id_1");
$this->assert_title("Image $image_id_1: testcase$ts"); $this->assert_title("Image $image_id_1: testcase$ts");
$this->delete_image($image_id_1); // Change
$_POST["tag"] = "TestCase$ts";
send_event(new AdminActionEvent('set_tag_case'));
// Validate change
$this->get_page("post/view/$image_id_1");
$this->assert_title("Image $image_id_1: TestCase$ts");
} }
# FIXME: make sure the admin tools actually work # FIXME: make sure the admin tools actually work
public function testRecount() public function testRecount()
{ {
$this->log_in_as_admin(); global $database;
$this->get_page('admin');
$this->assert_title("Admin Tools");
//$this->click("Recount tag use"); // Create a problem
$ts = time(); // we need a tag that hasn't been used before
send_event(new UserLoginEvent(User::by_name($this->admin_name)));
$database->execute(
"INSERT INTO tags(tag, count) VALUES(:tag, :count)",
["tag"=>"tes$ts", "count"=>42]
);
// Fix
send_event(new AdminActionEvent('recount_tag_use')); send_event(new AdminActionEvent('recount_tag_use'));
// Validate fix
$this->assertEquals(
0,
$database->get_one(
"SELECT count FROM tags WHERE tag = :tag",
["tag"=>"tes$ts"]
)
);
} }
public function testDump() public function testCommands()
{ {
$this->log_in_as_admin(); send_event(new UserLoginEvent(User::by_name($this->admin_name)));
$this->get_page('admin'); ob_start();
$this->assert_title("Admin Tools"); send_event(new CommandEvent(["index.php", "help"]));
send_event(new CommandEvent(["index.php", "get-page", "post/list"]));
// this calls mysqldump which jams up travis prompting for a password send_event(new CommandEvent(["index.php", "post-page", "post/list", "foo=bar"]));
//$this->click("Download database contents"); send_event(new CommandEvent(["index.php", "get-token"]));
//send_event(new AdminActionEvent('database_dump')); send_event(new CommandEvent(["index.php", "regen-thumb", "42"]));
//$this->assert_response(200); ob_end_clean();
} }
} }

View File

@ -42,13 +42,6 @@ class AdminPageTheme extends Themelet
$html = ""; $html = "";
$html .= $this->button("All tags to lowercase", "lowercase_all_tags", true); $html .= $this->button("All tags to lowercase", "lowercase_all_tags", true);
$html .= $this->button("Recount tag use", "recount_tag_use", false); $html .= $this->button("Recount tag use", "recount_tag_use", false);
if (class_exists('ZipArchive')) {
$html .= $this->button("Download all images", "download_all_images", false);
}
$html .= $this->button("Download database contents", "database_dump", false);
if ($database->get_driver_name() == DatabaseDriver::MYSQL) {
$html .= $this->button("Reset image IDs", "reset_image_ids", true);
}
$page->add_block(new Block("Misc Admin Tools", $html)); $page->add_block(new Block("Misc Admin Tools", $html));
$html = (string)SHM_SIMPLE_FORM( $html = (string)SHM_SIMPLE_FORM(

View File

@ -39,6 +39,14 @@ class AddAliasEvent extends Event
} }
} }
class DeleteAliasEvent extends Event {
public $oldtag;
public function __construct(string $oldtag) {
$this->oldtag = $oldtag;
}
}
class AddAliasException extends SCoreException class AddAliasException extends SCoreException
{ {
} }
@ -58,8 +66,7 @@ class AliasEditor extends Extension
$user->ensure_authed(); $user->ensure_authed();
$input = validate_input(["c_oldtag"=>"string", "c_newtag"=>"string"]); $input = validate_input(["c_oldtag"=>"string", "c_newtag"=>"string"]);
try { try {
$aae = new AddAliasEvent($input['c_oldtag'], $input['c_newtag']); send_event(new AddAliasEvent($input['c_oldtag'], $input['c_newtag']));
send_event($aae);
$page->set_mode(PageMode::REDIRECT); $page->set_mode(PageMode::REDIRECT);
$page->set_redirect(make_link("alias/list")); $page->set_redirect(make_link("alias/list"));
} catch (AddAliasException $ex) { } catch (AddAliasException $ex) {
@ -70,8 +77,7 @@ class AliasEditor extends Extension
if ($user->can(Permissions::MANAGE_ALIAS_LIST)) { if ($user->can(Permissions::MANAGE_ALIAS_LIST)) {
$user->ensure_authed(); $user->ensure_authed();
$input = validate_input(["d_oldtag"=>"string"]); $input = validate_input(["d_oldtag"=>"string"]);
$database->execute("DELETE FROM aliases WHERE oldtag=:oldtag", ["oldtag" => $input['d_oldtag']]); send_event(new DeleteAliasEvent($input['d_oldtag']));
log_info("alias_editor", "Deleted alias for ".$input['d_oldtag'], "Deleted alias");
$page->set_mode(PageMode::REDIRECT); $page->set_mode(PageMode::REDIRECT);
$page->set_redirect(make_link("alias/list")); $page->set_redirect(make_link("alias/list"));
} }
@ -136,6 +142,12 @@ class AliasEditor extends Extension
log_info("alias_editor", "Added alias for {$event->oldtag} -> {$event->newtag}", "Added alias"); log_info("alias_editor", "Added alias for {$event->oldtag} -> {$event->newtag}", "Added alias");
} }
public function onDeleteAlias(DeleteAliasEvent $event) {
global $database;
$database->execute("DELETE FROM aliases WHERE oldtag=:oldtag", ["oldtag" => $event->oldtag]);
log_info("alias_editor", "Deleted alias for {$event->oldtag}", "Deleted alias");
}
public function onPageSubNavBuilding(PageSubNavBuildingEvent $event) public function onPageSubNavBuilding(PageSubNavBuildingEvent $event)
{ {
if ($event->parent=="tags") { if ($event->parent=="tags") {
@ -168,8 +180,7 @@ class AliasEditor extends Extension
$parts = str_getcsv($line); $parts = str_getcsv($line);
if (count($parts) == 2) { if (count($parts) == 2) {
try { try {
$aae = new AddAliasEvent($parts[0], $parts[1]); send_event(new AddAliasEvent($parts[0], $parts[1]));
send_event($aae);
} catch (AddAliasException $ex) { } catch (AddAliasException $ex) {
$this->theme->display_error(500, "Error adding alias", $ex->getMessage()); $this->theme->display_error(500, "Error adding alias", $ex->getMessage());
} }

View File

@ -10,98 +10,74 @@ class AliasEditorTest extends ShimmiePHPUnitTestCase
public function testAliasListReadOnly() public function testAliasListReadOnly()
{ {
// Check that normal users can't add aliases.
$this->log_in_as_user(); $this->log_in_as_user();
$this->get_page('alias/list'); $this->get_page('alias/list');
$this->assert_title("Alias List"); $this->assert_title("Alias List");
$this->assert_no_text("Add"); $this->assert_no_text("Add");
$this->log_out();
$this->get_page('alias/list');
$this->assert_title("Alias List");
$this->assert_no_text("Add");
} }
public function testAliasEditor() public function testAliasOneToOne() {
{
/*
**********************************************************************
* FIXME: TODO:
* For some reason the alias tests always fail when they are running
* inside the TravisCI VM environment. I have tried to determine
* the exact cause of this, but have been unable to pin it down.
*
* For now, I am commenting them out until I have more time to
* dig into this and determine exactly what is happening.
*
*********************************************************************
*/
$this->markTestIncomplete();
$this->log_in_as_admin(); $this->log_in_as_admin();
# test one to one $this->get_page("alias/export/aliases.csv");
$this->get_page('alias/list'); $this->assert_no_text("test1");
$this->assert_title("Alias List");
$this->set_field('oldtag', "test1");
$this->set_field('newtag', "test2");
$this->clickSubmit('Add');
$this->assert_no_text("Error adding alias");
send_event(new AddAliasEvent("test1", "test2"));
$this->get_page('alias/list'); $this->get_page('alias/list');
$this->assert_text("test1"); $this->assert_text("test1");
$this->get_page("alias/export/aliases.csv"); $this->get_page("alias/export/aliases.csv");
$this->assert_text("test1,test2"); $this->assert_text('"test1","test2"');
$image_id = $this->post_image("tests/pbx_screenshot.jpg", "test1"); $image_id = $this->post_image("tests/pbx_screenshot.jpg", "test1");
$this->get_page("post/view/$image_id"); # check that the tag has been replaced $this->get_page("post/view/$image_id"); # check that the tag has been replaced
$this->assert_title("Image $image_id: test2"); $this->assert_title("Image $image_id: test2");
$this->get_page("post/list/test1/1"); # searching for an alias should find the master tag $this->get_page("post/list/test1/1"); # searching for an alias should find the master tag
$this->assert_title("Image $image_id: test2"); $this->assert_response(302);
$this->get_page("post/list/test2/1"); # check that searching for the main tag still works $this->get_page("post/list/test2/1"); # check that searching for the main tag still works
$this->assert_title("Image $image_id: test2"); $this->assert_response(302);
$this->delete_image($image_id); $this->delete_image($image_id);
$this->get_page('alias/list'); send_event(new DeleteAliasEvent("test1"));
$this->click("Remove");
$this->get_page('alias/list'); $this->get_page('alias/list');
$this->assert_title("Alias List"); $this->assert_title("Alias List");
$this->assert_no_text("test1"); $this->assert_no_text("test1");
}
# test one to many public function testAliasOneToMany() {
$this->get_page('alias/list'); $this->log_in_as_admin();
$this->assert_title("Alias List");
$this->set_field('oldtag', "onetag"); $this->get_page("alias/export/aliases.csv");
$this->set_field('newtag', "multi tag"); $this->assert_no_text("multi");
$this->click("Add");
send_event(new AddAliasEvent("onetag", "multi tag"));
$this->get_page('alias/list'); $this->get_page('alias/list');
$this->assert_text("multi"); $this->assert_text("multi");
$this->assert_text("tag"); $this->assert_text("tag");
$this->get_page("alias/export/aliases.csv"); $this->get_page("alias/export/aliases.csv");
$this->assert_text("onetag,multi tag"); $this->assert_text('"onetag","multi tag"');
$image_id_1 = $this->post_image("tests/pbx_screenshot.jpg", "onetag"); $image_id_1 = $this->post_image("tests/pbx_screenshot.jpg", "onetag");
$image_id_2 = $this->post_image("tests/bedroom_workshop.jpg", "onetag"); $image_id_2 = $this->post_image("tests/bedroom_workshop.jpg", "onetag");
// FIXME: known broken $this->get_page("post/list/onetag/1"); # searching for an aliased tag should find its aliases
//$this->get_page("post/list/onetag/1"); # searching for an aliased tag should find its aliases $this->assert_title("multi tag");
//$this->assert_title("onetag"); $this->assert_no_text("No Images Found");
//$this->assert_no_text("No Images Found");
$this->get_page("post/list/multi/1"); $this->get_page("post/list/multi/1");
$this->assert_title("multi"); $this->assert_title("multi");
$this->assert_no_text("No Images Found"); $this->assert_no_text("No Images Found");
$this->get_page("post/list/multi%20tag/1"); $this->get_page("post/list/multi tag/1");
$this->assert_title("multi tag"); $this->assert_title("multi tag");
$this->assert_no_text("No Images Found"); $this->assert_no_text("No Images Found");
$this->delete_image($image_id_1); $this->delete_image($image_id_1);
$this->delete_image($image_id_2); $this->delete_image($image_id_2);
$this->get_page('alias/list'); send_event(new DeleteAliasEvent("onetag"));
$this->click("Remove");
$this->get_page('alias/list'); $this->get_page('alias/list');
$this->assert_title("Alias List"); $this->assert_title("Alias List");
$this->assert_no_text("test1"); $this->assert_no_text("test1");
$this->log_out();
$this->get_page('alias/list');
$this->assert_title("Alias List");
$this->assert_no_text("Add");
} }
} }

View File

@ -1,5 +1,5 @@
<?php declare(strict_types=1); <?php declare(strict_types=1);
class ArtistTest extends ShimmiePHPUnitTestCase class ArtistsTest extends ShimmiePHPUnitTestCase
{ {
public function testSearch() public function testSearch()
{ {

12
ext/autocomplete/test.php Normal file
View File

@ -0,0 +1,12 @@
<?php
declare(strict_types=1);
class AutoCompleteTest extends ShimmiePHPUnitTestCase {
public function testAuth() {
send_event(new UserLoginEvent(User::by_name($this->anon_name)));
$page = $this->get_page('api/internal/autocomplete', ["s"=>"not-a-tag"]);
$this->assertEquals(200, $page->code);
$this->assertEquals(PageMode::DATA, $page->mode);
$this->assertEquals("[]", $page->data);
}
}

View File

@ -175,8 +175,7 @@ class BulkActions extends Extension
} }
if (is_iterable($items)) { if (is_iterable($items)) {
$newEvent = new BulkActionEvent($action, $items); send_event(new BulkActionEvent($action, $items));
send_event($newEvent);
} }
$page->set_mode(PageMode::REDIRECT); $page->set_mode(PageMode::REDIRECT);

View File

@ -21,8 +21,7 @@ class BulkAdd extends Extension
if ($event->page_matches("bulk_add")) { if ($event->page_matches("bulk_add")) {
if ($user->can(Permissions::BULK_ADD) && $user->check_auth_token() && isset($_POST['dir'])) { if ($user->can(Permissions::BULK_ADD) && $user->check_auth_token() && isset($_POST['dir'])) {
set_time_limit(0); set_time_limit(0);
$bae = new BulkAddEvent($_POST['dir']); $bae = send_event(new BulkAddEvent($_POST['dir']));
send_event($bae);
foreach ($bae->results as $result) { foreach ($bae->results as $result) {
$this->theme->add_status("Adding files", $result); $this->theme->add_status("Adding files", $result);
} }
@ -39,8 +38,7 @@ class BulkAdd extends Extension
} }
if ($event->cmd == "bulk-add") { if ($event->cmd == "bulk-add") {
if (count($event->args) == 1) { if (count($event->args) == 1) {
$bae = new BulkAddEvent($event->args[0]); $bae = send_event(new BulkAddEvent($event->args[0]));
send_event($bae);
print(implode("\n", $bae->results)); print(implode("\n", $bae->results));
} }
} }

View File

@ -2,42 +2,20 @@
class BulkAddTest extends ShimmiePHPUnitTestCase class BulkAddTest extends ShimmiePHPUnitTestCase
{ {
public function testBulkAdd() public function testInvalidDir() {
{ send_event(new UserLoginEvent(User::by_name($this->admin_name)));
$this->log_in_as_admin(); $bae = send_event(new BulkAddEvent('asdf'));
$this->get_page('admin');
$this->assert_title("Admin Tools");
$bae = new BulkAddEvent('asdf');
send_event($bae);
$this->assertContains( $this->assertContains(
"Error, asdf is not a readable directory", "Error, asdf is not a readable directory",
$bae->results, $bae->results,
implode("\n", $bae->results) implode("\n", $bae->results)
); );
}
// FIXME: have BAE return a list of successes as well as errors? public function testValidDir() {
$this->markTestIncomplete(); send_event(new UserLoginEvent(User::by_name($this->admin_name)));
$this->get_page('admin');
$this->assert_title("Admin Tools");
send_event(new BulkAddEvent('tests')); send_event(new BulkAddEvent('tests'));
$page = $this->get_page("post/list/hash=17fc89f372ed3636e28bd25cc7f3bac1/1");
# FIXME: test that the output here makes sense, no "adding foo.php ... ok" $this->assertEquals(302, $page->code);
$this->get_page("post/list/hash=17fc89f372ed3636e28bd25cc7f3bac1/1");
$this->assert_title_matches(new PatternExpectation("/^Image \d+: data/"));
$this->click("Delete");
$this->get_page("post/list/hash=feb01bab5698a11dd87416724c7a89e3/1");
$this->assert_title_matches(new PatternExpectation("/^Image \d+: data/"));
$this->click("Delete");
$this->get_page("post/list/hash=e106ea2983e1b77f11e00c0c54e53805/1");
$this->assert_title_matches(new PatternExpectation("/^Image \d+: data/"));
$this->click("Delete");
$this->log_out();
} }
} }

View File

@ -53,14 +53,12 @@ class BulkAddCSV extends Extension
} }
$metadata['tags'] = Tag::explode($tags); $metadata['tags'] = Tag::explode($tags);
$metadata['source'] = $source; $metadata['source'] = $source;
$event = new DataUploadEvent($tmpname, $metadata); $event = send_event(new DataUploadEvent($tmpname, $metadata));
send_event($event);
if ($event->image_id == -1) { if ($event->image_id == -1) {
throw new UploadException("File type not recognised"); throw new UploadException("File type not recognised");
} else { } else {
if (class_exists("RatingSetEvent") && in_array($rating, ["s", "q", "e"])) { if (class_exists("RatingSetEvent") && in_array($rating, ["s", "q", "e"])) {
$ratingevent = new RatingSetEvent(Image::by_id($event->image_id), $rating); send_event(new RatingSetEvent(Image::by_id($event->image_id), $rating));
send_event($ratingevent);
} }
if (file_exists($thumbfile)) { if (file_exists($thumbfile)) {
copy($thumbfile, warehouse_path(Image::THUMBNAIL_DIR, $event->hash)); copy($thumbfile, warehouse_path(Image::THUMBNAIL_DIR, $event->hash));

View File

@ -87,25 +87,20 @@ class CommentListTest extends ShimmiePHPUnitTestCase
public function testSingleDel() public function testSingleDel()
{ {
$this->markTestIncomplete(); global $database, $user;
$this->log_in_as_admin(); $this->log_in_as_admin();
$image_id = $this->post_image("tests/pbx_screenshot.jpg", "pbx"); $image_id = $this->post_image("tests/pbx_screenshot.jpg", "pbx");
# make a comment # make a comment
$this->get_page("post/view/$image_id"); send_event(new CommentPostingEvent($image_id, $user, "Test Comment ASDFASDF"));
$this->set_field('comment', "Test Comment ASDFASDF"); $page = $this->get_page("post/view/$image_id");
$this->click("Post Comment");
$this->assert_title("Image $image_id: pbx");
$this->assert_text("ASDFASDF"); $this->assert_text("ASDFASDF");
# delete it # delete a comment
$this->click("Del"); $comment_id = (int)$database->get_one("SELECT id FROM comments");
$this->assert_title("Image $image_id: pbx"); send_event(new CommentDeletionEvent($comment_id));
$page = $this->get_page("post/view/$image_id");
$this->assert_no_text("ASDFASDF"); $this->assert_no_text("ASDFASDF");
# tidy up
$this->delete_image($image_id);
$this->log_out();
} }
} }

View File

@ -1,5 +1,5 @@
<?php declare(strict_types=1); <?php declare(strict_types=1);
class EmoticonTest extends ShimmiePHPUnitTestCase class EmoticonsTest extends ShimmiePHPUnitTestCase
{ {
public function testEmoticons() public function testEmoticons()
{ {

View File

@ -3,28 +3,37 @@ class FavoritesTest extends ShimmiePHPUnitTestCase
{ {
public function testFavorites() public function testFavorites()
{ {
global $user;
$this->log_in_as_user(); $this->log_in_as_user();
$image_id = $this->post_image("tests/pbx_screenshot.jpg", "test"); $image_id = $this->post_image("tests/pbx_screenshot.jpg", "test");
# No favourites
$this->get_page("post/view/$image_id"); $this->get_page("post/view/$image_id");
$this->assert_title("Image $image_id: test"); $this->assert_title("Image $image_id: test");
$this->assert_no_text("Favorited By"); $this->assert_no_text("Favorited By");
$this->markTestIncomplete(); # Add a favourite
send_event(new FavoriteSetEvent($image_id, $user, true));
$this->click("Favorite"); # Favourite shown on page
$this->assert_text("Favorited By"); $this->get_page("post/view/$image_id");
$this->get_page("post/list/favorited_by=test/1");
$this->assert_title("Image $image_id: test"); $this->assert_title("Image $image_id: test");
$this->assert_text("Favorited By"); $this->assert_text("Favorited By");
# Favourite shown on index
$page = $this->get_page("post/list/favorited_by=test/1");
$this->assertEquals(PageMode::REDIRECT, $page->mode);
# Favourite shown on user page
$this->get_page("user/test"); $this->get_page("user/test");
$this->assert_text("Images favorited: 1"); $this->assert_text("Images favorited</a>: 1");
$this->click("Images favorited");
$this->assert_title("Image $image_id: test");
$this->click("Un-Favorite"); # Delete a favourite
send_event(new FavoriteSetEvent($image_id, $user, false));
# No favourites
$this->get_page("post/view/$image_id");
$this->assert_title("Image $image_id: test");
$this->assert_no_text("Favorited By"); $this->assert_no_text("Favorited By");
} }
} }

View File

@ -3,33 +3,33 @@ class FeaturedTest extends ShimmiePHPUnitTestCase
{ {
public function testFeatured() public function testFeatured()
{ {
global $config;
// Set up
$this->log_in_as_user(); $this->log_in_as_user();
$image_id = $this->post_image("tests/pbx_screenshot.jpg", "pbx"); $image_id = $this->post_image("tests/pbx_screenshot.jpg", "pbx");
# FIXME: test that regular users can't feature things # FIXME: test that regular users can't feature things
$this->log_in_as_admin(); // Admin can feature things
$this->get_page("post/view/$image_id"); // FIXME: use Event rather than modifying database
$this->assert_title("Image $image_id: pbx"); // $this->log_in_as_admin();
// send_event(new SetFeaturedEvent($image_id));
$config->set_int("featured_id", $image_id);
$this->markTestIncomplete();
$this->click("Feature This");
$this->get_page("post/list"); $this->get_page("post/list");
$this->assert_text("Featured Image"); $this->assert_text("Featured Image");
# FIXME: test changing from one feature to another # FIXME: test changing from one feature to another
$this->get_page("featured_image/download"); $page = $this->get_page("featured_image/download");
$this->assert_response(200); $this->assertEquals(200, $page->code);
$this->get_page("featured_image/view"); $page = $this->get_page("featured_image/view");
$this->assert_response(200); $this->assertEquals(200, $page->code);
// after deletion, there should be no feature
$this->delete_image($image_id); $this->delete_image($image_id);
$this->log_out();
# after deletion, there should be no feature
$this->get_page("post/list"); $this->get_page("post/list");
$this->assert_no_text("Featured Image"); $this->assert_no_text("Featured Image");
} }

View File

@ -1,5 +1,5 @@
<?php declare(strict_types=1); <?php declare(strict_types=1);
class IcoHandlerTest extends ShimmiePHPUnitTestCase class IcoFileHandlerTest extends ShimmiePHPUnitTestCase
{ {
public function testIcoHander() public function testIcoHander()
{ {

View File

@ -1,5 +1,5 @@
<?php declare(strict_types=1); <?php declare(strict_types=1);
class PixelHandlerTest extends ShimmiePHPUnitTestCase class PixelFileHandlerTest extends ShimmiePHPUnitTestCase
{ {
public function testPixelHander() public function testPixelHander()
{ {

View File

@ -1,5 +1,5 @@
<?php declare(strict_types=1); <?php declare(strict_types=1);
class SVGHandlerTest extends ShimmiePHPUnitTestCase class SVGFileHandlerTest extends ShimmiePHPUnitTestCase
{ {
public function testSVGHander() public function testSVGHander()
{ {

View File

@ -1,34 +1,39 @@
<?php declare(strict_types=1); <?php declare(strict_types=1);
class HashBanTest extends ShimmiePHPUnitTestCase class ImageBanTest extends ShimmiePHPUnitTestCase
{ {
public function testBan() public function testBan()
{ {
$this->log_in_as_user();
$image_id = $this->post_image("tests/pbx_screenshot.jpg", "pbx");
$this->log_out();
$this->log_in_as_admin(); $this->log_in_as_admin();
$this->get_page("post/view/$image_id"); $hash = "feb01bab5698a11dd87416724c7a89e3";
$this->markTestIncomplete(); // Post image
$this->click("Ban and Delete");
$this->log_out();
$this->log_in_as_user();
$this->get_page("post/view/$image_id");
$this->assert_response(404);
$image_id = $this->post_image("tests/pbx_screenshot.jpg", "pbx"); $image_id = $this->post_image("tests/pbx_screenshot.jpg", "pbx");
$this->get_page("post/view/$image_id"); $page = $this->get_page("post/view/$image_id");
$this->assert_response(404); $this->assertEquals(200, $page->code);
$this->log_in_as_admin(); // Ban & delete
$this->get_page("image_hash_ban/list/1"); send_event(new AddImageHashBanEvent($hash, "test hash ban"));
$this->click("Remove"); send_event(new ImageDeletionEvent(Image::by_id($image_id)));
$this->log_in_as_user(); // Check deleted
$page = $this->get_page("post/view/$image_id");
$this->assertEquals(404, $page->code);
// Can't repost
try {
$this->post_image("tests/pbx_screenshot.jpg", "pbx");
$this->assertTrue(false);
}
catch(UploadException $e) {
$this->assertTrue(true);
}
// Remove ban
send_event(new RemoveImageHashBanEvent($hash));
// Can repost
$image_id = $this->post_image("tests/pbx_screenshot.jpg", "pbx"); $image_id = $this->post_image("tests/pbx_screenshot.jpg", "pbx");
$this->get_page("post/view/$image_id"); $page = $this->get_page("post/view/$image_id");
$this->assert_response(200); $this->assertEquals(200, $page->code);
} }
} }

View File

@ -155,12 +155,6 @@ class IndexTest extends ShimmiePHPUnitTestCase
{ {
$image_ids = $this->upload(); $image_ids = $this->upload();
global $database;
$db = $database->get_driver_name();
if ($db == DatabaseDriver::PGSQL || $db == DatabaseDriver::SQLITE) {
$this->markTestIncomplete();
}
// Only the first image matches both the wildcard and the tag. // Only the first image matches both the wildcard and the tag.
// This checks for https://github.com/shish/shimmie2/issues/547 // This checks for https://github.com/shish/shimmie2/issues/547
// (comp* is expanded to "computer computing", then we searched // (comp* is expanded to "computer computing", then we searched
@ -179,7 +173,7 @@ class IndexTest extends ShimmiePHPUnitTestCase
$this->get_page("post/list/comp*/1"); $this->get_page("post/list/comp*/1");
$this->assert_response(200); $this->assert_response(200);
} }
/* * * * * * * * * * * /* * * * * * * * * * *
* Mixed * * Mixed *
* * * * * * * * * * */ * * * * * * * * * * */
@ -201,7 +195,7 @@ class IndexTest extends ShimmiePHPUnitTestCase
* * * * * * * * * * */ * * * * * * * * * * */
public function testOther() public function testOther()
{ {
$this->markTestIncomplete(); $image_ids = $this->upload();
# negative tag, should have one result # negative tag, should have one result
$this->get_page('post/list/computer -pbx/1'); $this->get_page('post/list/computer -pbx/1');
@ -209,8 +203,8 @@ class IndexTest extends ShimmiePHPUnitTestCase
# negative tag alone, should work # negative tag alone, should work
# FIXME: known broken in mysql # FIXME: known broken in mysql
//$this->get_page('post/list/-pbx/1'); $this->get_page('post/list/-pbx/1');
//$this->assert_response(302); $this->assert_response(302);
# test various search methods # test various search methods
$this->get_page("post/list/bedroo*/1"); $this->get_page("post/list/bedroo*/1");

View File

@ -257,7 +257,7 @@ class IPBan extends Extension
{ {
global $cache, $user, $database; global $cache, $user, $database;
$sql = "INSERT INTO bans (ip, mode, reason, expires, banner_id) VALUES (:ip, :mode, :reason, :expires, :admin_id)"; $sql = "INSERT INTO bans (ip, mode, reason, expires, banner_id) VALUES (:ip, :mode, :reason, :expires, :admin_id)";
$database->Execute($sql, ["ip"=>$event->ip, "mode"=>$event->mode, "reason"=>$event->reason, "expires"=>$event->expires, "admin_id"=>$user->id]); $database->execute($sql, ["ip"=>$event->ip, "mode"=>$event->mode, "reason"=>$event->reason, "expires"=>$event->expires, "admin_id"=>$user->id]);
$cache->delete("ip_bans"); $cache->delete("ip_bans");
$cache->delete("network_bans"); $cache->delete("network_bans");
log_info("ipban", "Banned ({$event->mode}) {$event->ip} because '{$event->reason}' until {$event->expires}"); log_info("ipban", "Banned ({$event->mode}) {$event->ip} because '{$event->reason}' until {$event->expires}");
@ -284,6 +284,7 @@ class IPBan extends Extension
$database->create_table("bans", " $database->create_table("bans", "
id SCORE_AIPK, id SCORE_AIPK,
banner_id INTEGER NOT NULL, banner_id INTEGER NOT NULL,
mode VARCHAR(16) NOT NULL DEFAULT 'block',
ip SCORE_INET NOT NULL, ip SCORE_INET NOT NULL,
reason TEXT NOT NULL, reason TEXT NOT NULL,
added TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, added TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,

View File

@ -1,30 +1,53 @@
<?php declare(strict_types=1); <?php declare(strict_types=1);
class IPBanTest extends ShimmiePHPUnitTestCase class IPBanTest extends ShimmiePHPUnitTestCase
{ {
public function testIPBan() # FIXME: test that the IP is actually banned
{
$this->get_page('ip_ban/list'); public function testAccess() {
$this->assert_response(403); $page = $this->get_page('ip_ban/list');
$this->assert_title("Permission Denied"); $this->assertEquals(403, $page->code);
$this->assertEquals("Permission Denied", $page->title);
}
public function testIPBan() {
global $database;
$this->log_in_as_admin(); $this->log_in_as_admin();
// Check initial state
$this->get_page('ip_ban/list'); $this->get_page('ip_ban/list');
$this->assert_no_text("42.42.42.42"); $this->assert_no_text("42.42.42.42");
$this->markTestIncomplete(); // Add ban
send_event(new AddIPBanEvent(
'42.42.42.42',
'block',
'unit testing',
'2099-01-01'
));
$this->set_field('c_ip', '42.42.42.42'); // Check added
$this->set_field('c_reason', 'unit testing'); $page = $this->get_page('ip_ban/list');
$this->set_field('c_expires', '1 week'); $this->assertStringContainsString(
$this->click("Ban"); "42.42.42.42",
$page->find_block("Edit IP Bans")->body
);
$this->assert_text("42.42.42.42"); // Delete ban
$this->click("Remove"); // FIXME: remove which ban? :S $ban_id = (int)$database->get_one("SELECT id FROM bans");
$this->assert_no_text("42.42.42.42"); send_event(new RemoveIPBanEvent($ban_id));
// Check delete
$page = $this->get_page('ip_ban/list');
$this->assertStringNotContainsString(
"42.42.42.42",
$page->find_block("Edit IP Bans")->body
);
}
public function test_all() {
$this->log_in_as_admin();
$this->get_page('ip_ban/list?r_all=on'); // just test it doesn't crash for now $this->get_page('ip_ban/list?r_all=on'); // just test it doesn't crash for now
# FIXME: test that the IP is actually banned
} }
} }

View File

@ -5,21 +5,12 @@ class LinkImageTest extends ShimmiePHPUnitTestCase
{ {
$this->log_in_as_user(); $this->log_in_as_user();
$image_id = $this->post_image("tests/pbx_screenshot.jpg", "pie"); $image_id = $this->post_image("tests/pbx_screenshot.jpg", "pie");
# FIXME
# look in the "plain text link to post" box, follow the link
# in there, see if it takes us to the right page
$this->get_page("post/view/$image_id"); $this->get_page("post/view/$image_id");
$this->markTestIncomplete();
// FIXME
$matches = []; $matches = [];
preg_match("#value='(http://.*(/|%2F)post(/|%2F)view(/|%2F)[0-9]+)'#", $this->page_to_text(), $matches); preg_match("#value='https?://.*/(post/view/[0-9]+)'#", $this->page_to_text(), $matches);
$this->assertTrue(count($matches) > 0); $this->assertTrue(count($matches) > 0);
if ($matches) { $page = $this->get_page($matches[1]);
$this->get($matches[1]); $this->assertEquals("Image $image_id: pie", $page->title);
$this->assert_title("Image $image_id: pie");
}
} }
} }

View File

@ -3,59 +3,55 @@ class NumericScoreTest extends ShimmiePHPUnitTestCase
{ {
public function testNumericScore() public function testNumericScore()
{ {
global $user;
$this->log_in_as_user(); $this->log_in_as_user();
$image_id = $this->post_image("tests/pbx_screenshot.jpg", "pbx"); $image_id = $this->post_image("tests/pbx_screenshot.jpg", "pbx");
$this->get_page("post/view/$image_id"); $this->get_page("post/view/$image_id");
$this->markTestIncomplete();
$this->assert_text("Current Score: 0"); $this->assert_text("Current Score: 0");
$this->click("Vote Down");
send_event(new NumericScoreSetEvent($image_id, $user, -1));
$this->get_page("post/view/$image_id");
$this->assert_text("Current Score: -1"); $this->assert_text("Current Score: -1");
$this->click("Vote Up");
send_event(new NumericScoreSetEvent($image_id, $user, 1));
$this->get_page("post/view/$image_id");
$this->assert_text("Current Score: 1"); $this->assert_text("Current Score: 1");
# FIXME: "remove vote" button?
# FIXME: test that up and down are hidden if already voted up or down # FIXME: test that up and down are hidden if already voted up or down
# test search by score # test search by score
$this->get_page("post/list/score=1/1"); $page = $this->get_page("post/list/score=1/1");
$this->assert_title("Image $image_id: pbx"); $this->assertEquals(PageMode::REDIRECT, $page->mode);
$this->get_page("post/list/score>0/1"); $page = $this->get_page("post/list/score>0/1");
$this->assert_title("Image $image_id: pbx"); $this->assertEquals(PageMode::REDIRECT, $page->mode);
$this->get_page("post/list/score>-5/1"); $page = $this->get_page("post/list/score>-5/1");
$this->assert_title("Image $image_id: pbx"); $this->assertEquals(PageMode::REDIRECT, $page->mode);
$this->get_page("post/list/-score>5/1"); $page = $this->get_page("post/list/-score>5/1");
$this->assert_title("Image $image_id: pbx"); $this->assertEquals(PageMode::REDIRECT, $page->mode);
$this->get_page("post/list/-score<-5/1"); $page = $this->get_page("post/list/-score<-5/1");
$this->assert_title("Image $image_id: pbx"); $this->assertEquals(PageMode::REDIRECT, $page->mode);
# test search by vote # test search by vote
$this->get_page("post/list/upvoted_by=test/1"); $page = $this->get_page("post/list/upvoted_by=test/1");
$this->assert_title("Image $image_id: pbx"); $this->assertEquals(PageMode::REDIRECT, $page->mode);
$this->assert_no_text("No Images Found");
# and downvote # and downvote
$this->get_page("post/list/downvoted_by=test/1"); $page = $this->get_page("post/list/downvoted_by=test/1");
$this->assert_text("No Images Found"); $this->assertEquals(404, $page->code);
# test errors # test errors
$this->get_page("post/list/upvoted_by=asdfasdf/1"); $page = $this->get_page("post/list/upvoted_by=asdfasdf/1");
$this->assert_text("No Images Found"); $this->assertEquals(404, $page->code);
$this->get_page("post/list/downvoted_by=asdfasdf/1"); $page = $this->get_page("post/list/downvoted_by=asdfasdf/1");
$this->assert_text("No Images Found"); $this->assertEquals(404, $page->code);
$this->get_page("post/list/upvoted_by_id=0/1"); $page = $this->get_page("post/list/upvoted_by_id=0/1");
$this->assert_text("No Images Found"); $this->assertEquals(404, $page->code);
$this->get_page("post/list/downvoted_by_id=0/1"); $page = $this->get_page("post/list/downvoted_by_id=0/1");
$this->assert_text("No Images Found"); $this->assertEquals(404, $page->code);
$this->log_out();
$this->log_in_as_admin();
$this->delete_image($image_id);
$this->log_out();
} }
} }

View File

@ -3,59 +3,35 @@ class PrivMsgTest extends ShimmiePHPUnitTestCase
{ {
public function testPM() public function testPM()
{ {
// Send from admin to user
$this->log_in_as_admin(); $this->log_in_as_admin();
$this->get_page("user/test"); send_event(new SendPMEvent(new PM(
User::by_name($this->admin_name)->id,
"0.0.0.0",
User::by_name($this->user_name)->id,
"message demo to test"
)));
$this->markTestIncomplete(); // Check that admin can see user's messages
$this->get_page("user/{$this->user_name}");
$this->set_field('subject', "message demo to test"); $this->assert_text("message demo to test");
$this->set_field('message', "message contents");
$this->click("Send");
$this->log_out();
// Check that user can see own messages
$this->log_in_as_user(); $this->log_in_as_user();
$this->get_page("user"); $this->get_page("user");
$this->assert_text("message demo to test"); $this->assert_text("message demo to test");
$this->click("message demo to test");
$this->assert_text("message contents");
$this->back();
$this->click("Delete");
$this->assert_no_text("message demo to test");
$this->get_page("pm/read/0"); // FIXME: read PM
$this->assert_text("No such PM"); // $this->get_page("pm/read/0");
// GET doesn't work due to auth token check // $this->assert_text("No such PM");
//$this->get_page("pm/delete/0");
//$this->assert_text("No such PM");
$this->get_page("pm/waffle/0");
$this->assert_text("Invalid action");
$this->log_out(); // FIXME: delete PM
} // send_event();
// $this->get_page("user");
// $this->assert_no_text("message demo to test");
public function testAdminAccess() // FIXME: verify deleted
{ // $this->get_page("pm/read/0");
$this->log_in_as_admin(); // $this->assert_text("No such PM");
$this->get_page("user/test");
$this->markTestIncomplete();
$this->set_field('subject', "message demo to test");
$this->set_field('message', "message contents");
$this->click("Send");
$this->get_page("user/test");
$this->assert_text("message demo to test");
$this->click("message demo to test");
$this->assert_text("message contents");
$this->back();
$this->click("Delete");
# simpletest bug? - redirect(referrer) works in opera, not in
# webtestcase, so we end up at the wrong page...
$this->get_page("user/test");
$this->assert_title("test's Page");
$this->assert_no_text("message demo to test");
$this->log_out();
} }
} }

View File

@ -1,43 +1,11 @@
<?php declare(strict_types=1); <?php declare(strict_types=1);
class PoolsTest extends ShimmiePHPUnitTestCase class PoolsTest extends ShimmiePHPUnitTestCase
{ {
public function testPools() public function testAnon() {
{
$this->get_page('pool/list'); $this->get_page('pool/list');
$this->assert_title("Pools"); $this->assert_title("Pools");
$this->get_page('pool/new'); $this->get_page('pool/new');
$this->assert_title("Error"); $this->assert_title("Error");
$this->log_in_as_user();
$this->get_page('pool/list');
$this->markTestIncomplete();
$this->click("Create Pool");
$this->assert_title("Create Pool");
$this->click("Create");
$this->assert_title("Error");
$this->get_page('pool/new');
$this->assert_title("Create Pool");
$this->set_field("title", "Test Pool Title");
$this->set_field("description", "Test pool description");
$this->click("Create");
$this->assert_title("Pool: Test Pool Title");
$this->log_out();
$this->log_in_as_admin();
$this->get_page('pool/list');
$this->click("Test Pool Title");
$this->assert_title("Pool: Test Pool Title");
$this->click("Delete Pool");
$this->assert_title("Pools");
$this->assert_no_text("Test Pool Title");
$this->log_out();
} }
} }

View File

@ -12,28 +12,28 @@ class RandomImage extends Extension
$search_terms = []; $search_terms = [];
} elseif ($event->count_args() == 2) { } elseif ($event->count_args() == 2) {
$action = $event->get_arg(0); $action = $event->get_arg(0);
$search_terms = explode(' ', $event->get_arg(1)); $search_terms = Tag::explode($event->get_arg(1));
} else { } else {
throw new SCoreException("Error: too many arguments."); throw new SCoreException("Error: too many arguments.");
} }
$image = Image::by_random($search_terms); $image = Image::by_random($search_terms);
if(!$image) {
throw new SCoreException(
"Couldn't find any images randomly",
Tag::implode($search_terms)
);
}
if ($action === "download") { if ($action === "download") {
if (!is_null($image)) { $page->set_mode(PageMode::DATA);
$page->set_mode(PageMode::DATA); $page->set_type($image->get_mime_type());
$page->set_type($image->get_mime_type()); $page->set_data(file_get_contents($image->get_image_filename()));
$page->set_data(file_get_contents($image->get_image_filename()));
}
} elseif ($action === "view") { } elseif ($action === "view") {
if (!is_null($image)) { send_event(new DisplayingImageEvent($image));
send_event(new DisplayingImageEvent($image));
}
} elseif ($action === "widget") { } elseif ($action === "widget") {
if (!is_null($image)) { $page->set_mode(PageMode::DATA);
$page->set_mode(PageMode::DATA); $page->set_type("text/html");
$page->set_type("text/html"); $page->set_data($this->theme->build_thumb_html($image));
$page->set_data($this->theme->build_thumb_html($image));
}
} }
} }
} }

View File

@ -1,5 +1,5 @@
<?php declare(strict_types=1); <?php declare(strict_types=1);
class RandomTest extends ShimmiePHPUnitTestCase class RandomImageTest extends ShimmiePHPUnitTestCase
{ {
public function testRandom() public function testRandom()
{ {
@ -7,53 +7,41 @@ class RandomTest extends ShimmiePHPUnitTestCase
$image_id = $this->post_image("tests/pbx_screenshot.jpg", "test"); $image_id = $this->post_image("tests/pbx_screenshot.jpg", "test");
$this->log_out(); $this->log_out();
$this->get_page("random_image/view"); $page = $this->get_page("random_image/view");
$this->assert_title("Image $image_id: test"); $this->assertEquals("Image $image_id: test", $page->title);
$this->get_page("random_image/view/test"); $page = $this->get_page("random_image/view/test");
$this->assert_title("Image $image_id: test"); $this->assertEquals("Image $image_id: test", $page->title);
$this->get_page("random_image/download"); $page = $this->get_page("random_image/download");
$this->assertNotNull($page->data);
# FIXME: assert($raw == file(blah.jpg)) # FIXME: assert($raw == file(blah.jpg))
} }
public function testPostListBlock() public function testPostListBlock()
{ {
global $config;
$this->log_in_as_admin(); $this->log_in_as_admin();
$this->get_page("setup");
$this->markTestIncomplete();
$this->set_field("_config_show_random_block", true);
$this->click("Save Settings");
$this->log_out();
# enabled, no image = no text # enabled, no image = no text
$this->get_page("post/list"); $config->set_bool("show_random_block", true);
$this->assert_no_text("Random Image"); $page = $this->get_page("post/list");
$this->assertNull($page->find_block("Random Image"));
$this->log_in_as_user();
$image_id = $this->post_image("tests/pbx_screenshot.jpg", "test");
$this->log_out();
# enabled, image = text # enabled, image = text
$this->get_page("post/list"); $image_id = $this->post_image("tests/pbx_screenshot.jpg", "test");
$this->assert_text("Random Image"); $page = $this->get_page("post/list");
$this->assertNotNull($page->find_block("Random Image"));
$this->log_in_as_admin();
$this->get_page("setup");
$this->set_field("_config_show_random_block", true);
$this->click("Save Settings");
# disabled, image = no text # disabled, image = no text
$this->get_page("post/list"); $config->set_bool("show_random_block", false);
$this->assert_text("Random Image"); $page = $this->get_page("post/list");
$this->assertNull($page->find_block("Random Image"));
$this->delete_image($image_id);
$this->log_out();
# disabled, no image = no image # disabled, no image = no image
$this->get_page("post/list"); $this->delete_image($image_id);
$this->assert_no_text("Random Image"); $page = $this->get_page("post/list");
$this->assertNull($page->find_block("Random Image"));
} }
} }

View File

@ -1,4 +1,5 @@
<?php declare(strict_types=1); <?php declare(strict_types=1);
use function MicroHTML\{DIV,A,IMG};
class RandomImageTheme extends Themelet class RandomImageTheme extends Themelet
{ {
@ -9,20 +10,24 @@ class RandomImageTheme extends Themelet
public function build_random_html(Image $image, ?string $query = null): string public function build_random_html(Image $image, ?string $query = null): string
{ {
$i_id = int_escape($image->id);
$h_view_link = make_link("post/view/$i_id", $query);
$h_thumb_link = $image->get_thumb_link();
$h_tip = html_escape($image->get_tooltip());
$tsize = get_thumbnail_size($image->width, $image->height); $tsize = get_thumbnail_size($image->width, $image->height);
return " return (string)DIV(
<center><div> ["style"=>"text-align: center;"],
A(
<a href='$h_view_link' style='position: relative; height: {$tsize[1]}px; width: {$tsize[0]}px;'> [
<img id='thumb_rand_$i_id' title='$h_tip' alt='$h_tip' class='highlighted' style='height: {$tsize[1]}px; width: {$tsize[0]}px;' src='$h_thumb_link'> "href"=>make_link("post/view/{$image->id}", $query),
</a> "style"=>"position: relative; height: {$tsize[1]}px; width: {$tsize[0]}px;"
],
</div></center> IMG([
"; "id"=>"thumb_rand_{$image->id}",
"title"=>$image->get_tooltip(),
"alt"=>$image->get_tooltip(),
"class"=>'highlighted',
"style"=>"height: {$tsize[1]}px; width: {$tsize[0]}px;",
"src"=>$image->get_thumb_link()
])
)
);
} }
} }

View File

@ -1,5 +1,5 @@
<?php declare(strict_types=1); <?php declare(strict_types=1);
class RatingTest extends ShimmiePHPUnitTestCase class RatingsTest extends ShimmiePHPUnitTestCase
{ {
public function testRating() public function testRating()
{ {

View File

@ -1,5 +1,5 @@
<?php declare(strict_types=1); <?php declare(strict_types=1);
class RelationshipTest extends ShimmiePHPUnitTestCase class RelationshipsTest extends ShimmiePHPUnitTestCase
{ {
public function testSetParent() public function testSetParent()
{ {

View File

@ -3,41 +3,36 @@ class ReportImageTest extends ShimmiePHPUnitTestCase
{ {
public function testReportImage() public function testReportImage()
{ {
$this->log_in_as_user(); global $config, $database, $user;
$this->log_in_as_admin();
$image_id = $this->post_image("tests/pbx_screenshot.jpg", "pbx computer screenshot"); $image_id = $this->post_image("tests/pbx_screenshot.jpg", "pbx computer screenshot");
$this->get_page("post/view/$image_id"); $this->get_page("post/view/$image_id");
$this->markTestIncomplete(); // Add image report
send_event(new AddReportedImageEvent(new ImageReport($image_id, $user->id, "report details")));
$this->set_field('reason', "report details"); // Check that the report exists
$this->click("Report"); $config->set_bool("report_image_show_thumbs", true);
$this->log_out();
$this->log_in_as_admin();
$this->get_page("setup");
$this->set_field("_config_report_image_show_thumbs", true);
$this->click("Save Settings");
$this->get_page("image_report/list"); $this->get_page("image_report/list");
$this->assert_title("Reported Images"); $this->assert_title("Reported Images");
$this->assert_text("report details"); $this->assert_text("report details");
$this->get_page("setup"); $config->set_bool("report_image_show_thumbs", false);
$this->set_field("_config_report_image_show_thumbs", false);
$this->click("Save Settings");
$this->get_page("image_report/list"); $this->get_page("image_report/list");
$this->assert_title("Reported Images"); $this->assert_title("Reported Images");
$this->assert_text("report details"); $this->assert_text("report details");
$this->assert_text("$image_id"); $this->assert_text("$image_id");
// Remove report
$report_id = (int)$database->get_one("SELECT id FROM image_reports");
send_event(new RemoveReportedImageEvent($report_id));
// Check that the report is gone
$this->get_page("image_report/list"); $this->get_page("image_report/list");
$this->click("Remove Report");
$this->assert_title("Reported Images"); $this->assert_title("Reported Images");
$this->assert_no_text("report details"); $this->assert_no_text("report details");
$this->delete_image($image_id);
$this->log_out();
# FIXME: test delete image from report screen # FIXME: test delete image from report screen
# FIXME: test that >>123 works # FIXME: test that >>123 works
} }

View File

@ -1,5 +1,5 @@
<?php declare(strict_types=1); <?php declare(strict_types=1);
class ResLimitTest extends ShimmiePHPUnitTestCase class ResolutionLimitTest extends ShimmiePHPUnitTestCase
{ {
public function testResLimitOK() public function testResLimitOK()
{ {

View File

@ -1,26 +1,34 @@
<?php declare(strict_types=1); <?php declare(strict_types=1);
class TagEditTest extends ShimmiePHPUnitTestCase class TagEditTest extends ShimmiePHPUnitTestCase
{ {
public function testTagEdit() public function testValidChange() {
{
$this->log_in_as_user(); $this->log_in_as_user();
$image_id = $this->post_image("tests/pbx_screenshot.jpg", "pbx"); $image_id = $this->post_image("tests/pbx_screenshot.jpg", "pbx");
$image = Image::by_id($image_id);
// Original
$this->get_page("post/view/$image_id"); $this->get_page("post/view/$image_id");
$this->assert_title("Image $image_id: pbx"); $this->assert_title("Image $image_id: pbx");
$this->markTestIncomplete(); // Modified
send_event(new TagSetEvent($image, ["new"]));
$this->set_field("tag_edit__tags", "new"); $this->get_page("post/view/$image_id");
$this->click("Set");
$this->assert_title("Image $image_id: new"); $this->assert_title("Image $image_id: new");
$this->set_field("tag_edit__tags", ""); }
$this->click("Set");
$this->assert_title("Image $image_id: tagme");
$this->log_out();
$this->log_in_as_admin(); public function testInvalidChange()
$this->delete_image($image_id); {
$this->log_out(); $this->log_in_as_user();
$image_id = $this->post_image("tests/pbx_screenshot.jpg", "pbx");
$image = Image::by_id($image_id);
try {
send_event(new TagSetEvent($image, []));
$this->assertTrue(false);
}
catch(SCoreException $e) {
$this->assertEquals("Tried to set zero tags", $e->error);
}
} }
public function testTagEdit_tooLong() public function testTagEdit_tooLong()
@ -35,54 +43,12 @@ class TagEditTest extends ShimmiePHPUnitTestCase
{ {
$this->log_in_as_user(); $this->log_in_as_user();
$image_id = $this->post_image("tests/pbx_screenshot.jpg", "pbx"); $image_id = $this->post_image("tests/pbx_screenshot.jpg", "pbx");
$this->get_page("post/view/$image_id"); $image = Image::by_id($image_id);
$this->assert_title("Image $image_id: pbx");
$this->markTestIncomplete(); send_event(new SourceSetEvent($image, "example.com"));
send_event(new SourceSetEvent($image, "http://example.com"));
$this->set_field("tag_edit__source", "example.com");
$this->click("Set");
$this->click("example.com");
$this->assert_title("Example Domain");
$this->back();
$this->set_field("tag_edit__source", "http://example.com");
$this->click("Set");
$this->click("example.com");
$this->assert_title("Example Domain");
$this->back();
$this->log_out();
$this->log_in_as_admin();
$this->delete_image($image_id);
$this->log_out();
}
/*
* FIXME: Mass Tagger seems to be broken, and this test case always fails.
*/
public function testMassEdit()
{
$this->markTestIncomplete();
$this->log_in_as_admin();
$image_id = $this->post_image("tests/pbx_screenshot.jpg", "pbx");
$this->get_page("post/view/$image_id");
$this->assert_title("Image $image_id: pbx");
$this->get_page("admin");
$this->assert_text("Mass Tag Edit");
$this->set_field("search", "pbx");
$this->set_field("replace", "pox");
$this->click("Replace");
$this->get_page("post/view/$image_id"); $this->get_page("post/view/$image_id");
$this->assert_title("Image $image_id: pox"); $this->assert_text("example.com");
$this->delete_image($image_id);
$this->log_out();
} }
} }

View File

@ -5,19 +5,21 @@ class TagHistoryTest extends ShimmiePHPUnitTestCase
{ {
$this->log_in_as_admin(); $this->log_in_as_admin();
$image_id = $this->post_image("tests/pbx_screenshot.jpg", "pbx"); $image_id = $this->post_image("tests/pbx_screenshot.jpg", "pbx");
$image = Image::by_id($image_id);
// Original
$this->get_page("post/view/$image_id"); $this->get_page("post/view/$image_id");
$this->assert_title("Image $image_id: pbx"); $this->assert_title("Image $image_id: pbx");
$this->markTestIncomplete(); // Modified
send_event(new TagSetEvent($image, ["new"]));
// FIXME // FIXME
$this->set_field("tag_edit__tags", "new"); // $this->click("View Tag History");
$this->click("Set"); // $this->assert_text("new (Set by demo");
$this->assert_title("Image $image_id: new"); // $this->click("Revert To");
$this->click("View Tag History"); // $this->get_page("post/view/$image_id");
$this->assert_text("new (Set by demo"); // $this->assert_title("Image $image_id: pbx");
$this->click("Revert To");
$this->assert_title("Image $image_id: pbx");
$this->get_page("tag_history/all/1"); $this->get_page("tag_history/all/1");
$this->assert_title("Global Tag History"); $this->assert_title("Global Tag History");

View File

@ -1,5 +1,25 @@
<?php declare(strict_types=1); <?php declare(strict_types=1);
class CreateTipEvent extends Event {
public $enable;
public $image;
public $text;
public function __construct(bool $enable, string $image, string $text) {
parent::__construct();
$this->enable = $enable;
$this->image = $image;
$this->text = $text;
}
}
class DeleteTipEvent extends Event {
public $tip_id;
public function __construct(int $tip_id) {
parent::__construct();
$this->tip_id = $tip_id;
}
}
class Tips extends Extension class Tips extends Extension
{ {
/** @var TipsTheme */ /** @var TipsTheme */
@ -42,7 +62,7 @@ class Tips extends Extension
break; break;
case "save": case "save":
if ($user->check_auth_token()) { if ($user->check_auth_token()) {
$this->saveTip(); send_event(new CreateTipEvent(isset($_POST["enable"]), $_POST["image"], $_POST["text"]));
$page->set_mode(PageMode::REDIRECT); $page->set_mode(PageMode::REDIRECT);
$page->set_redirect(make_link("tips/list")); $page->set_redirect(make_link("tips/list"));
} }
@ -57,7 +77,7 @@ class Tips extends Extension
case "delete": case "delete":
// FIXME: HTTP GET CSRF // FIXME: HTTP GET CSRF
$tipID = int_escape($event->get_arg(1)); $tipID = int_escape($event->get_arg(1));
$this->deleteTip($tipID); send_event(new DeleteTipEvent($tipID));
$page->set_mode(PageMode::REDIRECT); $page->set_mode(PageMode::REDIRECT);
$page->set_redirect(make_link("tips/list")); $page->set_redirect(make_link("tips/list"));
break; break;
@ -101,19 +121,13 @@ class Tips extends Extension
$this->theme->manageTips($url, $images); $this->theme->manageTips($url, $images);
} }
private function saveTip() public function onCreateTip(CreateTipEvent $event) {
{
global $database; global $database;
$enable = isset($_POST["enable"]) ? "Y" : "N";
$image = html_escape($_POST["image"]);
$text = $_POST["text"];
$database->execute( $database->execute(
" "
INSERT INTO tips (enable, image, text) INSERT INTO tips (enable, image, text)
VALUES (:enable, :image, :text)", VALUES (:enable, :image, :text)",
["enable"=>$enable, "image"=>$image, "text"=>$text] ["enable"=>$event->enable ? "Y" : "N", "image"=>$event->image, "text"=>$event->text]
); );
} }
@ -162,9 +176,8 @@ class Tips extends Extension
$database->execute("UPDATE tips SET enable = :enable WHERE id = :id", ["enable"=>$enable, "id"=>$tipID]); $database->execute("UPDATE tips SET enable = :enable WHERE id = :id", ["enable"=>$enable, "id"=>$tipID]);
} }
private function deleteTip(int $tipID) public function onDeleteTip(DeleteTipEvent $event) {
{
global $database; global $database;
$database->execute("DELETE FROM tips WHERE id = :id", ["id"=>$tipID]); $database->execute("DELETE FROM tips WHERE id = :id", ["id"=>$event->tip_id]);
} }
} }

View File

@ -4,86 +4,62 @@ class TipsTest extends ShimmiePHPUnitTestCase
public function setUp(): void public function setUp(): void
{ {
parent::setUp(); parent::setUp();
// Delete default tips so we can test from a blank slate
$this->log_in_as_admin(); global $database;
$this->get_page("tips/list"); $database->execute("DELETE FROM tips");
$this->markTestIncomplete();
// get rid of the default data if it's there
if (strpos($this->page_to_text(), "Delete")) {
$this->click("Delete");
}
$this->log_out();
} }
public function testImageless() public function testImageless()
{ {
global $database;
$this->log_in_as_admin(); $this->log_in_as_admin();
$this->get_page("tips/list"); $this->get_page("tips/list");
$this->assert_title("Tips List"); $this->assert_title("Tips List");
$this->markTestIncomplete(); send_event(new CreateTipEvent(true, "", "an imageless tip"));
$this->set_field("image", "");
$this->set_field("text", "an imageless tip");
$this->click("Submit");
$this->assert_title("Tips List");
$this->get_page("post/list"); $this->get_page("post/list");
$this->assert_text("an imageless tip"); $this->assert_text("an imageless tip");
$this->get_page("tips/list"); $tip_id = (int)$database->get_one("SELECT id FROM tips");
$this->click("Delete"); send_event(new DeleteTipEvent($tip_id));
$this->get_page("post/list");
$this->log_out(); $this->assert_no_text("an imageless tip");
} }
public function testImaged() public function testImaged()
{ {
global $database;
$this->log_in_as_admin(); $this->log_in_as_admin();
$this->get_page("tips/list"); $this->get_page("tips/list");
$this->assert_title("Tips List"); $this->assert_title("Tips List");
$this->markTestIncomplete(); send_event(new CreateTipEvent(true, "coins.png", "an imageless tip"));
$this->set_field("image", "coins.png");
$this->set_field("text", "an imaged tip");
$this->click("Submit");
$this->assert_title("Tips List");
$this->get_page("post/list"); $this->get_page("post/list");
$this->assert_text("an imaged tip"); $this->assert_text("an imageless tip");
$this->get_page("tips/list"); $tip_id = (int)$database->get_one("SELECT id FROM tips");
$this->click("Delete"); send_event(new DeleteTipEvent($tip_id));
$this->get_page("post/list");
$this->log_out(); $this->assert_no_text("an imageless tip");
} }
public function testDisabled() public function testDisabled()
{ {
global $database;
$this->log_in_as_admin(); $this->log_in_as_admin();
$this->get_page("tips/list"); $this->get_page("tips/list");
$this->assert_title("Tips List"); $this->assert_title("Tips List");
$this->markTestIncomplete(); send_event(new CreateTipEvent(false, "", "an imageless tip"));
$this->set_field("image", "coins.png");
$this->set_field("text", "an imaged tip");
$this->click("Submit");
$this->click("Yes");
$this->assert_title("Tips List");
$this->get_page("post/list"); $this->get_page("post/list");
$this->assert_no_text("an imaged tip"); $this->assert_no_text("an imageless tip");
$this->get_page("tips/list"); $tip_id = (int)$database->get_one("SELECT id FROM tips");
$this->click("Delete"); send_event(new DeleteTipEvent($tip_id));
$this->get_page("post/list");
$this->log_out(); $this->assert_no_text("an imageless tip");
} }
} }

View File

@ -46,9 +46,9 @@ class TipsTheme extends Themelet
$img = ""; $img = "";
if (!empty($tip['image'])) { if (!empty($tip['image'])) {
$img = "<img src=".$url.$tip['image']." /> "; $img = "<img src=".$url.url_escape($tip['image'])." /> ";
} }
$html = "<div id='tips'>".$img.$tip['text']."</div>"; $html = "<div id='tips'>".$img.html_escape($tip['text'])."</div>";
$page->add_block(new Block(null, $html, "subheading", 10)); $page->add_block(new Block(null, $html, "subheading", 10));
} }

View File

@ -169,7 +169,7 @@ class Upload extends Extension
if (filesize($event->tmpname) > $config->get_int('upload_size')) { if (filesize($event->tmpname) > $config->get_int('upload_size')) {
$size = to_shorthand_int(filesize($event->tmpname)); $size = to_shorthand_int(filesize($event->tmpname));
$limit = to_shorthand_int($config->get_int('upload_size')); $limit = to_shorthand_int($config->get_int('upload_size'));
throw new UploadException("File too large ($size &gt; $limit)"); throw new UploadException("File too large ($size > $limit)");
} }
} }

View File

@ -37,14 +37,15 @@ class UploadTest extends ShimmiePHPUnitTestCase
public function testRejectHuge() public function testRejectHuge()
{ {
$this->markTestIncomplete();
// FIXME: huge.dat is rejected for other reasons; manual testing shows that this works // FIXME: huge.dat is rejected for other reasons; manual testing shows that this works
file_put_contents("huge.dat", file_get_contents("tests/pbx_screenshot.jpg") . str_repeat("U", 1024*1024*3)); file_put_contents("data/huge.jpg", file_get_contents("tests/pbx_screenshot.jpg") . str_repeat("U", 1024*1024*3));
$this->post_image("index.php", "test"); try {
$this->assert_response(200); $this->post_image("data/huge.jpg", "test");
$this->assert_title("Upload Status"); $this->assertTrue(false, "Uploading huge.jpg didn't fail...");
$this->assert_text("File too large"); }
unlink("huge.dat"); catch (UploadException $e) {
$this->assertEquals("File too large (3.0MB > 1.0MB)", $e->error);
}
unlink("data/huge.jpg");
} }
} }

View File

@ -31,7 +31,7 @@ class UploadTheme extends Themelet
</form> </form>
<small>(Max file size is $max_kb)</small> <small>(Max file size is $max_kb)</small>
"; ";
$page->set_title("Upload"); $page->set_title("Upload");
$page->set_heading("Upload"); $page->set_heading("Upload");
$page->add_block(new NavBlock()); $page->add_block(new NavBlock());
@ -95,25 +95,25 @@ class UploadTheme extends Themelet
// Uploader 2.0! // Uploader 2.0!
$upload_list = ""; $upload_list = "";
$upload_count = $config->get_int('upload_count'); $upload_count = $config->get_int('upload_count');
for ($i=0; $i<$upload_count; $i++) { for ($i=0; $i<$upload_count; $i++) {
$a = $i+1; $a = $i+1;
$s = $i-1; $s = $i-1;
if ($i != 0) { if ($i != 0) {
$upload_list .="<tr id='row$i' style='display:none'>"; $upload_list .="<tr id='row$i' style='display:none'>";
} else { } else {
$upload_list .= "<tr id='row$i'>"; $upload_list .= "<tr id='row$i'>";
} }
$upload_list .= "<td width='15'>"; $upload_list .= "<td width='15'>";
if ($i == 0) { if ($i == 0) {
$js = 'javascript:$(function() { $js = 'javascript:$(function() {
$("#row'.$a.'").show(); $("#row'.$a.'").show();
$("#hide'.$i.'").hide(); $("#hide'.$i.'").hide();
$("#hide'.$a.'").show();});'; $("#hide'.$a.'").show();});';
$upload_list .= " $upload_list .= "
<div id='hide$i'> <div id='hide$i'>
<img id='wrapper' src='ext/upload/minus.png' /> <img id='wrapper' src='ext/upload/minus.png' />
@ -128,12 +128,12 @@ class UploadTheme extends Themelet
$("#data'.$i.'").val(""); $("#data'.$i.'").val("");
$("#url'.$i.'").val(""); $("#url'.$i.'").val("");
});'; });';
$upload_list .=" $upload_list .="
<div id='hide$i'> <div id='hide$i'>
<a href='#' onclick='$js'><img src='ext/upload/minus.png' /></a> <a href='#' onclick='$js'><img src='ext/upload/minus.png' /></a>
"; ";
if ($a == $upload_count) { if ($a == $upload_count) {
$upload_list .="<img id='wrapper' src='ext/upload/plus.png' />"; $upload_list .="<img id='wrapper' src='ext/upload/plus.png' />";
} else { } else {
@ -141,7 +141,7 @@ class UploadTheme extends Themelet
$("#row'.$a.'").show(); $("#row'.$a.'").show();
$("#hide'.$i.'").hide(); $("#hide'.$i.'").hide();
$("#hide'.$a.'").show(); });'; $("#hide'.$a.'").show(); });';
$upload_list .= $upload_list .=
"<a href='#' onclick='$js1'>". "<a href='#' onclick='$js1'>".
"<img src='ext/upload/plus.png' /></a>"; "<img src='ext/upload/plus.png' /></a>";
@ -149,7 +149,7 @@ class UploadTheme extends Themelet
$upload_list .= "</div>"; $upload_list .= "</div>";
} }
$upload_list .= "</td>"; $upload_list .= "</td>";
$js2 = 'javascript:$(function() { $js2 = 'javascript:$(function() {
$("#url'.$i.'").hide(); $("#url'.$i.'").hide();
$("#url'.$i.'").val(""); $("#url'.$i.'").val("");
@ -157,13 +157,13 @@ class UploadTheme extends Themelet
$upload_list .= " $upload_list .= "
<form><td width='60'><input id='radio_button_a$i' type='radio' name='method' value='file' checked='checked' onclick='$js2' /> File<br>"; <form><td width='60'><input id='radio_button_a$i' type='radio' name='method' value='file' checked='checked' onclick='$js2' /> File<br>";
if ($tl_enabled) { if ($tl_enabled) {
$js = 'javascript:$(function() { $js = 'javascript:$(function() {
$("#data'.$i.'").hide(); $("#data'.$i.'").hide();
$("#data'.$i.'").val(""); $("#data'.$i.'").val("");
$("#url'.$i.'").show(); });'; $("#url'.$i.'").show(); });';
$upload_list .= $upload_list .=
"<input id='radio_button_b$i' type='radio' name='method' value='url' onclick='$js' /> URL</ br></td></form> "<input id='radio_button_b$i' type='radio' name='method' value='url' onclick='$js' /> URL</ br></td></form>
<td> <td>
@ -175,7 +175,7 @@ class UploadTheme extends Themelet
<td width='250'><input id='data$i' name='data$i' class='wid' type='file'></td> <td width='250'><input id='data$i' name='data$i' class='wid' type='file'></td>
"; ";
} }
$upload_list .= " $upload_list .= "
</tr> </tr>
"; ";
@ -273,10 +273,10 @@ class UploadTheme extends Themelet
$max_size = $config->get_int('upload_size'); $max_size = $config->get_int('upload_size');
$max_kb = to_shorthand_int($max_size); $max_kb = to_shorthand_int($max_size);
$image = Image::by_id($image_id); $image = Image::by_id($image_id);
$thumbnail = $this->build_thumb_html($image); $thumbnail = $this->build_thumb_html($image);
$html = " $html = "
<p>Replacing Image ID ".$image_id."<br>Please note: You will have to refresh the image page, or empty your browser cache.</p>" <p>Replacing Image ID ".$image_id."<br>Please note: You will have to refresh the image page, or empty your browser cache.</p>"
.$thumbnail."<br>" .$thumbnail."<br>"
@ -311,7 +311,7 @@ class UploadTheme extends Themelet
public function display_upload_error(Page $page, string $title, string $message) public function display_upload_error(Page $page, string $title, string $message)
{ {
$page->add_block(new Block($title, $message)); $page->add_block(new Block($title, html_escape($message)));
} }
protected function build_upload_block(): string protected function build_upload_block(): string
@ -320,7 +320,7 @@ class UploadTheme extends Themelet
$upload_list = ""; $upload_list = "";
$upload_count = $config->get_int('upload_count'); $upload_count = $config->get_int('upload_count');
for ($i=0; $i<$upload_count; $i++) { for ($i=0; $i<$upload_count; $i++) {
if ($i == 0) { if ($i == 0) {
$style = ""; $style = "";

View File

@ -14,8 +14,6 @@ class DisplayingImageEvent extends Event
/** @var Image */ /** @var Image */
public $image; public $image;
public $title;
public function __construct(Image $image) public function __construct(Image $image)
{ {
parent::__construct(); parent::__construct();
@ -26,9 +24,4 @@ class DisplayingImageEvent extends Event
{ {
return $this->image; return $this->image;
} }
public function set_title(String $title)
{
$this->title = $title;
}
} }

View File

@ -60,9 +60,7 @@ class ViewImage extends Extension
$image = Image::by_id($image_id); $image = Image::by_id($image_id);
if (!is_null($image)) { if (!is_null($image)) {
$die = new DisplayingImageEvent($image); send_event(new DisplayingImageEvent($image));
send_event($die);
$page->set_title(html_escape($die->title));
$iabbe = new ImageAdminBlockBuildingEvent($image, $user); $iabbe = new ImageAdminBlockBuildingEvent($image, $user);
send_event($iabbe); send_event($iabbe);
ksort($iabbe->parts); ksort($iabbe->parts);
@ -91,9 +89,6 @@ class ViewImage extends Extension
send_event($iibbe); send_event($iibbe);
ksort($iibbe->parts); ksort($iibbe->parts);
$this->theme->display_meta_headers($event->get_image()); $this->theme->display_meta_headers($event->get_image());
$event->title = "Image {$event->get_image()->id}: ".$event->get_image()->get_tag_list();
$this->theme->display_page($event->get_image(), $iibbe->parts); $this->theme->display_page($event->get_image(), $iibbe->parts);
} }
} }

View File

@ -1,5 +1,5 @@
<?php declare(strict_types=1); <?php declare(strict_types=1);
class ViewTest extends ShimmiePHPUnitTestCase class ViewImageTest extends ShimmiePHPUnitTestCase
{ {
public function setUp(): void public function setUp(): void
{ {
@ -21,21 +21,32 @@ class ViewTest extends ShimmiePHPUnitTestCase
public function testPrevNext() public function testPrevNext()
{ {
$this->markTestIncomplete();
$this->log_in_as_user(); $this->log_in_as_user();
$image_id_1 = $this->post_image("tests/pbx_screenshot.jpg", "test"); $image_id_1 = $this->post_image("tests/pbx_screenshot.jpg", "test");
$image_id_2 = $this->post_image("tests/bedroom_workshop.jpg", "test2"); $image_id_2 = $this->post_image("tests/bedroom_workshop.jpg", "test2");
$image_id_3 = $this->post_image("tests/favicon.png", "test"); $image_id_3 = $this->post_image("tests/favicon.png", "test");
$this->click("Prev"); // Front image: no next, has prev
$this->assert_title("Image $image_id_2: test2"); $page = $this->get_page("post/next/$image_id_1");
$this->assertEquals(404, $page->code);
$page = $this->get_page("post/prev/$image_id_1");
$this->assertEquals("/post/view/$image_id_2", $page->redirect);
$this->click("Next"); // When searching, we skip the middle
$this->assert_title("Image $image_id_1: test"); $page = $this->get_page("post/prev/$image_id_1?search=test");
$this->assertEquals("/post/view/$image_id_2", $page->redirect);
$this->click("Next"); // Middle image: has next and prev
$this->assert_title("Image not found"); $page = $this->get_page("post/next/$image_id_2");
$this->assertEquals("/post/view/$image_id_1", $page->redirect);
$page = $this->get_page("post/prev/$image_id_2");
$this->assertEquals("/post/view/$image_id_3", $page->redirect);
// Last image has next, no prev
$page = $this->get_page("post/next/$image_id_3");
$this->assertEquals("/post/view/$image_id_2", $page->redirect);
$page = $this->get_page("post/prev/$image_id_3");
$this->assertEquals(404, $page->code);
} }
public function testView404() public function testView404()
@ -52,20 +63,4 @@ class ViewTest extends ShimmiePHPUnitTestCase
$this->get_page('post/view/-1'); $this->get_page('post/view/-1');
$this->assert_title('Image not found'); $this->assert_title('Image not found');
} }
public function testNextSearchResult()
{
$this->markTestIncomplete();
$this->log_in_as_user();
$image_id_1 = $this->post_image("tests/pbx_screenshot.jpg", "test");
$image_id_2 = $this->post_image("tests/bedroom_workshop.jpg", "test2");
$image_id_3 = $this->post_image("tests/favicon.png", "test");
// FIXME: this assumes Nice URLs.
# note: skips image #2
$this->get_page("post/view/$image_id_1?search=test"); // FIXME: assumes niceurls
$this->click("Prev");
$this->assert_title("Image $image_id_3: test");
}
} }

View File

@ -20,6 +20,7 @@ class ViewImageTheme extends Themelet
public function display_page(Image $image, $editor_parts) public function display_page(Image $image, $editor_parts)
{ {
global $page; global $page;
$page->set_title("Image {$image->id}: ".$image->get_tag_list());
$page->set_heading(html_escape($image->get_tag_list())); $page->set_heading(html_escape($image->get_tag_list()));
$page->add_block(new Block("Navigation", $this->build_navigation($image), "left", 0)); $page->add_block(new Block("Navigation", $this->build_navigation($image), "left", 0));
$page->add_block(new Block(null, $this->build_info($image, $editor_parts), "main", 20)); $page->add_block(new Block(null, $this->build_info($image, $editor_parts), "main", 20));

View File

@ -15,6 +15,26 @@ class WikiUpdateEvent extends Event
} }
} }
class WikiDeleteRevisionEvent extends Event {
public $title;
public $revision;
public function __construct($title, $revision) {
parent::__construct();
$this->title = $title;
$this->revision = $revision;
}
}
class WikiDeletePageEvent extends Event {
public $title;
public function __construct($title) {
parent::__construct();
$this->title = $title;
}
}
class WikiUpdateException extends SCoreException class WikiUpdateException extends SCoreException
{ {
} }
@ -50,12 +70,12 @@ class WikiPage
//assert(!empty($row)); //assert(!empty($row));
if (!is_null($row)) { if (!is_null($row)) {
$this->id = $row['id']; $this->id = (int)$row['id'];
$this->owner_id = $row['owner_id']; $this->owner_id = (int)$row['owner_id'];
$this->owner_ip = $row['owner_ip']; $this->owner_ip = $row['owner_ip'];
$this->date = $row['date']; $this->date = $row['date'];
$this->title = $row['title']; $this->title = $row['title'];
$this->revision = $row['revision']; $this->revision = (int)$row['revision'];
$this->locked = ($row['locked'] == 'Y'); $this->locked = ($row['locked'] == 'Y');
$this->body = $row['body']; $this->body = $row['body'];
} }
@ -149,22 +169,14 @@ class Wiki extends Extension
} }
} elseif ($event->page_matches("wiki_admin/delete_revision")) { } elseif ($event->page_matches("wiki_admin/delete_revision")) {
if ($user->can(Permissions::WIKI_ADMIN)) { if ($user->can(Permissions::WIKI_ADMIN)) {
global $database; send_event(new WikiDeleteRevisionEvent($_POST["title"], $_POST["revision"]));
$database->Execute(
"DELETE FROM wiki_pages WHERE title=:title AND revision=:rev",
["title"=>$_POST["title"], "rev"=>$_POST["revision"]]
);
$u_title = url_escape($_POST["title"]); $u_title = url_escape($_POST["title"]);
$page->set_mode(PageMode::REDIRECT); $page->set_mode(PageMode::REDIRECT);
$page->set_redirect(make_link("wiki/$u_title")); $page->set_redirect(make_link("wiki/$u_title"));
} }
} elseif ($event->page_matches("wiki_admin/delete_all")) { } elseif ($event->page_matches("wiki_admin/delete_all")) {
if ($user->can(Permissions::WIKI_ADMIN)) { if ($user->can(Permissions::WIKI_ADMIN)) {
global $database; send_event(new WikiDeletePageEvent($_POST["title"]));
$database->Execute(
"DELETE FROM wiki_pages WHERE title=:title",
["title"=>$_POST["title"]]
);
$u_title = url_escape($_POST["title"]); $u_title = url_escape($_POST["title"]);
$page->set_mode(PageMode::REDIRECT); $page->set_mode(PageMode::REDIRECT);
$page->set_redirect(make_link("wiki/$u_title")); $page->set_redirect(make_link("wiki/$u_title"));
@ -204,6 +216,22 @@ class Wiki extends Extension
} }
} }
public function onWikiDeleteRevision(WikiDeleteRevisionEvent $event) {
global $database;
$database->Execute(
"DELETE FROM wiki_pages WHERE title=:title AND revision=:rev",
["title"=>$event->title, "rev"=>$event->revision]
);
}
public function onWikiDeletePage(WikiDeletePageEvent $event) {
global $database;
$database->Execute(
"DELETE FROM wiki_pages WHERE title=:title",
["title" => $event->title]
);
}
/** /**
* See if the given user is allowed to edit the given page. * See if the given user is allowed to edit the given page.
*/ */
@ -227,7 +255,7 @@ class Wiki extends Extension
return false; return false;
} }
private function get_page(string $title, int $revision=-1): WikiPage public static function get_page(string $title, int $revision=-1): WikiPage
{ {
global $database; global $database;
// first try and get the actual page // first try and get the actual page

View File

@ -10,8 +10,6 @@ class WikiTest extends ShimmiePHPUnitTestCase
public function testAccess() public function testAccess()
{ {
$this->markTestIncomplete();
global $config; global $config;
foreach (["anon", "user", "admin"] as $user) { foreach (["anon", "user", "admin"] as $user) {
foreach ([false, true] as $allowed) { foreach ([false, true] as $allowed) {
@ -32,12 +30,16 @@ class WikiTest extends ShimmiePHPUnitTestCase
$this->assert_text("This is a default page"); $this->assert_text("This is a default page");
if ($allowed || $user == "admin") { if ($allowed || $user == "admin") {
$this->get_page("wiki/test", ['edit'=>'on']); $this->post_page("wiki_admin/edit", ["title"=>"test"]);
$this->assert_text("Editor"); $this->assert_text("Editor");
} else { }
$this->get_page("wiki/test", ['edit'=>'on']); /*
// Everyone can see the editor
else {
$this->post_page("wiki_admin/edit", ["title"=>"test"]);
$this->assert_no_text("Editor"); $this->assert_no_text("Editor");
} }
*/
if ($user == "user" || $user == "admin") { if ($user == "user" || $user == "admin") {
$this->log_out(); $this->log_out();
@ -46,85 +48,68 @@ class WikiTest extends ShimmiePHPUnitTestCase
} }
} }
public function testLock()
{
$this->markTestIncomplete();
global $config;
$config->set_bool("wiki_edit_anon", true);
$config->set_bool("wiki_edit_user", false);
$this->log_in_as_admin();
$this->get_page("wiki/test_locked");
$this->assert_title("test_locked");
$this->assert_text("This is a default page");
$this->click("Edit");
$this->set_field("body", "test_locked content");
$this->set_field("lock", true);
$this->click("Save");
$this->log_out();
$this->log_in_as_user();
$this->get_page("wiki/test_locked");
$this->assert_title("test_locked");
$this->assert_text("test_locked content");
$this->assert_no_text("Edit");
$this->log_out();
$this->get_page("wiki/test_locked");
$this->assert_title("test_locked");
$this->assert_text("test_locked content");
$this->assert_no_text("Edit");
$this->log_in_as_admin();
$this->get_page("wiki/test_locked");
$this->click("Delete All");
$this->log_out();
}
public function testDefault() public function testDefault()
{ {
$this->markTestIncomplete(); global $user;
$this->log_in_as_admin(); $this->log_in_as_admin();
// Check default page is default
$this->get_page("wiki/wiki:default"); $this->get_page("wiki/wiki:default");
$this->assert_title("wiki:default"); $this->assert_title("wiki:default");
$this->assert_text("This is a default page"); $this->assert_text("This is a default page");
$this->click("Edit");
$this->set_field("body", "Empty page! Fill it!");
$this->click("Save");
// Customise default page
$wikipage = Wiki::get_page("wiki:default");
$wikipage->revision = 1;
$wikipage->body = "New Default Template";
send_event(new WikiUpdateEvent($user, $wikipage));
// Check that some random page is using the new default
$this->get_page("wiki/something"); $this->get_page("wiki/something");
$this->assert_text("Empty page! Fill it!"); $this->assert_text("New Default Template");
// Delete the custom default
send_event(new WikiDeletePageEvent("wiki:default"));
// Check that the default page is back to normal
$this->get_page("wiki/wiki:default"); $this->get_page("wiki/wiki:default");
$this->click("Delete All"); $this->assert_title("wiki:default");
$this->log_out(); $this->assert_text("This is a default page");
} }
public function testRevisions() public function testRevisions()
{ {
$this->markTestIncomplete(); global $user;
$this->log_in_as_admin(); $this->log_in_as_admin();
$this->get_page("wiki/test"); $this->get_page("wiki/test");
$this->assert_title("test"); $this->assert_title("test");
$this->assert_text("This is a default page"); $this->assert_text("This is a default page");
$this->click("Edit");
$this->set_field("body", "Mooooo 1"); $wikipage = Wiki::get_page("test");
$this->click("Save"); $wikipage->revision = $wikipage->revision + 1;
$wikipage->body = "Mooooo 1";
send_event(new WikiUpdateEvent($user, $wikipage));
$this->get_page("wiki/test");
$this->assert_text("Mooooo 1"); $this->assert_text("Mooooo 1");
$this->assert_text("Revision 1"); $this->assert_text("Revision 1");
$this->click("Edit");
$this->set_field("body", "Mooooo 2"); $wikipage = Wiki::get_page("test");
$this->click("Save"); $wikipage->revision = $wikipage->revision + 1;
$wikipage->body = "Mooooo 2";
send_event(new WikiUpdateEvent($user, $wikipage));
$this->get_page("wiki/test");
$this->assert_text("Mooooo 2"); $this->assert_text("Mooooo 2");
$this->assert_text("Revision 2"); $this->assert_text("Revision 2");
$this->click("Delete This Version");
send_event(new WikiDeleteRevisionEvent("test", 2));
$this->get_page("wiki/test");
$this->assert_text("Mooooo 1"); $this->assert_text("Mooooo 1");
$this->assert_text("Revision 1"); $this->assert_text("Revision 1");
$this->click("Delete All");
$this->log_out(); send_event(new WikiDeletePageEvent("test"));
$this->get_page("wiki/test");
$this->assert_title("test");
$this->assert_text("This is a default page");
} }
} }

View File

@ -10,7 +10,7 @@ class WordFilterTest extends ShimmiePHPUnitTestCase
public function _doThings($in, $out) public function _doThings($in, $out)
{ {
global $user; global $user, $_tracer;
$this->log_in_as_user(); $this->log_in_as_user();
$image_id = $this->post_image("tests/pbx_screenshot.jpg", "pbx computer screenshot"); $image_id = $this->post_image("tests/pbx_screenshot.jpg", "pbx computer screenshot");
send_event(new CommentPostingEvent($image_id, $user, $in)); send_event(new CommentPostingEvent($image_id, $user, $in));

View File

@ -23,36 +23,50 @@ require_all(zglob("ext/{".Extension::get_enabled_extensions_as_string()."}/main.
_load_theme_files(); _load_theme_files();
$page = new Page(); $page = new Page();
_load_event_listeners(); _load_event_listeners();
$config->set_string("thumb_engine", "gd"); # GD has less overhead per-call
send_event(new DatabaseUpgradeEvent()); send_event(new DatabaseUpgradeEvent());
send_event(new InitExtEvent()); send_event(new InitExtEvent());
abstract class ShimmiePHPUnitTestCase extends \PHPUnit\Framework\TestCase abstract class ShimmiePHPUnitTestCase extends \PHPUnit\Framework\TestCase
{ {
private $images = []; protected $anon_name = "anonymous";
protected $admin_name = "demo";
protected $user_name = "test";
public function setUp(): void public function setUp(): void
{ {
global $_tracer, $tracer_enabled;
$tracer_enabled = true;
$_tracer->begin("setUp");
$class = str_replace("Test", "", get_class($this)); $class = str_replace("Test", "", get_class($this));
if (!class_exists($class)) { if (!ExtensionInfo::get_for_extension_class($class)->is_supported()) {
$this->markTestSkipped("$class not loaded");
} elseif (!ExtensionInfo::get_for_extension_class($class)->is_supported()) {
$this->markTestSkipped("$class not supported with this database"); $this->markTestSkipped("$class not supported with this database");
} }
$this->create_user("demo"); $this->create_user($this->admin_name);
$this->create_user("test"); $this->create_user($this->user_name);
// things to do after bootstrap and before request // things to do after bootstrap and before request
// log in as anon // log in as anon
$this->log_out(); $this->log_out();
$_tracer->end();
$_tracer->begin($this->getName());
} }
public function tearDown(): void public function tearDown(): void
{ {
foreach ($this->images as $image_id) { global $_tracer;
$this->delete_image($image_id); $_tracer->end();
$_tracer->begin("tearDown");
global $database, $_tracer;
foreach ($database->get_col("SELECT id FROM images") as $image_id) {
send_event(new ImageDeletionEvent(Image::by_id($image_id)));
} }
$_tracer->end();
$_tracer->clear();
$_tracer->flush("tests/trace.json");
} }
protected function create_user(string $name) protected function create_user(string $name)
@ -73,11 +87,12 @@ abstract class ShimmiePHPUnitTestCase extends \PHPUnit\Framework\TestCase
} }
$_GET = $args; $_GET = $args;
$_POST = []; $_POST = [];
$page = class_exists("CustomPage") ? new CustomPage() : new Page(); $page = new Page();
send_event(new PageRequestEvent($page_name)); send_event(new PageRequestEvent($page_name));
if ($page->mode == PageMode::REDIRECT) { if ($page->mode == PageMode::REDIRECT) {
$page->code = 302; $page->code = 302;
} }
return $page;
} }
protected function post_page($page_name, $args=null) protected function post_page($page_name, $args=null)
@ -92,7 +107,7 @@ abstract class ShimmiePHPUnitTestCase extends \PHPUnit\Framework\TestCase
} }
$_GET = []; $_GET = [];
$_POST = $args; $_POST = $args;
$page = class_exists("CustomPage") ? new CustomPage() : new Page(); $page = new Page();
send_event(new PageRequestEvent($page_name)); send_event(new PageRequestEvent($page_name));
if ($page->mode == PageMode::REDIRECT) { if ($page->mode == PageMode::REDIRECT) {
$page->code = 302; $page->code = 302;
@ -127,14 +142,22 @@ abstract class ShimmiePHPUnitTestCase extends \PHPUnit\Framework\TestCase
protected function page_to_text(string $section=null) protected function page_to_text(string $section=null)
{ {
global $page; global $page;
$text = $page->title . "\n"; if($page->mode == PageMode::PAGE) {
foreach ($page->blocks as $block) { $text = $page->title . "\n";
if (is_null($section) || $section == $block->section) { foreach ($page->blocks as $block) {
$text .= $block->header . "\n"; if (is_null($section) || $section == $block->section) {
$text .= $block->body . "\n\n"; $text .= $block->header . "\n";
$text .= $block->body . "\n\n";
}
} }
return $text;
}
elseif($page->mode == PageMode::DATA) {
return $page->data;
}
else {
$this->assertTrue(false, "Page mode is not PAGE or DATA");
} }
return $text;
} }
protected function assert_text(string $text, string $section=null) protected function assert_text(string $text, string $section=null)
@ -162,23 +185,17 @@ abstract class ShimmiePHPUnitTestCase extends \PHPUnit\Framework\TestCase
// user things // user things
protected function log_in_as_admin() protected function log_in_as_admin()
{ {
global $user; send_event(new UserLoginEvent(User::by_name($this->admin_name)));
$user = User::by_name('demo');
$this->assertNotNull($user);
send_event(new UserLoginEvent($user));
} }
protected function log_in_as_user() protected function log_in_as_user()
{ {
global $user; send_event(new UserLoginEvent(User::by_name($this->user_name)));
$user = User::by_name('test');
$this->assertNotNull($user);
send_event(new UserLoginEvent($user));
} }
protected function log_out() protected function log_out()
{ {
global $user, $config; global $config;
$user = User::by_id($config->get_int("anon_id", 0)); $user = User::by_id($config->get_int("anon_id", 0));
$this->assertNotNull($user); $this->assertNotNull($user);
send_event(new UserLoginEvent($user)); send_event(new UserLoginEvent($user));
@ -194,7 +211,6 @@ abstract class ShimmiePHPUnitTestCase extends \PHPUnit\Framework\TestCase
"source" => null, "source" => null,
]); ]);
send_event($dae); send_event($dae);
$this->images[] = $dae->image_id;
return $dae->image_id; return $dae->image_id;
} }

View File

@ -10,10 +10,10 @@ define("COVERAGE", false);
define("CACHE_HTTP", false); define("CACHE_HTTP", false);
define("COOKIE_PREFIX", 'shm'); define("COOKIE_PREFIX", 'shm');
define("SPEED_HAX", false); define("SPEED_HAX", false);
define("NICE_URLS", false); define("NICE_URLS", true);
define("WH_SPLITS", 1); define("WH_SPLITS", 1);
define("VERSION", 'unit-tests'); define("VERSION", 'unit-tests');
define("BASE_URL", null); define("BASE_URL", "/");
define("TRACE_FILE", null); define("TRACE_FILE", null);
define("TRACE_THRESHOLD", 0.0); define("TRACE_THRESHOLD", 0.0);
define("TIMEZONE", 'UTC'); define("TIMEZONE", 'UTC');