From 1211af09ccaebd9709ac222f285f23103db1b7fc Mon Sep 17 00:00:00 2001 From: Guillermo Dev Date: Sat, 13 Oct 2018 18:00:51 +0200 Subject: [PATCH] created mocks for testing --- .README.md.swp | Bin 0 -> 12288 bytes .gitignore | 1 + composer.json | 4 +- composer.lock | 43 ++++++- config/configuration.local.php | 3 +- flow.txt | 68 ++++++++++ src/Webservice/.WebService.php.swp | Bin 0 -> 12288 bytes .../Exception/.UsageException.php.swp | Bin 0 -> 12288 bytes src/Webservice/Formatter/Formatter.php | 17 ++- src/Webservice/Formatter/Html.php | 3 +- src/Webservice/Help.php | 1 - src/Webservice/Renderer.php | 14 +- src/Webservice/WebService.php | 17 ++- templates/func_help.html | 14 ++ templates/layout.html | 40 ++++++ templates/panel.html | 11 ++ templates/param_help.html | 5 + templates/return_help.html | 2 + .../.MockWebserviceSubclass.php.swp | Bin 0 -> 12288 bytes tests/Webservice/.WebserviceTest.php.swp | Bin 0 -> 16384 bytes tests/Webservice/Formatter/FormatterTest.php | 79 +----------- tests/Webservice/Formatter/JsonTest.php | 35 +++-- tests/Webservice/MockRenderer.php | 16 +++ tests/Webservice/MockWebserviceSubclass.php | 10 ++ tests/Webservice/RendererTest.php | 26 ++-- tests/Webservice/WebserviceTest.php | 121 +++++++++++++++++- 26 files changed, 412 insertions(+), 118 deletions(-) create mode 100644 .README.md.swp create mode 100644 flow.txt create mode 100644 src/Webservice/.WebService.php.swp create mode 100644 src/Webservice/Exception/.UsageException.php.swp create mode 100644 templates/func_help.html create mode 100644 templates/layout.html create mode 100644 templates/panel.html create mode 100644 templates/param_help.html create mode 100644 templates/return_help.html create mode 100644 tests/Webservice/.MockWebserviceSubclass.php.swp create mode 100644 tests/Webservice/.WebserviceTest.php.swp create mode 100644 tests/Webservice/MockRenderer.php create mode 100644 tests/Webservice/MockWebserviceSubclass.php diff --git a/.README.md.swp b/.README.md.swp new file mode 100644 index 0000000000000000000000000000000000000000..9817a7faedb6f52a443711f32ae252e8df9646f1 GIT binary patch literal 12288 zcmeI&O=}b}7zglF@aPNm3q0D3LY?fcC|VHNcB^ak9Rl=OH{{4(Ub8cqT-AT}gif=hSF2zjoBUMHf4t1sY?)G@Hvt2au zjD0W#0SKH&;0n7p8V_F*vkBgT00bZa0SG_<0uX=z1TLsR@+<5^j{VXy z{>#gD<*#WvwFxB(#nFw<;$U<#77WYgJAcY3|fUC4UEE<|G!O?Qc$Z-`rlt zQR>oYmm_}Hs_1M!T2a;f4wdtMw@GMyK13IaPKtz;ROZ!-BfgmS17j 'solr/', 'result_count' => 10, ), + 'renderer' => array('class' => '\BSR\Webservice\MockRenderer'), 'log' => array( - 'file' => '/var/www/webservice/logs/log.txt', + 'file' => realpath(dirname(__FILE__) . '/..') . '/log/log.txt', 'format' => '%ip% - [%date%] - %status% %error% - %time% - %func%', // The greater the verbosity, the more is displayed // 0 : no log at all diff --git a/flow.txt b/flow.txt new file mode 100644 index 0000000..034ff3d --- /dev/null +++ b/flow.txt @@ -0,0 +1,68 @@ +index.php +web = new NetBiblio() + parent::__construct(self::$version) +web->Run() <=> parent->Run() +| Logger::start(version) // initialize static log array +| new Renderer::__construct() +| |---ob_start() +| $data = [] +| try { +| $result = this->Call() //1) start session, +| | //2) call webservice method and params passed in +| | // http request after doing a few checks +| | //3) log the request +| | session_save_path(Configuration::get(session.save_path)) +| | session_start() +| | $paras = GET or POST +| | if empty(params) throw NoArguments +| | if !isset(params["func"]) throw MissingMethod +| | this->func = params["func"] +| | unset(params["func"]) +| | Logger::info([ +| | "func" => this->func . '(' . implode(',' params) . ')' +| | ]) // add func -> string to Logger::data +| | if !is_callable([this, this->func]) throw BadMethod +| | // descriptive wrapper for NetBiblio method +| | $rm = new \ReflectionMethod(this, this->func) +| | // check whether provided params match required +| | //TODO here is where the magic happens !!!!!!!!!!!!!!!!!!!! +| |---return call_user_func_array([this, this->func], params) +| $data['result'][this->func] = $result +| } catch (WebException $e) { +| $data['error'] = ['code' => $e->getCode(), ... ] +| $this->status = 400 +| Logger::info($e->getName(), 'error') // add to log +| } catch (\Exception $e) { +| $data['failure'] = ['code' => $e->getCode(), 'reason' ...] +| Logger::info($e->getMessage, 'error') +| } +| Logger::stop(['status' => $this->status]) +| $renderer->render($this->status, $data) // default status:200 +| | header(sprintf( +| | 'HTTP/1.0 %s %s', +| | $status, self::$statusMessages[$status] +| | )) +| | header('Access-Control-Allow-Origin: *') +| | ob_clean() +| | flush() +| | $formatter = Formatter::getFormatter(); +| | | self::loadFormatters() // call init on all formatters in dir +| | | | foreach($files as f) { +| | | | //infer class name from file name +| | | | //and if it is not this current class +| | | | //call init on the class +| | | | //Ex: +| | | | Json::init() +| | | | | self::registerFormats([ //self parent +| | | | | 'application/json', +| | | | | 'application/x-json', +| | | | | ]); +| | | | | | forach($formats as $f) { // self +| | | | | | self::$formats[$f] = get_called_class() +| | | | |---|---} +| | | | } +| | | $format = self::getFormatFromHeader(); +| | | |---return 'BSR\Lib\Formatter\Json'; +| | |---return new $format() +| | $formatter->render($data) +|---|---|---echo json_encode($data) diff --git a/src/Webservice/.WebService.php.swp b/src/Webservice/.WebService.php.swp new file mode 100644 index 0000000000000000000000000000000000000000..4a0509c2086f1b3ef336ab5293ac6d5390f478a3 GIT binary patch literal 12288 zcmeI2OKcoP8pjKE3A;;ph!vd6!$7x#Ki#-&ZwBcMd#oqD}8^93XhzK*;+yeX#oY`YYtjKMCopdzbJUy57JKStH<{8|+d4 zv3~P7=ly`q92NdLYtHlLT*vLR<_7D;OsxAJYsSKBK3IIk<+3ShM1yFLzN?~2fl7fr z6i8%m=I(3B-|zUF4)t4V6ZEe)p5CKDRa7ZZDNrd;DNrd;DNrd;DNrd;De!w!Kt@-P z$1$lZ(}`ujv9CzKXP>{fc~|qP6sQ!a6sQ!a6sQ!a6sQ!a6sQ!a6sQ!a6!?Eq!0i%p z6DIt#`k{~i|IdE^|9U+kzkqMSH{dPs6j%kb;4ruaOn|GwPuCIhBlr}20$u`-flaUh zIJgb``&vTY25*3KU;`Wi2f?@d33(U11D*rVf~Ub6uz>~6Uqi@e;91ZC4KM?~{|h1C zfsesQ;298s7WnU6CrPcSHU`P!8|w!_Je)khpP#B z89WKL!K2^=xE*}3kC1m!Si|!`ujOt|e2!4O%)7c0OeP|vcyc3f5o+q~E1z>lY?{+O9n#gq6JxxyXBlLrY=y{K2wr}`!bf^X1}ZP3#(p7B`N z^jIW)9@@1P&f9LdH7ELUZJO53@PrPNSkg%Fb-&A~E9sEqdp+!^I@A^YWXM7pH&A`F zvsPc?QfO!u?Uq-`Z*kOY5UTHu&)hw1IlkhODi{Z>{pUFkt zWT~fxVUmg1E~%E*S5vsK$tm_o;tST@wP`B$Ve0WDly>1Fnc^@4{VJbWJH>hd^OQrh znH=!0J;uv^gKr&iyQV+oS>}pvmpu0z?Q#~=kW0!o{dl}j9hp1ov=>(HTRK{jMmf}k zA3G{g+)luD4~|K-Ub&Y|mikaSSSo-ldKfOL;>rY6!?LZ0Ka2w2Wwtd<@t3LBuqLhP zytn&#zt2Rg<%d0|4Pv+bIQGMSA^0Mv zL%o_bj+p27eAXQov+Wbh%O@6(@1n6zI?lsv%P}it8v_ePM&!NJAYSAMV3S6aYrxVx zt?X^=;?lT4Wy45r*Gu&=Gbs`_X?zmdMj1w@=)F4Q$2&4~UYhPRdUf-g+68Hc^MH;FfsLq3 zdt6Y-VhI;Z8)WTN3{qdx4nrN5ZeggVlcHd8639kY_ozy8Lp+`s(~W`e4KfdvTu+U5 zTs0OZibbIqQ7@9VOJ_&whF#rNb85;&TH$eZ0Tr2GVrJG{nItwdi?x%9+A_PYbV~u4 zMQ<#5lt!;*>Xs9NxucfM%z^IQsKj;UFr(TTBHNl4-&y@XIE-GzsqvE9_P z*h;Jrc9myr>>R68-sW-z&Kq8`ym)|iFM*rQT;qWEZA5=49bv<>RS->^NWZ|7jH8%3 zn0jen(XL_&cFf$|RGwtEJr%KR$A*gS|NXy z13SHyCF5=Fl~K|Oe6Ps2A_+%ifvw}y?QXd6WI%PK zEFQ(CT^#m28EnxBZ75Rw3j9^-BkqU$<*V9Y0f;%;G9FK=FWbts^$yCieCfmWX0_7S>5TwzYm*#o!jw}!6 zMQZQMTWu4!gP~kcQtcMBcqE+=>{Il}@~O4c(huS_;|J--!5xJo4!1V)t*DB=(+A;; hw76Cd;fquq{dI&XtE3c1u4l|Fx<}EWd(;#4{{sSsm`wlx literal 0 HcmV?d00001 diff --git a/src/Webservice/Exception/.UsageException.php.swp b/src/Webservice/Exception/.UsageException.php.swp new file mode 100644 index 0000000000000000000000000000000000000000..2da13aeed80c9789972dfa609c282eb02c732f30 GIT binary patch literal 12288 zcmeI&&1w@-6bJBI_w}QFfnx<1fo77{MInl&CdMF1pp#mPg*Y=gof$fr8Sb5?6;bg8 z^bvI9LkO;X0vEc|*AR8(nV9CIU~y~tU-&b*b3bzD2U!d`Zs}pOMH|JEl6G0CD@z|A zy)y6A?t7*D{N6vbf#U^X%*812oal`C&wZ*4*YVjpV%M-9h8|l+ zd)CghTR-+V&B7$MwvEi3bc<<_p7Bi>f&c{O1P-(P)s029zE&Rn)UT~vrRAmVxhd#C z00Izz00bZa0SG_<0_R&GOBd7&dBh9j$6Ov?7fxNrU0fgl0SG_<0uX=z1Rwwb2tWV= z5cm%ToW4>&7L|H@Q4TNv|DU}7|GK2qPsta_XUQkYYe`%3KyqEOBKa=szDd4HK1kk5 z-bh|bTuHufPl5&k2tWV=5P$##AOHafKmY>gTi}@@XDv@_AXnnkh8o#Kc-Bno`X} zj class) */ - protected static function registerFormats(array $formats) { + protected static function registerFormats(array $formats) + { foreach($formats as $f) { self::$formats[$f] = get_called_class(); } } + /** + * See loadFormatters() init() + * @return array of registered formats by subclasses on init() + */ + public static function getRegisterdFormats() + { + return self::$formats; + } + /** * @return Formatter The formatter to use for this request */ - public static function getFormatter() { + public static function getFormatter() + { self::loadFormatters(); $format = self::getFormatFromHeader(); @@ -66,7 +76,6 @@ abstract class Formatter { } } - return 'BSR\Webservice\Formatter\Json'; } diff --git a/src/Webservice/Formatter/Html.php b/src/Webservice/Formatter/Html.php index 9be2a4e..c13fb47 100644 --- a/src/Webservice/Formatter/Html.php +++ b/src/Webservice/Formatter/Html.php @@ -1,5 +1,4 @@ 'info', ); } - $info = Logger::data(); + $info = Logger::getData(); $context['time'] = $info['time']; $panel = static::template($context, 'panel'); diff --git a/src/Webservice/Help.php b/src/Webservice/Help.php index c3e09d4..6096a3e 100644 --- a/src/Webservice/Help.php +++ b/src/Webservice/Help.php @@ -1,5 +1,4 @@ 'Ok', 400 => 'Bad request', @@ -13,13 +13,19 @@ class Renderer { 500 => 'Server Error', ); - public function __construct() { + public function __construct() + { ob_start(); } - public function render($status, $data) { + /** + * + */ + public function render($status, $data) + { header(sprintf('HTTP/1.0 %s %s', $status, self::$statusMessages[$status])); header("Access-Control-Allow-Origin: *"); + ob_clean(); flush(); diff --git a/src/Webservice/WebService.php b/src/Webservice/WebService.php index 02482da..5798dd5 100644 --- a/src/Webservice/WebService.php +++ b/src/Webservice/WebService.php @@ -21,17 +21,19 @@ abstract class WebService /** * Treat the current request and output the result. This is the only * method that should be called on the webservice directly ! + * @param bool $sendSession needed for testing */ - public function run() + public function run($sendSession = true) { Logger::start(array('version' => $this->version)); - $renderer = new Renderer(); + $rendererClass = Configuration::get('renderer.class', __NAMESPACE__ . '\Renderer'); + $renderer = new $rendererClass; $data = array(); try { - $result = $this->call(); + $result = $this->call($sendSession); $data["result"][$this->func] = $result; // Logger::log(print_r($result, true)); @@ -61,13 +63,16 @@ abstract class WebService * Determines which method to call based on GET or POST parameters and * call it before returning the result. * + * @param bool $sendSession used for testing * @return array * @throws UsageException */ - private function call() + private function call($sendSession = true) { - session_save_path(Configuration::get('session.save_path')); - session_start(); + if ($sendSession) { + session_save_path(Configuration::get('session.save_path')); + session_start(); + } $params = empty($_GET) ? $_POST : $_GET; if (empty($params)) { diff --git a/templates/func_help.html b/templates/func_help.html new file mode 100644 index 0000000..e6e1925 --- /dev/null +++ b/templates/func_help.html @@ -0,0 +1,14 @@ +

{{ func }}

+ +

Parameters

+
+ {{ parameters }} +
+ +

Return

+{{ return }} + +

Description

+{{ help }} + + diff --git a/templates/layout.html b/templates/layout.html new file mode 100644 index 0000000..2f00480 --- /dev/null +++ b/templates/layout.html @@ -0,0 +1,40 @@ + + + + + + BSR WebService - {{ title }} + + + + + + +
+ {{ content }} +
+ + + + + \ No newline at end of file diff --git a/templates/panel.html b/templates/panel.html new file mode 100644 index 0000000..207c655 --- /dev/null +++ b/templates/panel.html @@ -0,0 +1,11 @@ +
+
+

{{ title }}

+
+
+ {{ content }} +
+ +
\ No newline at end of file diff --git a/templates/param_help.html b/templates/param_help.html new file mode 100644 index 0000000..df14e71 --- /dev/null +++ b/templates/param_help.html @@ -0,0 +1,5 @@ +
{{ name }} {{ optional }}
+
+ {{ type }} + {{ doc }} +
\ No newline at end of file diff --git a/templates/return_help.html b/templates/return_help.html new file mode 100644 index 0000000..8f361cf --- /dev/null +++ b/templates/return_help.html @@ -0,0 +1,2 @@ +{{ type }} +{{ doc }} diff --git a/tests/Webservice/.MockWebserviceSubclass.php.swp b/tests/Webservice/.MockWebserviceSubclass.php.swp new file mode 100644 index 0000000000000000000000000000000000000000..42453110ece76727093688fe4a0a3817dec322ee GIT binary patch literal 12288 zcmeI&O-jQ+7zW_4E`_S-1;!t!f;P2o3RT1(6c-{`R75vP`n8RwnUI;ZLQxOkIb4cs zw_ZdK;0atgi7llH#jWKXcxN)18InAZMaVdX(}P1%$`{C#DWdH3>&1h5r1KY|dUEa$ zrD?kjFW|f{UE3cr|E_NBOIi1MWjFF#Z0$&E%dzWhwb@Y|wLF(C%}OiltbgKAy4U?~ zC3aljRw^Gh!Xa0}5CkAFAQ0=?N-0Zg#ntpxpP!o*Gt(ynQ_z6`1Rwwb2tWV=5P$## zMq5CK8M-%*IM#j4@ot;>(RRCNAOHafKmY;|fB*y_009U<00I#BhXQt$=wpJYFllby z{QvKL|9_hPyUCl$v&oaml}Xj4WKuLq)>tMe5P$##AOHafKmY;|fB*y_0D(~xxFuoA zcbyzXtm7yUxr%JENcO6Wy*O~SCj)Vu4&};}%#g zpxZL38xiwSsKtf|V&7k)4yBvl)9d`+6EFBib5K>HKSUJRO;(}pve>R1U-n1Jw7!|_ Gq5lE_Bzutn literal 0 HcmV?d00001 diff --git a/tests/Webservice/.WebserviceTest.php.swp b/tests/Webservice/.WebserviceTest.php.swp new file mode 100644 index 0000000000000000000000000000000000000000..5a8eca6474a04bfbd9280e273a267019f3964305 GIT binary patch literal 16384 zcmeI2Uu+ab9LGmc1QaC@)C4sn)a+fMy%sRmR*JQhQsvsS*GiBh$KKuC-NN3^va@>y zQG6lsK^}ZF@xcTVP!kgqjWL865??SHA2d;;iIJcQF~sN#N=y{Lv%A;5D@W5dM5&og zKDRf!voo{b`R&Ya{^UBI9ZJ%!_6~w$IUzr<`gr%5>PfQeG$AE!EaL_bgT<@6FuOt73_PSwb>gv*305<8;{(cdxLYPZYwG&!hS zN&%%nQw2P?*w(d-Y~0Z4f9h-3JVaNn7;hR?T~rDv1(X6x0i}RaKq;UUPzopo{+|lC z_5$(}UTs16dPaD@Wy*PB7+xKoGgIz|L3L6JC+E;2ZEY_zHXuUIzO>4#dG)un3&LlaQ0(2zU-`0>9ru$Zz0Ra1k5_ zN5KnV9e5Zl1{anR@+LS14uj`G8YIA#C4_tc${+`HupBG}zbq!?95@DE0VPlbTfl1Y z)9r-30fxbLFbFO$LV3WK;2m%P*x+gK6j%$c-bTnL;1t*kmV>2W3Haz%LOukq0~b67 zy1+`X0$jr6%Q^5WNP@pnSF*k?f%D)y@GUqBj(~$;0)+Q8sj{vTZdA*qgTX` zHOdZncp?@jeriGbb4xjC2w_+ynWEva!n8S{__ZU*G7Lq57PoAOwq9Le8;Uz{z|&0; z)50v0%q{bRww|^)OxWBKtj}@uL%TKRINZ_p?A9#3!n8f{9#YGtS#q5nozof;128*RF2>vcRUR>Vuo zq@uUTrbg0ZNJy9O8`E@+ZtkU;-l;XjY9ieZUMexCyL)&fyJKW9yK7)9n@kVl^-W%? zF9?E2z7`vW-JuH?LD8hR4y*7gtG_vo;V{>8EHNM}sG%06O%C&IFkjzbu49q18XKx` zm`@tTFz<6pUWHk%n7c_t>2-E=%*HCJx|1z<6+5y3-xljNtr>uSL)lI5Z0u$$X99II z>YI;mJ$2PBZO6A7mpN$5QXEZRv-a%fwVuglOJm0~pL(0Rnhg4yx)uXw(b#CnmV&k>NN}c4pcfvp(#(dpdW7_wa6hhl9r zOa@oiFZsV*%YLSjdmH_eg)xdTLu8AxbS?5X9;cpV8rJ?W82PaMiOuBrD)!mEge^h{fK%dvvtNVhrG@0)aJ%iZ1Z0b?4X zx66WQ@pza@=;~qDIKGT%_)%X^*D>wL%SG-Mo1jU29MPWgw3o}9aQkCgXZwcsjncD~ zuNCGuWwaxhJ8stoFLqd%mMDiFa+vt3(I^ACX`QlzF1|)VWuRXdj1YX3^vU#SX52MQ zk!cX2G1N09D(nibbtX6kH&feF8IS@C!C%Plk6OMn7?i3gN&%&SQa~x76i^B%1(X6x0i}RaU``4IDIbd6)S<{o%wR=J@CuXD0#X<`rG{C6 U`8Ef6?ez3D>t0c{*RR9=11M+0hyVZp literal 0 HcmV?d00001 diff --git a/tests/Webservice/Formatter/FormatterTest.php b/tests/Webservice/Formatter/FormatterTest.php index f9895db..dbe15fc 100644 --- a/tests/Webservice/Formatter/FormatterTest.php +++ b/tests/Webservice/Formatter/FormatterTest.php @@ -1,78 +1,13 @@ class) - */ - protected static function registerFormats(array $formats) { - foreach($formats as $f) { - self::$formats[$f] = get_called_class(); - } - } - - /** - * @return Formatter The formatter to use for this request - */ - public static function getFormatter() { - self::loadFormatters(); - $format = self::getFormatFromHeader(); - - return new $format(); - } - - /** - * Load all formatters in the current directory - */ - private static function loadFormatters() { - preg_match('/(.+)\\\([a-zA-Z0-9]+)/', get_called_class(), $parts); - $us = $parts[2]; - $namespace = $parts[1]; +use PHPUnit\Framework\TestCase; - $base = __DIR__.'/'; - $ext = '.php'; - $files = glob(sprintf('%s%s%s', $base, '*', $ext)); - foreach($files as $f) { - $c = str_replace(array($base, $ext), '', $f); - if($c !== $us) { - $c = $namespace.'\\'.$c; - call_user_func(array($c, 'init')); - } - } +class FormatterTest extends TestCase +{ + public function testFormatterAllwaysReturnsAJsonFormatter() + { + $formatter = Formatter::getFormatter(); + $this->assertEquals($formatter instanceof Json, true); } - - /** - * @return string The class name to instantiate in accord to the Accept header - */ - private static function getFormatFromHeader() { - //TODO this is ugly - return 'BSR\Webservice\Formatter\Json'; - if(isset($_SERVER['HTTP_ACCEPT'])) { - $formats = array_map(function($f) { - $parts = explode(';', $f); - $parts[1] = (isset($parts[1]) ? (float) preg_replace('/[^0-9\.]/', '', $parts[1]) : 1.0) * 100; - return $parts; - }, explode(',', $_SERVER['HTTP_ACCEPT'])); - - usort($formats, function($a, $b) { return $b[1] - $a[1]; }); - - foreach($formats as $f) { - if(isset(self::$formats[$f[0]])) { - return self::$formats[$f[0]]; - } - } - - } - - return 'BSR\Webservice\Formatter\Json'; - } - - /** - * Output the content for the given data - * @param array $data - */ - abstract public function render($data); } diff --git a/tests/Webservice/Formatter/JsonTest.php b/tests/Webservice/Formatter/JsonTest.php index 45d46a8..eda054c 100644 --- a/tests/Webservice/Formatter/JsonTest.php +++ b/tests/Webservice/Formatter/JsonTest.php @@ -1,17 +1,34 @@ array(1, 'a', 'b', array()), + '1' => array(3 => 'c'), + 0 => 'hello', + ); + ob_start(); + $format->render($someArray); + $jsonRepresentation = ob_get_clean(); + $this->assertSame(json_decode($jsonRepresentation, true), $someArray); } - public function render($data) { - echo json_encode($data); + public function testRegistersItsFormatAcceptHeader() + { + Formatter::getFormatter(); + $formats = Formatter::getRegisterdFormats(); + $this->assertSame(array_intersect($this->accept, array_keys($formats)), $this->accept); } } diff --git a/tests/Webservice/MockRenderer.php b/tests/Webservice/MockRenderer.php new file mode 100644 index 0000000..a284274 --- /dev/null +++ b/tests/Webservice/MockRenderer.php @@ -0,0 +1,16 @@ +render($data); + } +} diff --git a/tests/Webservice/MockWebserviceSubclass.php b/tests/Webservice/MockWebserviceSubclass.php new file mode 100644 index 0000000..06fde41 --- /dev/null +++ b/tests/Webservice/MockWebserviceSubclass.php @@ -0,0 +1,10 @@ + 'Ok', 400 => 'Bad request', 404 => 'Not Found', @@ -13,17 +15,15 @@ class Renderer { 500 => 'Server Error', ); - public function __construct() { + public function testThatOutputBufferGetsInializedOnConstruction() + { + $text = 'This text should be captured by the renderers ob_start()'; ob_start(); - } - - public function render($status, $data) { - header(sprintf('HTTP/1.0 %s %s', $status, self::$statusMessages[$status])); - header("Access-Control-Allow-Origin: *"); - ob_clean(); - flush(); - - $formatter = Formatter::getFormatter(); - $formatter->render($data); + echo 'Rubish text, that is not intended to be outputed'; + ob_get_clean(); + $renderer = new Renderer(); + echo $text; + $obcontent = ob_get_clean(); + $this->assertSame($text, $obcontent); } } diff --git a/tests/Webservice/WebserviceTest.php b/tests/Webservice/WebserviceTest.php index 4035af5..464334e 100644 --- a/tests/Webservice/WebserviceTest.php +++ b/tests/Webservice/WebserviceTest.php @@ -2,12 +2,131 @@ namespace BSR\Webservice; use PHPUnit\Framework\TestCase; +use BSR\Utils\Logger\Logger; +use BSR\Utils\Configuration\Configuration; class WebserviceTest extends TestCase { + private $webservice; + public function setUp() { + $this->webservice = new MockWebserviceSubclass('1.2.3'); + } + + private function removeLogs() + { + $logsDir = realpath(dirname(Configuration::get('log.file'))); + $files = glob("$logsDir/*"); + foreach($files as $file){ + if(is_file($file)) unlink($file); + } } - public function test + + /** + * @see config/configuration.local.php for the mock renderer used + * @runInSeparateProcess + */ + public function testRunSavesTheRequestIntoALogFile() + { + $this->removeLogs(); + $log = Logger::getLastLogs(); + $this->assertEquals(Logger::NO_LOG_YET_MSG, $log); + $this->webservice->run(false); + $response = ob_get_clean(); + $log = Logger::getLastLogs(); + $this->assertNotEquals(Logger::NO_LOG_YET_MSG, $log); + } + + /** + * @see config/configuration.local.php for the mock renderer used + * @runInSeparateProcess + */ + public function testReturnsErrorNoArgumentsWhenNoParamtersInGetPostRequest() + { + $this->removeLogs(); + $log = Logger::getLastLogs(); + $this->assertEquals(Logger::NO_LOG_YET_MSG, $log); + + $_GET = array(); $_POST = array(); + + $this->webservice->run(false); + $response = ob_get_clean(); + $responseArray = json_decode($response, true); + $this->assertEquals(100, $responseArray['error']['code']); + $this->assertEquals('NoArguments', $responseArray['error']['name']); + } + + public function testDoesNotReturnErrorNoArgumentsWhenParamtersInGetRequest() + { + $this->removeLogs(); + $log = Logger::getLastLogs(); + $this->assertEquals(Logger::NO_LOG_YET_MSG, $log); + + $_GET = array('a' => 'a1'); + + $this->webservice->run(false); + $response = ob_get_clean(); + $responseArray = json_decode($response, true); + $this->assertNotEquals(100, $responseArray['error']['code']); + $this->assertNotEquals('NoArguments', $responseArray['error']['name']); + } + + public function testDoesNotReturnErrorNoArgumentsWhenParamtersInPostRequest() + { + $this->removeLogs(); + $log = Logger::getLastLogs(); + $this->assertEquals(Logger::NO_LOG_YET_MSG, $log); + + $_POST = array('a' => 'a1'); + + $this->webservice->run(false); + $response = ob_get_clean(); + $responseArray = json_decode($response, true); + var_dump($responseArray); + $this->assertNotEquals(100, $responseArray['error']['code']); + $this->assertNotEquals('NoArguments', $responseArray['error']['name']); + } + + public function testReturnsErrorMissingMethodWhenNoFuncParamInRequest() + { + $this->removeLogs(); + $log = Logger::getLastLogs(); + $this->assertEquals(Logger::NO_LOG_YET_MSG, $log); + + $_POST = array('a' => 'a1'); + + $this->webservice->run(false); + $response = ob_get_clean(); + $responseArray = json_decode($response, true); + $this->assertEquals(101, $responseArray['error']['code']); + $this->assertEquals('MissingMethod', $responseArray['error']['name']); + } + + public function testDoesNotReturnErrorMissingMethodWhenFuncParamInRequest() + { + $this->removeLogs(); + $log = Logger::getLastLogs(); + $this->assertEquals(Logger::NO_LOG_YET_MSG, $log); + + $_GET = array('func' => 'someMockFunction'); $_POST = array(); + + $this->webservice->run(false); + $response = ob_get_clean(); + $responseArray = json_decode($response, true); + $this->assertEquals(100, $responseArray['error']['code']); + } + + public function testRunThrowsAUsageExceptionWhenFuncParamIsNotCallableOnSubclass() + { + } + + public function testRunThrowsAUsageExceptionWhenMissingRequiredParamsInRequest() + { + } + + public function testRunThrowsAUsageExceptionWhenTooManyParamsInRequest() + { + } }