diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000..ad58a724af Binary files /dev/null and b/.DS_Store differ diff --git a/.github/workflows/php.yml b/.github/workflows/php.yml index 3644b298ae..47a6dc7eff 100644 --- a/.github/workflows/php.yml +++ b/.github/workflows/php.yml @@ -41,14 +41,11 @@ jobs: run: export MYSQL_PWD=root && mysql --default-character-set=utf8 -h 'localhost' -P '3306' -u 'root' -v -e "CREATE DATABASE IF NOT EXISTS opusdb DEFAULT CHARACTER SET = UTF8 DEFAULT COLLATE = UTF8_GENERAL_CI; CREATE USER 'opus4admin'@'localhost' IDENTIFIED WITH mysql_native_password BY 'root'; GRANT ALL PRIVILEGES ON opusdb.* TO 'opus4admin'@'localhost'; CREATE USER 'opus4'@'localhost' IDENTIFIED WITH mysql_native_password BY 'root'; GRANT SELECT,INSERT,UPDATE,DELETE ON opusdb.* TO 'opus4'@'localhost'; FLUSH PRIVILEGES;" - name: Prepare - run: ant prepare-workspace prepare-test-workspace prepare-javascript prepare-config lint reset-testdata -DdbUserPassword=root -DdbAdminPassword=root + run: ant prepare-workspace prepare-test-workspace prepare-config lint reset-testdata -DdbUserPassword=root -DdbAdminPassword=root - name: Mail-Server run: php scripts/opus-smtp-dumpserver.php 2>&1 >> tests/workspace/log/opus-smtp-dumpserver.log & - - name: Coding-Style - run: php composer.phar cs-check - - name: Test-library run: php composer.phar test -- --testsuite library @@ -63,3 +60,6 @@ jobs: - name: Test-scripts run: php composer.phar test -- --testsuite scripts + + - name: Coding-Style + run: php composer.phar cs-check diff --git a/.gitignore b/.gitignore index 7661df6ba7..850b38a600 100644 --- a/.gitignore +++ b/.gitignore @@ -7,10 +7,12 @@ db/schema # ignore any third-party library vendor +.vagrant # ignore composer runtime composer.phar composer.lock +bin/composer # ignore all workspace files workspace/**/* diff --git a/CHANGES.md b/CHANGES.md index 2fef388460..8f596d6276 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,132 @@ # OPUS 4 Change Log +## Release 4.7.1 - 2022-03-24 + +### Aufgaben + +* #520 SOLR-Installation von Install-Skript entfernen + +* [OPUSVIER-421] - Feinschliff des SolrIndexBuilder-Skripts +* [OPUSVIER-1443] - Cookies: Setzen der Option http_only gegen XSS-Cookie-Klau +* [OPUSVIER-3657] - Logging Setupcode verschieben und erweitern +* [OPUSVIER-3698] - Skript für die Volltextextraktion von Dateien +* [OPUSVIER-4140] - Verbesserung der Übersichtlichkeit in EnrichmentKey-Administration durch Trennung von nicht geschützten und geschützten EKs +* [OPUSVIER-4202] - Fehlermeldung bei Enrichments vom Typ Regex verbessern: Regex in Validierungsfehlermeldung ausgeben +* [OPUSVIER-4213] - BibTex-Parser für den BibTex-Import erstellen +* [OPUSVIER-4216] - Sonderzeichenbehandlung in BibTeX das Anführungszeichen verwendet fixen +* [OPUSVIER-4279] - Seite für Dokumenttypen aus Info in den Setup Bereich verschieben +* [OPUSVIER-4289] - Application Logging Code auf LogService umstellen +* [OPUSVIER-4298] - Embargofristen aus SWORD Schnittstelle übernehmen +* [OPUSVIER-4319] - Systemdaten für Dokumente separat von Enrichments speichern +* [OPUSVIER-4323] - Formatierung der Hilfe verbessern +* [OPUSVIER-4324] - Symfony/Console für Kommandozeileninterface verwenden +* [OPUSVIER-4325] - Kommando zum Entfernen von Dokumenten aus Index hinzufügen +* [OPUSVIER-4327] - Option für Indexing Blockgröße unterstützen +* [OPUSVIER-4328] - SolrIndexBuilder.php-Skript durch opus4-Skript ersetzen +* [OPUSVIER-4329] - Index-Löschen vor der Indexierung optional machen +* [OPUSVIER-4330] - Index Building Code von IndexCommand trennen +* [OPUSVIER-4331] - Support %runId% for custom log formats +* [OPUSVIER-4333] - BibTeX Import Skript in Kommando umwandeln +* [OPUSVIER-4338] - Skript für Volltextextraktion in Kommando umwandeln +* [OPUSVIER-4343] - Separate Logdatei für Indexierung +* [OPUSVIER-4344] - Delete Skript in Kommando umwandeln +* [OPUSVIER-4345] - Allgemeinen Console Code zu OPUS 4 Common verschieben +* [OPUSVIER-4346] - Logging using LogService in OPUS Framework +* [OPUSVIER-4348] - "Language set to 'de'" Nachricht nicht ständig ausgeben +* [OPUSVIER-4356] - Detailliertere Fortschrittsanzeige für Kommandos +* [OPUSVIER-4364] - Neue Klasse für System-Metadaten für Model-Objekte +* [OPUSVIER-4368] - Datenbankschema für neue Model-Properties erweitern +* [OPUSVIER-4369] - Model-Properties Funktionen in Opus_Model_Abstract integrieren +* [OPUSVIER-4393] - Extraktion von Datei als Kommando +* [OPUSVIER-4394] - Properties entfernen, wenn Model gelöscht wird +* [OPUSVIER-4395] - Sonderbehandlung von Delete für Dokumente beseitigen +* [OPUSVIER-4401] - Timeout Option für Extract/Index-Kommandos +* [OPUSVIER-4407] - Add information necessary for developers to framework README.md +* [OPUSVIER-4413] - Change level of logger at runtime +* [OPUSVIER-4414] - Function createLog should accept string and integer for priority +* [OPUSVIER-4415] - Framework Code auf PHP Namespaces umstellen +* [OPUSVIER-4416] - (Opus\Model\)Exception in ModelException umbenennen +* [OPUSVIER-4450] - LicencesAdminTest schlägt fehl +* [OPUSVIER-4454] - SWORD-Pakete bei Fehlern aufheben +* [OPUSVIER-4458] - Remove Log class from Framework +* [OPUSVIER-4459] - BibTeX-Import in Administration integrieren +* [OPUSVIER-4460] - Zugriffskontrolle auf BibTeX-Import +* [OPUSVIER-4461] - BibTeX-Parser +* [OPUSVIER-4462] - BibTeX-Processor +* [OPUSVIER-4463] - Konfiguration des BibTeX-Mappings +* [OPUSVIER-4464] - Mapping des Document-Type +* [OPUSVIER-4465] - Mapping-Klassen verallgemeinern +* [OPUSVIER-4466] - Umgang mit zusätzlichen Feldern +* [OPUSVIER-4467] - Umgang mit unbekannten Feldern +* [OPUSVIER-4468] - Mapping Originaldaten/Hash +* [OPUSVIER-4469] - Mapping Identifiers +* [OPUSVIER-4471] - Kanonisierung von BibTeX-Records +* [OPUSVIER-4472] - translation.log wird mit Meldungen zu "locale" und "language" unnötig groß +* [OPUSVIER-4494] - Import-Verzeichnis zu Workspace hinzufügen +* [OPUSVIER-4496] - Workspace Setup in Administration anzeigen +* [OPUSVIER-4499] - Funktion, um alle Enrichments eines Dokuments abzufragen +* [OPUSVIER-4505] - DOI Plugin von Delete-Event auf Status-Change umstellen +* [OPUSVIER-4507] - OPUS-Export-Funktionen hinter einem Proxy-Server +* [OPUSVIER-4508] - OAI-Abfragen in OPUS hinter einem Proxy-Server +* [OPUSVIER-4509] - "Administration > Dokumente > DOKUMENT > Dateien" hinter einem Proxy-Server +* [OPUSVIER-4510] - Benachrichtigungen (Notification) hinter einem Proxy-Server +* [OPUSVIER-4518] - Zugriff auf Zend_Registry kapseln +* [OPUSVIER-4520] - Verwendung von LOG_LEVEL entfernen +* [OPUSVIER-4521] - Verwendung von "Available_Languages" in Zend_Registry entfernen +* [OPUSVIER-4522] - Move opus.disableDatabaseVersionCheck into configuration +* [OPUSVIER-4523] - Stop using "db_adapter" in Zend_Registry +* [OPUSVIER-4524] - Stop using 'Zend_Locale' in Zend_Registry +* [OPUSVIER-4532] - Publikationslisten hinter einem Proxy +* [OPUSVIER-4543] - Run GitHub Actions for Pull Requests +* [OPUSVIER-4550] - MySQL Version 8: Install Skript zum Anlegen von Usern muss angepasst werden +* [OPUSVIER-4554] - Tägliche automatische GitHub Action Runs für alle Repositorien +* [OPUSVIER-4555] - BibTeX-Import: "and" zwischen Autoren wird manchmal ignoriert +* [OPUSVIER-4570] - BibTeX-Import - Import von DOI mit Maskierung + +### Bugs + +* #375 DB-Exception beim Versuch einen neuen Account ohne Passwort zu speichern bug +* #482 bin/install.sh doesn't finish with Composer 2 as robloach/component-installer package is abandoned +* #483 Setting up the database with MySQL 8.0 using install.sh script doesn't work + +* [OPUSVIER-4038] - Betrieb von OPUS hinter einem Proxy +* [OPUSVIER-4043] - Schattierung bei mehreren Autoren im Publishformular verschiebt sich +* [OPUSVIER-4161] - Class-Loading Warnungen in Admin_Form_EnrichmentKeyTest +* [OPUSVIER-4360] - Timeout bei Extraktion großer Dateien +* [OPUSVIER-4367] - "PHP Notice: Failed saving metadata to metadataCache" aus der Konsole +* [OPUSVIER-4370] - Sprache im Publishformular nicht auswählbar bei angepassten Feldern in der Templatedatei +* [OPUSVIER-4385] - Fehlerhafte Sortierung der Ergebnisse nach Jahr bei Einstellung CompletedYear +* [OPUSVIER-4419] - Bezeichnung des Formats MARC21 über OAI inkonsistent +* [OPUSVIER-4482] - Fix Ant "build.xml" script for framework +* [OPUSVIER-4484] - Skript nicht gefunden für die Indexierung der Testdaten während der Installation +* [OPUSVIER-4512] - Fehler beim Abspeichern in der Administration mit Select-Enrichmentfeld +* [OPUSVIER-4527] - Duplizierung von Übersetzungsschlüsseln beim Editieren der statischen Seiten +* [OPUSVIER-4547] - Facette "server_state" zeigt für den Admin nur noch publizierte Dokumente an +* [OPUSVIER-4551] - DOI-Vergabe funktioniert mit dev-4.7.1 nicht mehr +* [OPUSVIER-4556] - BibTeX-Import: Probleme mit Unterstrich in Werten +* [OPUSVIER-4557] - Bestimmte leere Felder im BibTeX-Import-File verhindern den Import +* [OPUSVIER-4571] - Maskierung von URLs beim BibTeX-Import funktioniert nur teilweise + +### Entwicklung + +* [OPUSVIER-4251] - Horizontal Tab (ASCII-Code 9) in Abstract und Subject von Testdokument 41 +* [OPUSVIER-4358] - SetStatusOfExistingDoiTest schlägt unregelmässig fehl +* [OPUSVIER-4359] - Branch 4.7 lässt sich auf GitHub nicht löschen +* [OPUSVIER-4553] - Framework Builds laufen auf GitHub nicht mehr + +### Feature Request + +* [OPUSVIER-2245] - SolrIndexBuilder: Index löschen nur durch explizites Kommando "--rebuild-all" + +### Spezifikation + +* [OPUSVIER-1276] - Wie könnte Kapselung von "Opus_Document" aussehen? +* [OPUSVIER-2560] - Spezifikation nachreichen für den Umgang mit Fehlern während der Indexierung +* [OPUSVIER-4100] - Hinweistext zu Enrichments im Metadaten-Edit-Formular einbauen +* [OPUSVIER-4504] - Entwurfsentscheidung zum ProcessorRule-Interface + +--- + ## Release 4.7.0.8 - 2022-01-25 ### Aufgaben diff --git a/README.md b/README.md index e9f013dc49..3b30565cf0 100644 --- a/README.md +++ b/README.md @@ -7,9 +7,9 @@ redevelopment that was created as part of a DFG ([Deutsche Forschungsgemeinschaf Since then the development has been continued at KOBV ([Kooperativer Bibliotheksverbund Berlin-Brandenburg][KOBV]) mostly. -## OPUS 4.7.0.7 (current version) +## OPUS 4.7.1 (current version) -The current version of OPUS 4 is __4.7__.0.7. It is available on the [master][MASTER] branch. +The current version of OPUS 4 is __4.7.1__. It is available on the [master][MASTER] branch. [Documentation][DOC] : Information on setting up a repository, for users and administrators. @@ -17,6 +17,16 @@ The current version of OPUS 4 is __4.7__.0.7. It is available on the [master][MA [Developers][DEVDOC] : Information for developers. +_We are in the process to moving the developer information into the GitHub Wiki. Specific information about OPUS 4 +packages, might be found in the Wiki pages of their repositories._ + +## Testing OPUS 4 + +You can run OPUS 4 using Vagrant. This makes it easy to create a VM running OPUS 4 for testing or even development. +More information in the Wiki: + +https://github.com/OPUS4/application/wiki/Vagrant + ## Questions & Issues Questions should be asked through the [OPUS 4 mailing list][OPUSTESTER]. We are sending out release announcements and diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 72e4ee89d4..f55e667731 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -1,4 +1,189 @@ # OPUS 4 Release Notes +--- + +## Release 4.7.1 2022-03-24 + +### Anforderungen + +OPUS 4.7.1 erfordert weiterhin PHP 7.1 bzw. eine Version vor PHP 7.2. Durch +die Verwendung von Zend Framework 1 ist OPUS 4 nicht kompatibel mit neueren +PHP Versionen. Diese werden erst nach dem vollständigen Umstieg auf Laminas +mit OPUS 4 v5.0 unterstützt werden. + +### Installation + +Die Installation von Apache Solr wurde aus den Installationsskripten entfernt. +Für den produktiven Betrieb sollte Solr entsprechend den Empfehlungen der +Apache Solr Dokumentation installiert werden. + + + +OPUS 4.7.1 ist mit Apache Solr 7.7.2 getestet. Der Umstieg auf Solr 8 ist +nach dem Umstieg auf Laminas geplant. + +Die Integration in die Installationsskripte war vor allem für Test-Installationen +gedacht. Tests sind nun mit dem Einsatz von Vagrant leichter geworden. + +### Testen mit Vagrant + +Mit Vagrant () und dem `Vagrantfile` in OPUS 4 +Application lässt sich eine Virtuelle Maschine hochfahren in der ein vollständiges +OPUS 4 läuft. Informationen dazu finden sich im Wiki. + + + +Damit kann man OPUS 4, auch Entwicklungsversionen, unter Linux, Mac OS-X +oder auch Windows laufen lassen, z.B. um neue Funktionen zu testen oder +an Anpassungen zu arbeiten. + +### User Interface "Experimente" + +Das Formular für den Import von BibTeX-Dateien verwendet ein neues Eingabefeld +für die Auswahl von Sammlungen. Es funktioniert wie ein Suchfeld für Sammlungen, +die dann direkt ausgewählt werden können. Bei der Suche werden der Name und die +Nummer von Sammlungen berücksichtigt. + +Auch wenn man den BibTeX-Import nicht nutzen möchte, lohnt es sich vielleicht das +Eingabefeld zu testen. Das Formularelement muss noch weiter ausgebaut werden. +Es soll aber später auch im neuen Publish-Modul und im Metadaten-Formular verwendet +werden. Feedback kann in folgendem GitHub Issue oder über die Tester-Mailing-Liste +gegeben werden. + + + +### Konfiguration + +Der Parameter `url` kann verwendet werden, um die absolute URL für eine OPUS 4 +Instanz manuell zu setzen. Diese URL wird dann verwendet, um absolute Links, +z.B. in Exporten oder E-Mails, zu generieren. + +url = 'https://opus4mig.kobv.de/opus4-demo' + +__URLs mit Port werden momentan nicht unterstützt.__ + +### Betrieb mit Proxy + +Es wurden eine Reihe von Problemen beim Betrieb von OPUS 4 mit einem Proxy-Server +behoben, hauptsächlich das korrekte Rendern von URLs in Exports. Der Betrieb mit +einem Proxy sollte nun ohne Einschränkungen möglich sein. + +### Neues Kommandozeilen-Skript `bin/opus4` + +Es gibt das neue Skript `bin/opus4`, dass in Zukunft die Rolle des zentralen OPUS 4 +Werkzeugs auf der Kommandozeile übernehmen wird. Mit dem Kommando `list` lassen sich +die bisher integrierten Kommandos anzeigen. Mit `help` lassen sich Informationen zu +einzelnen Kommandos abrufen. + + $ bin/opus4 list + $ bin/opus4 help index:index + +Es sind noch nicht alle alten Skripte in Kommandos umgewandelt worden. + +### Wartung des Solr-Index + +Das Skript `script/SolrIndexBuilder.php` wurde durch `bin/opus4` ersetzt. Dadurch +soll der Aufruf vereinfacht werden. Das neue Skript soll außerdem in Zukunft auch +andere Funktionen übernehmen, die nichts mit dem Index zu tun haben. + +Im OPUS 4 Handbuch gibt es eine neue Seite, die die Funktionen des Skripts für +den Index beschreibt. + + + +Es gibt jetzt die Möglichkeit einzelne Dokumente einfacher zu indexieren oder auch +aus dem Index zu entfernen. Es kann über eine Option bestimmt werden wie viele +Dokumente gleichzeitig zum Solr-Server geschickt werden sollen. Das kann helfen, +wenn es Probleme bei der Indexierung gibt. + +### Export + +Die beiden Variablen `host` und `server` in den Export-XSLT Skripten wurden durch +die Variable `opusUrl` ersetzt. Eigene Skripte, die diese Variablen einsetzen, +müssen angepasst werden. Die neue Variable `opusUrl` enthält die absolute URL für +die OPUS 4 Instanz. + +### BibTeX-Import + +OPUS 4 erlaubt nun den Import von Dokumentmetadaten aus BibTeX-Dateien. Der Import +ist bisher auf Administratoren beschränkt. Der Import einer BibTeX-Datei kann auf +der Kommandozeile mit dem Befehl + + $ bin/opus4 bibtex:import + +aufgerufen werden. Es können hierbei mehrere Optionen angegeben werden. Die Auflistung +der verfügbaren Optionen ist mit folgendem Befehl möglich. + + $ bin/opus4 help bibtex:import + +Der BibTeX-Import kann auch über die Weboberfläche von OPUS 4 aufgerufen werden. +In der Dokumentenverwaltung gibt es dazu einen entsprechenden Button _BibTeX-Import_. +Das Webformular in der Administration für den Import von BibTeX-Dateien bietet +sämtliche Optionen an, die auch auf der Kommandozeile verwendet werden können. + +#### Anforderungen für BibTeX-Import + +Für die Ausführung des BibTeX-Imports, insbesondere die Umwandlung von LaTeX-codierten +Sonderzeichen (z. B. Umlaute) in ihren Unicode-Entsprechungen, wird das Programm +**Pandoc** benötigt. Das BibTeX-Import-Feature wurde ausführlich mit Pandoc 2.9 +getestet, welches mit den aktuellen Ubuntu-Versionen (2020.10 und 2021.04) über die +Paketverwaltung installiert werden kann. Es wird empfohlen möglichst die neueste +Version von Pandoc (2.17+) zu installieren. + + + +Nach dem Import einer BibTeX-Datei (sowohl über CLI als auch das Webformular) wird +ein Protokoll über die Verarbeitungsschritte ausgegeben, aus dem u. a. hervorgeht, +wie viele BibTeX-Einträge aus der zu importierenden Daten erfolgreich in die OPUS 4 +Datenbank übernommen wurden. Im Falle von Verarbeitungsfehlern erfolgt an dieser +Stelle eine Ausgabe mit weiteren Details zur späteren Nachverfolgung. + +Im OPUS 4 Handbuch gibt es eine neue Seite, auf der die Optionen des CLI-Befehls für +den BibTeX-Import ausführlich beschrieben werden: + + + +### SWORD Import + +Nach dem Import über die SWORD-Schnittstelle werden die übertragenen Pakete gelöscht. +Das erfolgt nicht mehr automatische, wenn beim Import Probleme aufgetreten sind, damit +diese leichter analysiert und behoben werden können. + +### Deckblätter für PDF-Downloads + +Die Entwicklung von automatisch generierten Deckblättern in OPUS 4 hat begonnen. Sie +findet im neuen Paket __opus4-pdf__ statt und ist noch nicht abgeschlossen. In 4.7.1 +wurde die Grundlagen gelegt, um den Deckblatt-Support nach dem Abschluss der Arbeiten +aktivieren zu können. + + + +### Umstieg auf Laminas + +In 4.7.1 sind bereits einige Vorarbeiten für den Umstieg zu Laminas, dem Nachfolger +des Zend Frameworks, eingeflossen, insbesondere im Framework. Die kommenden Releases +werden sich zum größten Teil mit dem Umstieg befassen, da nur so eine solide Platform +für die Entwicklung und das Hosting in den kommenden Jahren geschaffen werden kann. + +### OPUS 4 Framework Package + +#### API + +Die `deletePermanent` Funktion von `Opus\Document`, um Dokumente vollständig zu +löschen, wurde entfernt. Die `delete` Funktion löscht Dokumente jetzt vollständig, +anstatt sie nur in den Server-Status **deleted** zu versetzen. Um Dokumente als +gelöscht zu markieren, ohne sie komplett zu entfernen, muss nun `setServerState` +verwendet werden. + + $doc->setServerState(Document::STATE_DELETED); + $doc->store(); + +Dies muss unter Umständen bei eigenen Skripten berücksichtigt werden. + +#### PHP Namespaces + +Der Code des OPUS Frameworks wurde in Vorbereitung auf die Migration zu Laminas +auf PHP Namespaces umgestellt und die Verwendung der Klassen in der Application +entsprechend angepasst. --- @@ -62,15 +247,15 @@ mehr überschrieben. ## Patch Release 4.7.0.5 2021-08-17 -Dieser Patch Release behebt zwei kleinere Bugs. Das Editieren der Inhalte der -Impressum und Kontakt-Seite ist nun auch von der FAQ-Seite aus ohne Probleme beim +Dieser Patch Release behebt zwei kleinere Bugs. Das Editieren der Inhalte der +Impressum und Kontakt-Seite ist nun auch von der FAQ-Seite aus ohne Probleme beim Speichern möglich. -Von den Suchlinks für Autoren in der Anzeige von Suchergebnissen wurden +Von den Suchlinks für Autoren in der Anzeige von Suchergebnissen wurden Anführungszeichen entfernt. Damit funktioniert die Autorensuche nun zuverlässiger, insbesondere auch mit Namen, die Bindestriche enthalten. -Die Deklaration des Namespaces "xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" -erfolgt nun beim OAI-Export in jedem Metadata Wurzel Element (GH-412). +Die Deklaration des Namespaces "xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" +erfolgt nun beim OAI-Export in jedem Metadata Wurzel Element (GH-412). --- diff --git a/Vagrantfile b/Vagrantfile new file mode 100644 index 0000000000..07c352666b --- /dev/null +++ b/Vagrantfile @@ -0,0 +1,147 @@ +# -*- mode: ruby -*- +# vi: set ft=ruby : + +$software = <' . "\n"; + + $this->assertEquals($expectation, $this->helper->javascriptMessages()); + } } diff --git a/tests/library/Application/View/Helper/LanguageSelectorTest.php b/tests/library/Application/View/Helper/LanguageSelectorTest.php index f1111c90f8..8ca23c536f 100644 --- a/tests/library/Application/View/Helper/LanguageSelectorTest.php +++ b/tests/library/Application/View/Helper/LanguageSelectorTest.php @@ -50,7 +50,7 @@ public function setUp() $this->_helper = new Application_View_Helper_LanguageSelector(); - $this->_helper->setView(Zend_Registry::get('Opus_View')); + $this->_helper->setView($this->getView()); } public function testLanguageConfiguredAndInResourcesGerman() @@ -90,10 +90,7 @@ public function testLanguageConfiguredAndInResourcesEnglish() */ public function testLanguageConfiguredButNotInResources() { - Zend_Registry::set( - 'Zend_Config', - Zend_Registry::get('Zend_Config')->merge(new Zend_Config(['supportedLanguages' => 'de,en,ru'])) - ); + $this->adjustConfiguration(['supportedLanguages' => 'de,en,ru']); $result = $this->_helper->languageSelector(); @@ -113,10 +110,7 @@ public function testLanguageConfiguredButNotInResources() */ public function testOnlyOneLanguageConfigured() { - Zend_Registry::set( - 'Zend_Config', - Zend_Registry::get('Zend_Config')->merge(new Zend_Config(['supportedLanguages' => 'en'])) - ); + $this->adjustConfiguration(['supportedLanguages' => 'en']); $result = $this->_helper->languageSelector(); diff --git a/tests/library/Application/View/Helper/MessagesTest.php b/tests/library/Application/View/Helper/MessagesTest.php index 2d95e75be8..2e0eb7eb56 100644 --- a/tests/library/Application/View/Helper/MessagesTest.php +++ b/tests/library/Application/View/Helper/MessagesTest.php @@ -43,7 +43,7 @@ public function testMessages() { $this->useEnglish(); - $view = Zend_Registry::get('Opus_View'); + $view = $this->getView(); $helper = new Application_View_Helper_Messages(); $helper->setView($view); @@ -67,7 +67,7 @@ public function testMessagesMultiple() { $this->useEnglish(); - $view = Zend_Registry::get('Opus_View'); + $view = $this->getView(); $helper = new Application_View_Helper_Messages(); $helper->setView($view); @@ -95,7 +95,7 @@ public function testMessagesTranslation() { $this->useEnglish(); - $view = Zend_Registry::get('Opus_View'); + $view = $this->getView(); $helper = new Application_View_Helper_Messages(); $helper->setView($view); @@ -119,7 +119,7 @@ public function testMessagesNone() { $helper = new Application_View_Helper_Messages(); - $helper->setView(Zend_Registry::get('Opus_View')); + $helper->setView($this->getView()); $this->assertEquals('', $helper->messages()); } @@ -128,7 +128,7 @@ public function testMessageWithoutMessageKey() { $helper = new Application_View_Helper_Messages(); - $helper->setView(Zend_Registry::get('Opus_View')); + $helper->setView($this->getView()); $this->assertEquals( <<assertTrue($helper->optionEnabled('orcid.linkAuthor.frontdoor')); $this->assertTrue($helper->optionEnabled('linkAuthor.frontdoor', 'orcid')); - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'orcid' => ['linkAuthor' => ['frontdoor' => self::CONFIG_VALUE_FALSE]] - ])); + ]); $this->assertFalse($helper->optionEnabled('orcid.linkAuthor.frontdoor')); $this->assertFalse($helper->optionEnabled('linkAuthor.frontdoor', 'orcid')); diff --git a/tests/library/Application/View/Helper/OptionUrlTest.php b/tests/library/Application/View/Helper/OptionUrlTest.php index 7caccc4777..16049dfa45 100644 --- a/tests/library/Application/View/Helper/OptionUrlTest.php +++ b/tests/library/Application/View/Helper/OptionUrlTest.php @@ -45,23 +45,23 @@ public function testOptionUrl() $helper = new Application_View_Helper_OptionUrl(); - $helper->setView(Zend_Registry::get('Opus_View')); + $helper->setView($this->getView()); - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'logoLink' => 'home' - ])); + ]); $this->assertEquals('http://localhost/opus4/home', $helper->optionUrl('logoLink')); - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'logoLink' => '/opus4/home' - ])); + ]); $this->assertEquals('http://localhost/opus4/home', $helper->optionUrl('logoLink')); - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'logoLink' => 'http://www.opus-repository.org' - ])); + ]); $this->assertEquals('http://www.opus-repository.org', $helper->optionUrl('logoLink')); } diff --git a/tests/library/Application/View/Helper/OptionValueTest.php b/tests/library/Application/View/Helper/OptionValueTest.php index 81e62fcc97..8318073330 100644 --- a/tests/library/Application/View/Helper/OptionValueTest.php +++ b/tests/library/Application/View/Helper/OptionValueTest.php @@ -50,9 +50,9 @@ public function testOptionValueWithEscaping() $this->assertEquals('OPUS 4', $helper->optionValue('name')); - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'name' => 'OPUS 4' - ])); + ]); $this->assertEquals('OPUS 4', $helper->optionValue('name')); $this->assertEquals('<b>OPUS 4</b>', $helper->optionValue('name', null, true)); diff --git a/tests/library/Application/View/Helper/ResultAuthorsTest.php b/tests/library/Application/View/Helper/ResultAuthorsTest.php index 9732220997..1ee748f85b 100644 --- a/tests/library/Application/View/Helper/ResultAuthorsTest.php +++ b/tests/library/Application/View/Helper/ResultAuthorsTest.php @@ -43,7 +43,7 @@ public function setUp() parent::setUp(); $this->helper = new Application_View_Helper_ResultAuthors(); - $view = Zend_Registry::get('Opus_View'); + $view = $this->getView(); $this->helper->setView($view); } diff --git a/tests/library/Application/View/Helper/ResultTitleTest.php b/tests/library/Application/View/Helper/ResultTitleTest.php index 8579350f21..67b29c7040 100644 --- a/tests/library/Application/View/Helper/ResultTitleTest.php +++ b/tests/library/Application/View/Helper/ResultTitleTest.php @@ -43,7 +43,7 @@ public function setUp() parent::setUp(); $this->helper = new Application_View_Helper_ResultTitle(); - $view = Zend_Registry::get('Opus_View'); + $view = $this->getView(); $this->helper->setView($view); $this->useEnglish(); diff --git a/tests/library/Application/View/Helper/ResultYearTest.php b/tests/library/Application/View/Helper/ResultYearTest.php index 4b34fc6d50..2d427e51b6 100644 --- a/tests/library/Application/View/Helper/ResultYearTest.php +++ b/tests/library/Application/View/Helper/ResultYearTest.php @@ -42,7 +42,7 @@ public function setUp() parent::setUp(); $this->helper = new Application_View_Helper_ResultYear(); - $view = Zend_Registry::get('Opus_View'); + $view = $this->getView(); $this->helper->setView($view); } diff --git a/tests/library/Application/View/Helper/SeriesNumberTest.php b/tests/library/Application/View/Helper/SeriesNumberTest.php index 345dd4b7ab..8d72f844dd 100644 --- a/tests/library/Application/View/Helper/SeriesNumberTest.php +++ b/tests/library/Application/View/Helper/SeriesNumberTest.php @@ -31,6 +31,8 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Series; + class Application_View_Helper_SeriesNumberTest extends ControllerTestCase { @@ -48,7 +50,7 @@ public function setUp() public function testSeriesNumberForLinkedDocument() { $document = $this->getDocument(146); - $series = new Opus_Series(1); + $series = new Series(1); $this->assertEquals('5/5', $this->_helper->seriesNumber($document, $series)); } @@ -56,7 +58,7 @@ public function testSeriesNumberForLinkedDocument() public function testSeriesNumberForNotLinkedDocument() { $document = $this->getDocument(146); - $series = new Opus_Series(2); + $series = new Series(2); $this->assertEquals('', $this->_helper->seriesNumber($document, $series)); } @@ -64,7 +66,7 @@ public function testSeriesNumberForNotLinkedDocument() public function testSeriesNumberEscaped() { $document = $this->createTestDocument(); - $series = new Opus_Series(5); + $series = new Series(5); $document->addSeries($series)->setNumber('XIII'); $document->store(); diff --git a/tests/library/Application/View/Helper/ShortenTextTest.php b/tests/library/Application/View/Helper/ShortenTextTest.php index d6cce2f5be..ac8b87f3a2 100644 --- a/tests/library/Application/View/Helper/ShortenTextTest.php +++ b/tests/library/Application/View/Helper/ShortenTextTest.php @@ -44,9 +44,9 @@ public function testShortenText() { $helper = new Application_View_Helper_ShortenText(); - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'frontdoor' => ['numOfShortAbstractChars' => '10'] - ])); + ]); $this->assertEquals('short text', $helper->shortenText('short text')); $this->assertEquals('shortened', $helper->shortenText('shortened text')); @@ -70,17 +70,17 @@ public function testGetMaxLength() { $helper = new Application_View_Helper_ShortenText(); - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'frontdoor' => ['numOfShortAbstractChars' => '10'] - ])); + ]); $this->assertEquals(10, $helper->getMaxLength()); $helper->setMaxLength(null); - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'frontdoor' => ['numOfShortAbstractChars' => 'bla'] - ])); + ]); $this->assertEquals(0, $helper->getMaxLength()); } @@ -89,9 +89,9 @@ public function testSetMaxLength() { $helper = new Application_View_Helper_ShortenText(); - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'frontdoor' => ['numOfShortAbstractChars' => '10'] - ])); + ]); $this->assertEquals(10, $helper->getMaxLength()); diff --git a/tests/library/Application/View/Helper/TransferUrlTest.php b/tests/library/Application/View/Helper/TransferUrlTest.php index c80c3ae54b..9af1c22f2d 100644 --- a/tests/library/Application/View/Helper/TransferUrlTest.php +++ b/tests/library/Application/View/Helper/TransferUrlTest.php @@ -39,7 +39,7 @@ class Application_View_Helper_TransferUrlTest extends ControllerTestCase public function testTransferUrl() { $helper = new Application_View_Helper_TransferUrl(); - $helper->setView(Zend_Registry::get('Opus_View')); + $helper->setView($this->getView()); $transferUrl = $helper->transferUrl('123'); $this->assertEquals('http:///oai/container/index/docId/123', $transferUrl); diff --git a/tests/library/Application/View/Helper/TranslationEditLinkTest.php b/tests/library/Application/View/Helper/TranslationEditLinkTest.php index 1234e460d5..dd85a8ee91 100644 --- a/tests/library/Application/View/Helper/TranslationEditLinkTest.php +++ b/tests/library/Application/View/Helper/TranslationEditLinkTest.php @@ -51,9 +51,9 @@ public function testRenderTranslationEditLink() public function testRenderOnlyIfSetupAccess() { - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'setup' => ['translation' => ['modules' => ['allowed' => 'default,publish,help']]] - ])); + ]); $helper = $this->getHelper(); @@ -76,9 +76,9 @@ public function testRenderOnlyIfSetupAccess() public function testRenderOnlyIfKeyEditable() { - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'setup' => ['translation' => ['modules' => ['allowed' => 'default']]] - ])); + ]); $helper = $this->getHelper(); @@ -86,9 +86,9 @@ public function testRenderOnlyIfKeyEditable() $this->assertEquals('', $html); - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'setup' => ['translation' => ['modules' => ['allowed' => 'default,publish,help']]] - ])); + ]); // TODO enable editing of help module @@ -104,7 +104,7 @@ public function testRenderOnlyIfKeyEditable() protected function getHelper() { $helper = new Application_View_Helper_TranslationEditLink(); - $helper->setView(Zend_Registry::get('Opus_View')); + $helper->setView($this->getView()); return $helper; } } diff --git a/tests/library/Application/View/Helper/ViewFormDefaultTest.php b/tests/library/Application/View/Helper/ViewFormDefaultTest.php index e81aca5817..b4f6aa685d 100644 --- a/tests/library/Application/View/Helper/ViewFormDefaultTest.php +++ b/tests/library/Application/View/Helper/ViewFormDefaultTest.php @@ -29,7 +29,6 @@ * @author Jens Schwidder * @copyright Copyright (c) 2008-2013, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id$ */ class Application_View_Helper_ViewFormDefaultTest extends ControllerTestCase { @@ -37,7 +36,7 @@ class Application_View_Helper_ViewFormDefaultTest extends ControllerTestCase public function testViewFormDefault() { $helper = new Application_View_Helper_ViewFormDefault(); - $helper->setView(new Zend_View()); + $helper->setView(new \Zend_View()); $markup = $helper->viewFormDefault('testName', 'testValue', ['id' => '10']); @@ -47,7 +46,7 @@ public function testViewFormDefault() public function testViewFormDefaultOnlyName() { $helper = new Application_View_Helper_ViewFormDefault(); - $helper->setView(new Zend_View()); + $helper->setView(new \Zend_View()); $markup = $helper->viewFormDefault('testName'); @@ -57,7 +56,7 @@ public function testViewFormDefaultOnlyName() public function testViewFormDefaultEscaping() { $helper = new Application_View_Helper_ViewFormDefault(); - $helper->setView(new Zend_View()); + $helper->setView(new \Zend_View()); $markup = $helper->viewFormDefault('testName', '

HTML

', ['id' => '10']); diff --git a/tests/library/Application/View/Helper/ViewFormMultiCheckboxTest.php b/tests/library/Application/View/Helper/ViewFormMultiCheckboxTest.php index 810adb084c..21476f737d 100644 --- a/tests/library/Application/View/Helper/ViewFormMultiCheckboxTest.php +++ b/tests/library/Application/View/Helper/ViewFormMultiCheckboxTest.php @@ -36,7 +36,7 @@ class Application_View_Helper_ViewFormMultiCheckboxTest extends ControllerTestCa public function testViewFormMultiCheckbox() { $helper = new Application_View_Helper_ViewFormMultiCheckbox(); - $helper->setView(new Zend_View()); + $helper->setView(new \Zend_View()); $markup = $helper->viewFormMultiCheckbox( 'testName', @@ -51,7 +51,7 @@ public function testViewFormMultiCheckbox() public function testViewFormMultiCheckboxEscaping() { $helper = new Application_View_Helper_ViewFormMultiCheckbox(); - $helper->setView(new Zend_View()); + $helper->setView(new \Zend_View()); $markup = $helper->viewFormMultiCheckbox( 'testName', diff --git a/tests/library/Application/View/Helper/ViewFormSelectTest.php b/tests/library/Application/View/Helper/ViewFormSelectTest.php index 8456c498ab..a8b12f6b56 100644 --- a/tests/library/Application/View/Helper/ViewFormSelectTest.php +++ b/tests/library/Application/View/Helper/ViewFormSelectTest.php @@ -29,7 +29,6 @@ * @author Jens Schwidder * @copyright Copyright (c) 2008-2013, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id$ */ class Application_View_Helper_ViewFormSelectTest extends ControllerTestCase { @@ -37,7 +36,7 @@ class Application_View_Helper_ViewFormSelectTest extends ControllerTestCase public function testViewFormSelect() { $helper = new Application_View_Helper_ViewFormSelect(); - $helper->setView(new Zend_View()); + $helper->setView(new \Zend_View()); $markup = $helper->viewFormSelect('testName', '1', null, ['Value1', 'Value2', 'Value3']); @@ -47,7 +46,7 @@ public function testViewFormSelect() public function testViewFormSelectEscaping() { $helper = new Application_View_Helper_ViewFormSelect(); - $helper->setView(new Zend_View()); + $helper->setView(new \Zend_View()); $markup = $helper->viewFormSelect('testName', '1', null, ['Value1', '

Value2

', 'Value3']); diff --git a/tests/library/Application/View/Helper/ViewFormTextareaTest.php b/tests/library/Application/View/Helper/ViewFormTextareaTest.php index 4e9b7ec7b5..4fab915dd9 100644 --- a/tests/library/Application/View/Helper/ViewFormTextareaTest.php +++ b/tests/library/Application/View/Helper/ViewFormTextareaTest.php @@ -37,7 +37,7 @@ class Application_View_Helper_ViewFormTextareaTest extends ControllerTestCase public function testViewFormTextarea() { $helper = new Application_View_Helper_ViewFormTextarea(); - $helper->setView(new Zend_View()); + $helper->setView(new \Zend_View()); $this->assertContains('class="field textarea"', $helper->viewFormTextarea('testName', 'testValue', [ 'id' => '10' diff --git a/tests/library/Application/ZendBasicsTest.php b/tests/library/Application/ZendBasicsTest.php index f884cf25f9..b46edd719c 100644 --- a/tests/library/Application/ZendBasicsTest.php +++ b/tests/library/Application/ZendBasicsTest.php @@ -65,7 +65,7 @@ public function testZendConfigBooleanOption($name, $value, $result) */ public function testZendConfigBooleanOptionLoadedFromIni($name, $value, $result) { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $options = $config->tests->config; $value = $options->$name; diff --git a/tests/library/DoiConfigTest.php b/tests/library/DoiConfigTest.php new file mode 100644 index 0000000000..9367d93bc6 --- /dev/null +++ b/tests/library/DoiConfigTest.php @@ -0,0 +1,51 @@ + + * @copyright Copyright (c) 2021, OPUS 4 development team + * @license http://www.gnu.org/licenses/gpl.html General Public License + */ + +use Opus\Doi\Generator\DoiGeneratorFactory; + +/** + * TODO move to opus4-doi + */ +class DoiConfigTest extends ControllerTestCase +{ + + /** + * Makes sure configuration in application.ini specifies an existing class. + */ + public function testDoiConfig() + { + $generator = DoiGeneratorFactory::create(); + + $this->assertNotNull($generator); + } +} diff --git a/tests/library/Mock/Opus/Document.php b/tests/library/Mock/Opus/Document.php index ea87d24cd4..e4a0a90f17 100644 --- a/tests/library/Mock/Opus/Document.php +++ b/tests/library/Mock/Opus/Document.php @@ -29,13 +29,14 @@ * @author Jens Schwidder * @copyright Copyright (c) 2008-2012, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id$ */ +use Opus\Document; + /** - * Mock Opus_Document for unit testing. + * Mock Document for unit testing. */ -class Mock_Opus_Document extends Opus_Document +class Mock_Opus_Document extends Document { public function store() diff --git a/tests/modules/ComposerTest.php b/tests/modules/ComposerTest.php new file mode 100644 index 0000000000..aba8c00142 --- /dev/null +++ b/tests/modules/ComposerTest.php @@ -0,0 +1,45 @@ +assertFileExists("$assetsPath/jquery"); + $this->assertFileExists("$assetsPath/jqueryui"); + } +} diff --git a/tests/modules/ControllerTestCaseTest.php b/tests/modules/ControllerTestCaseTest.php index 3eeee0f53d..e08994d7e2 100644 --- a/tests/modules/ControllerTestCaseTest.php +++ b/tests/modules/ControllerTestCaseTest.php @@ -1,5 +1,6 @@ - * @copyright Copyright (c) 2008-2019, OPUS 4 development team + * @copyright Copyright (c) 2008-2022, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ + +use Opus\Document; +use Opus\DocumentFinderInterface; +use Opus\DocumentFinder\DefaultDocumentFinder; +use Opus\Model\NotFoundException; +use Opus\Security\Realm; + class ControllerTestCaseTest extends ControllerTestCase { @@ -51,12 +57,12 @@ public function testLoginAdmin() { $this->enableSecurity(); $this->loginUser('admin', 'adminadmin'); - $realm = Opus_Security_Realm::getInstance(); + $realm = Realm::getInstance(); $this->assertContains( 'administrator', $realm->getRoles(), - Zend_Debug::dump($realm->getRoles(), null, false) + \Zend_Debug::dump($realm->getRoles(), null, false) ); } @@ -68,13 +74,13 @@ public function testLoginAdmin() public function testTearDownDidLogout() { $this->enableSecurity(); - $realm = Opus_Security_Realm::getInstance(); + $realm = Realm::getInstance(); $this->assertNotContains('administrator', $realm->getRoles()); } public function testSetHostname() { - $view = Zend_Registry::get('Opus_View'); + $view = $this->getView(); $this->assertEquals('http://', $view->serverUrl()); @@ -85,7 +91,7 @@ public function testSetHostname() public function testSetBaseUrlNotSet() { - $view = Zend_Registry::get('Opus_View'); + $view = $this->getView(); $this->assertEquals('', $view->baseUrl()); @@ -96,7 +102,7 @@ public function testSetBaseUrlNotSet() public function testSetBaseUrlSet() { - $view = Zend_Registry::get('Opus_View'); + $view = $this->getView(); $this->setBaseUrl('opus4'); @@ -105,32 +111,32 @@ public function testSetBaseUrlSet() /** * Test removing document using identifier. - * - * @expectedException Opus_Model_NotFoundException */ public function testRemoveDocumentById() { - $doc = new Opus_Document(); + $doc = Document::new(); $docId = $doc->store(); $this->removeDocument($docId); - new Opus_Document($docId); + $this->setExpectedException(NotFoundException::class); + + Document::get($docId); } /** * Test removing document using object. - * - * @expectedException Opus_Model_NotFoundException */ public function testRemoveDocument() { - $doc = new Opus_Document(); + $doc = Document::new(); $docId = $doc->store(); $this->removeDocument($doc); - new Opus_Document($docId); + $this->setExpectedException(NotFoundException::class); + + Document::get($docId); } /** @@ -138,7 +144,7 @@ public function testRemoveDocument() */ public function testRemoveDocumentNotStored() { - $doc = new Opus_Document(); + $doc = Document::new(); $this->removeDocument($doc); } @@ -163,17 +169,17 @@ public function testGetTempFile() public function testDisableEnableTranslation() { - $defaultTranslator = Zend_Registry::get('Zend_Translate'); + $defaultTranslator = Application_Translate::getInstance(); $this->assertTrue($defaultTranslator->isTranslated('LastName')); $this->disableTranslation(); - $translator = Zend_Registry::get('Zend_Translate'); + $translator = Application_Translate::getInstance(); $this->assertFalse($translator->isTranslated('LastName')); $this->enableTranslation(); - $translator = Zend_Registry::get('Zend_Translate'); + $translator = Application_Translate::getInstance(); $this->assertTrue($translator->isTranslated('LastName')); $this->assertSame($defaultTranslator, $translator); @@ -193,9 +199,9 @@ public function testGetWorkspacePath() */ public function testGetWorkspacePathNotDefined() { - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'workspacePath' => null - ])); + ]); $this->getWorkspacePath(); } @@ -429,4 +435,11 @@ public function testCopyFiles() $this->assertContains('imprint.de.txt', $files); $this->assertContains('metadata.en.txt', $files); } + + public function testGetDocumentFinder() + { + $finder = $this->getDocumentFinder(); + + $this->assertInstanceOf(DefaultDocumentFinder::class, $finder); + } } diff --git a/tests/modules/LanguageTest.php b/tests/modules/LanguageTest.php index 1e1ffcf050..25e583b4fc 100644 --- a/tests/modules/LanguageTest.php +++ b/tests/modules/LanguageTest.php @@ -76,7 +76,7 @@ public function testSetLanguage() { $this->application->bootstrap('translation'); - $translator = Zend_Registry::get('Zend_Translate'); + $translator = Application_Translate::getInstance(); $this->useGerman(); diff --git a/tests/modules/account/controllers/IndexControllerTest.php b/tests/modules/account/controllers/IndexControllerTest.php index 5b5a88ae6b..7366175b65 100644 --- a/tests/modules/account/controllers/IndexControllerTest.php +++ b/tests/modules/account/controllers/IndexControllerTest.php @@ -27,10 +27,13 @@ * @category Tests * @package Account * @author Jens Schwidder - * @copyright Copyright (c) 2008-2019, OPUS 4 development team + * @copyright Copyright (c) 2008-2021, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Account; +use Opus\Config; + /** * Basic unit tests for account module. * @@ -48,7 +51,7 @@ public function setUp() parent::setUp(); $this->deleteUser('john'); - $this->user = new Opus_Account(); + $this->user = new Account(); $this->user->setLogin('john'); $this->user->setPassword('testpwd'); $this->user->store(); @@ -62,8 +65,8 @@ public function tearDown() private function deleteUser($username) { - $account = Opus_Account::fetchAccountByLogin($username); - if ($account instanceof Opus_Account) { + $account = Account::fetchAccountByLogin($username); + if ($account instanceof Account) { $account->delete(); } } @@ -73,7 +76,7 @@ private function deleteUser($username) */ public function testIndexSuccessAction() { - $config = Zend_Registry::get('Zend_Config'); + $config = Config::get(); $config->account->editOwnAccount = self::CONFIG_VALUE_TRUE; $this->loginUser('admin', 'adminadmin'); @@ -89,7 +92,7 @@ public function testIndexSuccessAction() */ public function testIndexDeniedIfEditAccountDisabledAction() { - $config = Zend_Registry::get('Zend_Config'); + $config = Config::get(); $config->account->editOwnAccount = self::CONFIG_VALUE_FALSE; $this->loginUser('admin', 'adminadmin'); @@ -109,7 +112,7 @@ public function testIndexWithoutLoginAction() public function testChangePasswordFailsOnMissingInputAction() { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $config->account->editOwnAccount = self::CONFIG_VALUE_TRUE; $this->loginUser('john', 'testpwd'); @@ -125,7 +128,7 @@ public function testChangePasswordFailsOnMissingInputAction() $this->assertAction('save'); // Check if change failed... - $account = new Opus_Account(null, null, 'john'); + $account = new Account(null, null, 'john'); $this->assertTrue($account->isPasswordCorrect('testpwd')); $this->assertFalse($account->isPasswordCorrect('newpassword')); @@ -134,7 +137,7 @@ public function testChangePasswordFailsOnMissingInputAction() public function testChangePasswordFailsOnNoMatch() { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $config->account->editOwnAccount = self::CONFIG_VALUE_TRUE; $this->loginUser('john', 'testpwd'); @@ -151,7 +154,7 @@ public function testChangePasswordFailsOnNoMatch() $this->assertAction('save'); // Check if change failed... - $account = new Opus_Account(null, null, 'john'); + $account = new Account(null, null, 'john'); $this->assertTrue($account->isPasswordCorrect('testpwd')); $this->assertFalse($account->isPasswordCorrect('newpassword')); @@ -163,7 +166,7 @@ public function testChangePasswordFailsOnNoMatch() */ public function testChangePasswordSuccess() { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $config->account->editOwnAccount = self::CONFIG_VALUE_TRUE; $this->loginUser('john', 'testpwd'); @@ -181,7 +184,7 @@ public function testChangePasswordSuccess() $this->assertRedirect(); // Check if change succeeded... - $account = new Opus_Account(null, null, 'john'); + $account = new Account(null, null, 'john'); $this->assertTrue($account->isPasswordCorrect('newpassword')); $this->assertNotContains('
    ', $this->getResponse()->getBody()); @@ -192,7 +195,7 @@ public function testChangePasswordSuccess() */ public function testChangePasswordSuccessWithSpecialChars() { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $config->account->editOwnAccount = self::CONFIG_VALUE_TRUE; $this->loginUser('john', 'testpwd'); @@ -210,7 +213,7 @@ public function testChangePasswordSuccessWithSpecialChars() $this->assertRedirect(); // Check if change succeeded... - $account = new Opus_Account(null, null, 'john'); + $account = new Account(null, null, 'john'); $this->assertTrue($account->isPasswordCorrect('new@pwd$%')); $this->assertNotContains('
      ', $this->getResponse()->getBody()); @@ -221,7 +224,7 @@ public function testChangePasswordSuccessWithSpecialChars() */ public function testChangeLoginSuccess() { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $config->account->editOwnAccount = self::CONFIG_VALUE_TRUE; $this->deleteUser('john2'); @@ -240,11 +243,11 @@ public function testChangeLoginSuccess() $this->assertRedirect(); // Check if new user exists (with proper password) and old does not... - $account = Opus_Account::fetchAccountByLogin('john2'); + $account = Account::fetchAccountByLogin('john2'); $this->assertNotNull($account); $this->assertTrue($account->isPasswordCorrect('testpwd')); - $account = Opus_Account::fetchAccountByLogin('john'); + $account = Account::fetchAccountByLogin('john'); $this->assertNull($account); // Delete user 'john2' if we're done... diff --git a/tests/modules/account/forms/AccountTest.php b/tests/modules/account/forms/AccountTest.php index 5f9257c963..df371235e9 100644 --- a/tests/modules/account/forms/AccountTest.php +++ b/tests/modules/account/forms/AccountTest.php @@ -30,6 +30,8 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Account; + /** * Basic unit tests for account form for users. */ @@ -44,10 +46,10 @@ public function setUp() { parent::setUp(); - $account = Opus_Account::fetchAccountByLogin('user'); + $account = Account::fetchAccountByLogin('user'); if (is_null($account)) { - $account = new Opus_Account(); + $account = new Account(); $account->setLogin('user'); $account->setPassword('userpwd'); $account->store(); @@ -107,7 +109,7 @@ public function testChangedLoginNameValidationExistingLoginNameAccount() public function testChangedLoginNameValidationNewLoginName() { $form = new Account_Form_Account(); - $account = new Opus_Account(null, null, 'user'); + $account = new Account(null, null, 'user'); $form->populateFromModel($account); $this->assertNotNull($form); @@ -125,7 +127,7 @@ public function testChangedLoginNameValidationNewLoginName() public function testEditValidationSameAccount() { $form = new Account_Form_Account(); - $account = new Opus_Account(null, null, 'user'); + $account = new Account(null, null, 'user'); $form->populateFromModel($account); // check that form was populated @@ -145,7 +147,7 @@ public function testEditValidationSameAccount() public function testValidationMissmatchedPasswords() { $form = new Account_Form_Account(); - $account = new Opus_Account(null, null, 'user'); + $account = new Account(null, null, 'user'); $form->populateFromModel($account); $postData = [ @@ -166,7 +168,7 @@ public function testValidationMissmatchedPasswords() public function testValidationBadEmail() { $form = new Account_Form_Account(); - $account = new Opus_Account(null, null, 'user'); + $account = new Account(null, null, 'user'); $form->populateFromModel($account); $postData = [ diff --git a/tests/modules/admin/controllers/AccountControllerTest.php b/tests/modules/admin/controllers/AccountControllerTest.php index 6d07b1a1b4..c6175cd83a 100644 --- a/tests/modules/admin/controllers/AccountControllerTest.php +++ b/tests/modules/admin/controllers/AccountControllerTest.php @@ -30,6 +30,8 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Account; + /** * Basic unit tests for the Admin_AccountController class. * @@ -46,8 +48,8 @@ public static function tearDownAfterClass() $accounts = ['wally', 'wally2']; foreach ($accounts as $login) { - $account = Opus_Account::fetchAccountByLogin($login); - if ($account instanceof Opus_Account) { + $account = Account::fetchAccountByLogin($login); + if ($account instanceof Account) { $account->delete(); } } @@ -156,7 +158,7 @@ public function testCreateAction() $this->assertController('account'); $this->assertAction('new'); $this->assertRedirect(); - $this->assertNotNull(new Opus_Account(null, null, 'wally')); + $this->assertNotNull(new Account(null, null, 'wally')); } public function testCreateActionCancel() @@ -201,7 +203,7 @@ public function testCreateActionMissingInput() */ public function testUpdateAction() { - $account = new Opus_Account(null, null, 'wally'); + $account = new Account(null, null, 'wally'); $id = $account->getId(); $this->request ->setMethod('POST') @@ -222,7 +224,7 @@ public function testUpdateAction() $this->assertController('account'); $this->assertAction('edit'); $this->assertRedirect(); - $this->assertNotNull(new Opus_Account(null, null, 'wally2')); + $this->assertNotNull(new Account(null, null, 'wally2')); } public function testUpdateActionCancel() @@ -244,7 +246,7 @@ public function testUpdateActionCancel() */ public function testUpdateActionMissingInput() { - $account = new Opus_Account(null, null, 'wally2'); + $account = new Account(null, null, 'wally2'); $id = $account->getId(); $this->request ->setMethod('POST') @@ -269,7 +271,7 @@ public function testUpdateActionMissingInput() */ public function testUpdateActionChangePassword() { - $account = new Opus_Account(null, null, 'wally2'); + $account = new Account(null, null, 'wally2'); $id = $account->getId(); $this->request ->setMethod('POST') @@ -292,7 +294,7 @@ public function testUpdateActionChangePassword() $this->assertController('account'); $this->assertAction('edit'); $this->assertRedirect(); - $this->assertNotNull(new Opus_Account(null, null, 'wally2')); + $this->assertNotNull(new Account(null, null, 'wally2')); } /** @@ -302,7 +304,7 @@ public function testUpdateActionChangePassword() */ public function testDeleteAction() { - $account = new Opus_Account(null, null, 'wally2'); + $account = new Account(null, null, 'wally2'); $id = $account->getId(); $this->request ->setMethod('POST') @@ -316,13 +318,13 @@ public function testDeleteAction() $this->assertAction('delete'); $this->assertRedirect('/admin/account/index'); - $this->setExpectedException('Opus_Security_Exception'); - $this->assertNull(new Opus_Account(null, null, 'wally2')); + $this->setExpectedException('Opus\Security\SecurityException'); + $this->assertNull(new Account(null, null, 'wally2')); } public function testDeleteActionDeleteSelf() { - $user = new Opus_Account(); + $user = new Account(); $user->setLogin('john'); $user->setPassword('testpwd'); $user->store(); @@ -334,25 +336,25 @@ public function testDeleteActionDeleteSelf() $this->assertAction('delete'); $this->assertRedirect('/admin/account/index'); - $user = new Opus_Account(null, null, 'john'); + $user = new Account(null, null, 'john'); $this->assertNotNull($user); $user->delete(); } public function testDeleteActionDeleteAdmin() { - $user = new Opus_Account(null, null, 'admin'); + $user = new Account(null, null, 'admin'); $this->dispatch('/admin/account/delete/id/' . $user->getId()); $this->assertController('account'); $this->assertAction('delete'); $this->assertRedirect('/admin/account/index'); - $user = new Opus_Account(null, null, 'admin'); + $user = new Account(null, null, 'admin'); $this->assertNotNull($user); } public function testHideDeleteLinkForAdmin() { - $user = new Opus_Account(null, null, 'admin'); + $user = new Account(null, null, 'admin'); $this->dispatch('/admin/account'); $this->assertResponseCode(200); @@ -369,7 +371,7 @@ public function testHideDeleteLinkForCurrentUser() $this->assertResponseCode(200, $this->getResponse()->getBody()); $this->logoutUser(); - $user = new Opus_Account(null, null, 'security4'); + $user = new Account(null, null, 'security4'); $this->assertQueryCount( "a[@href='" . $this->getRequest()->getBaseUrl() diff --git a/tests/modules/admin/controllers/CollectionControllerTest.php b/tests/modules/admin/controllers/CollectionControllerTest.php index 34163b5eba..847dbeb0d1 100644 --- a/tests/modules/admin/controllers/CollectionControllerTest.php +++ b/tests/modules/admin/controllers/CollectionControllerTest.php @@ -32,6 +32,9 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Collection; +use Opus\CollectionRole; + /** * Basic unit tests for the collections controller in admin module. * @@ -52,7 +55,7 @@ public function setUp() { parent::setUp(); - $this->emptyCollectionRole = new Opus_CollectionRole(); + $this->emptyCollectionRole = new CollectionRole(); $this->emptyCollectionRole->setName("test1role"); $this->emptyCollectionRole->setOaiName("test1role"); $this->emptyCollectionRole->setDisplayBrowsing("Name"); @@ -60,7 +63,7 @@ public function setUp() $this->emptyCollectionRole->setPosition(100); $this->emptyCollectionRole->store(); - $this->nonEmptyCollectionRole = new Opus_CollectionRole(); + $this->nonEmptyCollectionRole = new CollectionRole(); $this->nonEmptyCollectionRole->setName("test2role"); $this->nonEmptyCollectionRole->setOaiName("test2role"); $this->nonEmptyCollectionRole->setDisplayBrowsing("Name"); @@ -71,13 +74,13 @@ public function setUp() $this->rootCollection = $this->nonEmptyCollectionRole->addRootCollection(); $this->rootCollection->store(); - $this->collection = new Opus_Collection(); + $this->collection = new Collection(); $this->collection->setName("first collection"); $this->collection->setNumber("123"); $this->rootCollection->addFirstChild($this->collection); $this->collection->store(); - $this->anotherCollection = new Opus_Collection(); + $this->anotherCollection = new Collection(); $this->anotherCollection->setName("last collection"); $this->anotherCollection->setNumber("987"); $this->rootCollection->addLastChild($this->anotherCollection); diff --git a/tests/modules/admin/controllers/CollectionrolesControllerTest.php b/tests/modules/admin/controllers/CollectionrolesControllerTest.php index b245ba2dce..a61aaea7eb 100644 --- a/tests/modules/admin/controllers/CollectionrolesControllerTest.php +++ b/tests/modules/admin/controllers/CollectionrolesControllerTest.php @@ -30,7 +30,12 @@ * @author Jens Schwidder * @copyright Copyright (c) 2008-2019, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * + */ + +use Opus\CollectionRole; +use Opus\Document; + +/** * @covers Admin_CollectionrolesController */ class Admin_CollectionrolesControllerTest extends ControllerTestCase @@ -46,7 +51,7 @@ public function setUp() { parent::setUp(); - $this->emptyCollectionRole = new Opus_CollectionRole(); + $this->emptyCollectionRole = new CollectionRole(); $this->emptyCollectionRole->setName("test1role"); $this->emptyCollectionRole->setOaiName("test1role"); $this->emptyCollectionRole->setDisplayBrowsing("Name"); @@ -54,7 +59,7 @@ public function setUp() $this->emptyCollectionRole->setPosition(100); $this->emptyCollectionRole->store(); - $this->nonEmptyCollectionRole = new Opus_CollectionRole(); + $this->nonEmptyCollectionRole = new CollectionRole(); $this->nonEmptyCollectionRole->setName("test2role"); $this->nonEmptyCollectionRole->setOaiName("test2role"); $this->nonEmptyCollectionRole->setDisplayBrowsing("Name"); @@ -68,7 +73,7 @@ public function setUp() public function tearDown() { - $database = new Opus_Translate_Dao(); + $database = new \Opus\Translate\Dao(); $database->removeAll(); if (! is_null($this->nonEmptyCollectionRole) && ! is_null($this->nonEmptyCollectionRole->getId())) { @@ -236,22 +241,22 @@ public function testDocumentServerDateModifiedNotUpdatedWhenCollectionSortOrderC { // check for expected test data - $collectionRole1 = new Opus_CollectionRole(1); + $collectionRole1 = new CollectionRole(1); $this->assertEquals(1, $collectionRole1->getPosition(), 'Test setup changed'); - $collectionRole2 = new Opus_CollectionRole(2); + $collectionRole2 = new CollectionRole(2); $this->assertEquals(2, $collectionRole2->getPosition(), 'Test setup changed'); - $docfinder = new Opus_DocumentFinder(); + $docfinder = $this->getDocumentFinder(); $docfinder->setCollectionRoleId(2); - $collectionRoleDocs = $docfinder->ids(); + $collectionRoleDocs = $docfinder->getIds(); $this->assertTrue(in_array(146, $collectionRoleDocs), 'Test setup changed'); // test if server_date_modified is altered - $docBefore = new Opus_Document(146); + $docBefore = Document::get(146); $this->dispatch('/admin/collectionroles/move/roleid/1/pos/2'); - $docAfter = new Opus_Document(146); + $docAfter = Document::get(146); // revert change in test data $this->resetRequest(); @@ -271,11 +276,11 @@ public function testCreateAction() { $this->useEnglish(); - $dao = new Opus_Translate_Dao(); + $dao = new \Opus\Translate\Dao(); $dao->remove('default_collection_role_CreateTestColName'); - $roles = Opus_CollectionRole::fetchAll(); + $roles = CollectionRole::fetchAll(); $this->assertEquals(22, count($roles)); @@ -307,7 +312,7 @@ public function testCreateAction() $this->dispatch('/admin/collectionroles/create'); - $roles = Opus_CollectionRole::fetchAll(); + $roles = CollectionRole::fetchAll(); $this->assertEquals(count($roleIds) + 1, count($roles)); // neue Collection wurde erzeugt @@ -351,12 +356,12 @@ public function testCreateActionForEdit() { $this->useEnglish(); - $dao = new Opus_Translate_Dao(); + $dao = new \Opus\Translate\Dao(); $dao->remove('default_collection_role_ModifiedName'); - $roles = Opus_CollectionRole::fetchAll(); + $roles = CollectionRole::fetchAll(); - $role = new Opus_CollectionRole(); + $role = new CollectionRole(); $role->setName('EditTestName'); $role->setOaiName('EditTestOaiName'); $role->setDisplayBrowsing('Name'); @@ -394,9 +399,9 @@ public function testCreateActionForEdit() $this->dispatch('/admin/collectionroles/create'); // TODO if assertion fails newly created role is not removed (cleanup) - $this->assertEquals(count($roles) + 1, count(Opus_CollectionRole::fetchAll())); // keine neue Collection + $this->assertEquals(count($roles) + 1, count(CollectionRole::fetchAll())); // keine neue Collection - $role = new Opus_CollectionRole($roleId); + $role = new CollectionRole($roleId); $role->delete(); @@ -431,12 +436,12 @@ public function testCreateActionForEditCancel() $this->useEnglish(); - $dao = new Opus_Translate_Dao(); + $dao = new \Opus\Translate\Dao(); $dao->remove('default_collection_role_ModifiedName'); - $roles = Opus_CollectionRole::fetchAll(); + $roles = CollectionRole::fetchAll(); - $role = new Opus_CollectionRole(); + $role = new CollectionRole(); $role->setName('EditTestName'); $role->setOaiName('EditTestOaiName'); $role->setDisplayBrowsing('Name'); @@ -474,9 +479,9 @@ public function testCreateActionForEditCancel() $this->dispatch('/admin/collectionroles/create'); // TODO if assertion fails newly created role is not removed (cleanup) - $this->assertEquals(count($roles) + 1, count(Opus_CollectionRole::fetchAll())); // keine neue Collection + $this->assertEquals(count($roles) + 1, count(CollectionRole::fetchAll())); // keine neue Collection - $role = new Opus_CollectionRole($roleId); + $role = new CollectionRole($roleId); $role->delete(); @@ -505,7 +510,7 @@ public function testCollectionRoleNameChangeModifiesTranslationKey() $oldName = 'TestCollectionRole'; $newName = 'NewNameForCollectionRole'; - $role = new Opus_CollectionRole(); + $role = new CollectionRole(); $role->setName($oldName); $role->setOaiName('oaiTestRole'); $roleId = $role->store(); diff --git a/tests/modules/admin/controllers/DnbinstituteControllerTest.php b/tests/modules/admin/controllers/DnbinstituteControllerTest.php index c6b0791606..10a2457520 100644 --- a/tests/modules/admin/controllers/DnbinstituteControllerTest.php +++ b/tests/modules/admin/controllers/DnbinstituteControllerTest.php @@ -31,6 +31,10 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Account; +use Opus\DnbInstitute; +use Opus\UserRole; + /** * Class Admin_DnbinstituteControllerTest * @@ -55,9 +59,9 @@ public function setUp() public function tearDown() { if (isset($this->roleId) && isset($this->userId)) { - $testRole = new Opus_UserRole($this->roleId); + $testRole = new UserRole($this->roleId); $testRole->delete(); - $userAccount = new Opus_Account($this->userId); + $userAccount = new Account($this->userId); $userAccount->delete(); } @@ -70,12 +74,12 @@ public function tearDown() public function getModels() { - return Opus_DnbInstitute::getAll(); + return DnbInstitute::getAll(); } public function createNewModel() { - $model = new Opus_DnbInstitute(); + $model = new DnbInstitute(); $model->setName('TestName'); $model->setCity('TestCity'); @@ -91,7 +95,7 @@ public function createNewModel() public function getModel($identifier) { - return new Opus_DnbInstitute($identifier); + return new DnbInstitute($identifier); } private function verifyShow() @@ -183,7 +187,7 @@ public function testNewActionCancel() $this->assertEquals( $modelCount, - count(Opus_DnbInstitute::getAll()), + count(DnbInstitute::getAll()), 'Es sollte keine neue Sprache geben.' ); } @@ -269,7 +273,7 @@ public function testDeleteActionShowForm() { $this->useEnglish(); - $institute = new Opus_DnbInstitute(); + $institute = new DnbInstitute(); $institute->updateFromArray([ 'Name' => 'Delete Test Institute', @@ -293,13 +297,13 @@ public function testDeleteActionShowForm() */ public function testUserAccessToInstituteWithInstituteRights() { - $testRole = new Opus_UserRole(); + $testRole = new UserRole(); $testRole->setName('TestRole'); $testRole->appendAccessModule('admin'); $testRole->appendAccessModule('resource_institutions'); $this->roleId = $testRole->store(); - $userAccount = new Opus_Account(); + $userAccount = new Account(); $userAccount->setLogin('role_tester') ->setPassword('role_tester'); $userAccount->setRole($testRole); @@ -321,13 +325,13 @@ public function testUserAccessToInstituteWithInstituteRights() */ public function testUserAccessToInstituteWithoutInstituteRights() { - $testRole = new Opus_UserRole(); + $testRole = new UserRole(); $testRole->setName('TestRole'); $testRole->appendAccessModule('admin'); $testRole->appendAccessModule('resource_languages'); $this->roleId = $testRole->store(); - $userAccount = new Opus_Account(); + $userAccount = new Account(); $userAccount->setLogin('role_tester') ->setPassword('role_tester'); $userAccount->setRole($testRole); @@ -350,13 +354,13 @@ public function testUserAccessToInstituteWithoutInstituteRights() */ public function testUserAccessToInstituteWithInstituteRightsRegression3245() { - $testRole = new Opus_UserRole(); + $testRole = new UserRole(); $testRole->setName('TestRole'); $testRole->appendAccessModule('admin'); $testRole->appendAccessModule('resource_institutions'); $this->roleId = $testRole->store(); - $userAccount = new Opus_Account(); + $userAccount = new Account(); $userAccount->setLogin('role_tester') ->setPassword('role_tester'); $userAccount->setRole($testRole); diff --git a/tests/modules/admin/controllers/DocumentControllerTest.php b/tests/modules/admin/controllers/DocumentControllerTest.php index 5f5f1306c1..fef38b8e95 100644 --- a/tests/modules/admin/controllers/DocumentControllerTest.php +++ b/tests/modules/admin/controllers/DocumentControllerTest.php @@ -28,10 +28,17 @@ * @author Jens Schwidder * @author Michael Lang * @author Maximilian Salomon - * @copyright Copyright (c) 2008-2020, OPUS 4 development team + * @copyright Copyright (c) 2008-2021, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\CollectionRole; +use Opus\Date; +use Opus\Log; +use Opus\Note; +use Opus\Person; +use Opus\Title; + /** * Unit tests for Admin_DocumentController. * @@ -87,10 +94,10 @@ public function testWarningDisplayingDateOfBirth() { $doc = $this->createTestDocument(); - $person = new Opus_Person(); + $person = new Person(); $person->setFirstName("Johnny"); $person->setLastName("Test"); - $dateOfBirth = new Opus_Date(new Zend_Date('1.1.2010', 'dd/MM/yyyy')); + $dateOfBirth = new Date(new \Zend_Date('1.1.2010', 'dd/MM/yyyy')); $person->setDateOfBirth($dateOfBirth); $doc->addPersonAuthor($person); @@ -149,7 +156,7 @@ public function testPreserveNewlinesForAbstract() $doc = $this->createTestDocument(); $doc->setLanguage("eng"); - $abstract = new Opus_Title(); + $abstract = new Title(); $abstract->setLanguage("eng"); $abstract->setValue("foo\nbar\n\nbaz"); $doc->addTitleAbstract($abstract); @@ -171,7 +178,7 @@ public function testPreserveNewlinesForNote() $doc->setLanguage("eng"); $doc->setServerState("published"); - $note = new Opus_Note(); + $note = new Note(); $note->setMessage("foo\nbar\n\nbaz"); $note->setVisibility("public"); $doc->addNote($note); @@ -189,7 +196,7 @@ public function testPreserveNewlinesForNote() public function testDisplayCollectionNumberAndNameOnOverviewPageForDDCCollection() { $this->markTestIncomplete("Muss fuer OPUS 4.4 angepasst werden."); // TODO OPUSVIER-2794 - $role = new Opus_CollectionRole(2); + $role = new CollectionRole(2); $displayBrowsing = $role->getDisplayBrowsing(); $role->setDisplayBrowsing('Name'); $role->store(); @@ -207,7 +214,7 @@ public function testDisplayCollectionNumberAndNameOnOverviewPageForDDCCollection public function testDisplayCollectionNumberAndNameOnAssignmentPageForDDCCollection() { $this->markTestIncomplete("Muss fuer OPUS 4.4 angepasst werden."); // TODO OPUSVIER-2794 - $role = new Opus_CollectionRole(2); + $role = new CollectionRole(2); $displayBrowsing = $role->getDisplayBrowsing(); $role->setDisplayBrowsing('Name'); $role->store(); @@ -943,9 +950,9 @@ public function testShowDocumentWithFilesWithLanguageNull() public function testUnableToTranslateForMetadataView() { $logger = new MockLogger(); - Zend_Registry::set('Zend_Log', $logger); + Log::set($logger); - $adapter = Zend_Registry::get('Zend_Translate')->getAdapter(); + $adapter = Application_Translate::getInstance()->getAdapter(); $options = $adapter->getOptions(); $options['log'] = $logger; $adapter->setOptions($options); @@ -962,7 +969,7 @@ public function testUnableToTranslateForMetadataView() } } - $output = Zend_Debug::dump($failedTranslations, null, false); + $output = \Zend_Debug::dump($failedTranslations, null, false); // currently only two messages cannot be avoided $this->assertLessThanOrEqual(2, count($failedTranslations), $output); @@ -971,9 +978,9 @@ public function testUnableToTranslateForMetadataView() public function testUnableToTranslateForEditForm() { $logger = new MockLogger(); - Zend_Registry::set('Zend_Log', $logger); + Log::set($logger); - $adapter = Zend_Registry::get('Zend_Translate')->getAdapter(); + $adapter = Application_Translate::getInstance()->getAdapter(); $options = $adapter->getOptions(); $options['log'] = $logger; $adapter->setOptions($options); @@ -990,7 +997,7 @@ public function testUnableToTranslateForEditForm() } } - $output = Zend_Debug::dump($failedTranslations, null, false); + $output = \Zend_Debug::dump($failedTranslations, null, false); // currently only two messages cannot be avoided $this->assertLessThanOrEqual(2, count($failedTranslations), $output); diff --git a/tests/modules/admin/controllers/DocumentsControllerTest.php b/tests/modules/admin/controllers/DocumentsControllerTest.php index d858a32750..88820f30c8 100644 --- a/tests/modules/admin/controllers/DocumentsControllerTest.php +++ b/tests/modules/admin/controllers/DocumentsControllerTest.php @@ -30,6 +30,9 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\CollectionRole; +use Opus\Person; + /** * Basic unit test for the documents controller in the admin module. * @@ -68,7 +71,7 @@ public function testCollectionRoleNameGetsTranslatedForDDC() */ public function testCollectionRoleNameGetsTranslatedForUserCollection() { - $cr = new Opus_CollectionRole(); + $cr = new CollectionRole(); $cr->setName('foo'); $cr->setOaiName('foo'); $cr->store(); @@ -82,7 +85,7 @@ public function testCollectionRoleNameGetsTranslatedForUserCollection() public function testShowAllDocsForDDCCollection() { - $role = new Opus_CollectionRole(2); + $role = new CollectionRole(2); $displayBrowsing = $role->getDisplayBrowsing(); $role->setDisplayBrowsing('Name'); $role->store(); @@ -99,7 +102,7 @@ public function testShowAllDocsForDDCCollection() public function testShowAllDocsForBklCollection() { - $role = new Opus_CollectionRole(7); + $role = new CollectionRole(7); $displayBrowsing = $role->getDisplayBrowsing(); $role->setDisplayBrowsing('Name'); $role->store(); @@ -144,10 +147,10 @@ public function testSelectHitsPerPage() public function testShowAllHits() { - $docFinder = new Opus_DocumentFinder(); + $docFinder = $this->getDocumentFinder(); $docFinder->setServerState('unpublished'); - $unpublishedDocs = $docFinder->count(); + $unpublishedDocs = $docFinder->getCount(); $this->dispatch('/admin/documents/index/state/unpublished/hitsperpage/all'); $this->assertQueryCount('span.title', $unpublishedDocs); @@ -155,15 +158,13 @@ public function testShowAllHits() public function testHitsPerPageBadParameter() { - $docFinder = new Opus_DocumentFinder(); - $this->dispatch('/admin/documents/index/state/unpublished/hitsperpage/dummy'); $this->assertQueryCount('span.title', 10); // default } public function testConfigureDefaultHitsPerPage() { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $config->admin->documents->maxDocsDefault = '7'; $this->dispatch('/admin/documents'); @@ -172,7 +173,7 @@ public function testConfigureDefaultHitsPerPage() public function testConfigureHitsPerPageOptions() { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $config->admin->documents->maxDocsOptions = "20,60,all"; $this->dispatch('/admin/documents'); @@ -205,7 +206,7 @@ public function testLinkForStateAuditedPresent() public function testShowAuthorFilter() { - $person = new Opus_Person(); + $person = new Person(); $person->setLastName('Test'); $person->setFirstName('Justa'); $person->setIdentifierOrcid('0000-0000-0000-0001'); diff --git a/tests/modules/admin/controllers/EnrichmentkeyControllerTest.php b/tests/modules/admin/controllers/EnrichmentkeyControllerTest.php index cc2b6e32a0..c0f3ca0320 100644 --- a/tests/modules/admin/controllers/EnrichmentkeyControllerTest.php +++ b/tests/modules/admin/controllers/EnrichmentkeyControllerTest.php @@ -33,6 +33,12 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Document; +use Opus\Enrichment; +use Opus\EnrichmentKey; +use Opus\Enrichment\AbstractType; +use Opus\Model\NotFoundException; + /** * Basic unit tests for Admin_EnrichmentkeyController class. * @@ -44,7 +50,7 @@ class Admin_EnrichmentkeyControllerTest extends CrudControllerTestCase protected $additionalResources = 'all'; /** - * @var all enrichment keys + * @var EnrichmentKey[] All enrichment keys */ private $allEnrichmentKeys = []; @@ -52,26 +58,26 @@ public function setUp() { $this->setController('enrichmentkey'); parent::setUp(); - foreach (Opus_EnrichmentKey::getAll() as $value) { + foreach (EnrichmentKey::getAll() as $value) { array_push($this->allEnrichmentKeys, $value->getDisplayName()); } } public function getModels() { - return Opus_EnrichmentKey::getAll(); + return EnrichmentKey::getAll(); } public function createNewModel() { - $model = new Opus_EnrichmentKey(); + $model = new EnrichmentKey(); $model->setName('TestEnrichmentKey'); return $model->store(); } public function getModel($identifier) { - return new Opus_EnrichmentKey($identifier); + return new EnrichmentKey($identifier); } /** @@ -121,7 +127,7 @@ public function testNewActionSave() $this->assertRedirectRegex('/^\/admin\/enrichmentkey/'); $this->verifyFlashMessage('controller_crud_save_success', self::MESSAGE_LEVEL_NOTICE); - $enrichmentKey = new Opus_EnrichmentKey('MyTestEnrichment'); + $enrichmentKey = new EnrichmentKey('MyTestEnrichment'); $this->assertNotNull($enrichmentKey); $this->assertEquals('MyTestEnrichment', $enrichmentKey->getName()); $this->assertNull($enrichmentKey->getOptions()); @@ -147,7 +153,7 @@ public function testNewActionSaveEnrichmentKeyWithTypeOptionsAndStrictValidation $this->assertRedirectRegex('/^\/admin\/enrichmentkey/'); $this->verifyFlashMessage('controller_crud_save_success', self::MESSAGE_LEVEL_NOTICE); - $enrichmentKey = new Opus_EnrichmentKey('MyTestEnrichment'); + $enrichmentKey = new EnrichmentKey('MyTestEnrichment'); $this->assertNotNull($enrichmentKey); $this->assertEquals('MyTestEnrichment', $enrichmentKey->getName()); $this->assertEquals('RegexType', $enrichmentKey->getType()); @@ -174,7 +180,7 @@ public function testNewActionSaveEnrichmentKeyWithTypeOptionsAndNoValidation() $this->assertRedirectRegex('/^\/admin\/enrichmentkey/'); $this->verifyFlashMessage('controller_crud_save_success', self::MESSAGE_LEVEL_NOTICE); - $enrichmentKey = new Opus_EnrichmentKey('MyTestEnrichment'); + $enrichmentKey = new EnrichmentKey('MyTestEnrichment'); $this->assertNotNull($enrichmentKey); $this->assertEquals('MyTestEnrichment', $enrichmentKey->getName()); $this->assertEquals('RegexType', $enrichmentKey->getType()); @@ -198,7 +204,7 @@ public function testNewActionSaveMissingEnrichmentType() $this->assertRedirectRegex('/^\/admin\/enrichmentkey/'); $this->verifyFlashMessage('controller_crud_save_success', self::MESSAGE_LEVEL_NOTICE); - $enrichmentKey = new Opus_EnrichmentKey('MyTestEnrichment'); + $enrichmentKey = new EnrichmentKey('MyTestEnrichment'); $this->assertNotNull($enrichmentKey); $this->assertEquals('MyTestEnrichment', $enrichmentKey->getName()); $this->assertNull($enrichmentKey->getOptions()); @@ -222,7 +228,7 @@ public function testNewActionSaveEmptyEnrichmentType() $this->assertRedirectRegex('/^\/admin\/enrichmentkey/'); $this->verifyFlashMessage('controller_crud_save_success', self::MESSAGE_LEVEL_NOTICE); - $enrichmentKey = new Opus_EnrichmentKey('MyTestEnrichment'); + $enrichmentKey = new EnrichmentKey('MyTestEnrichment'); $this->assertNotNull($enrichmentKey); $this->assertEquals('MyTestEnrichment', $enrichmentKey->getName()); $this->assertNull($enrichmentKey->getOptions()); @@ -247,7 +253,7 @@ public function testNewActionSaveUnknownEnrichmentType() $this->assertResponseCode(200); $this->assertXpath('//div[@id = "admin_enrichmentkey_type-element"]/ul[@class="errors"]'); - $this->assertNull(Opus_EnrichmentKey::fetchByName('MyTestEnrichment')); + $this->assertNull(EnrichmentKey::fetchByName('MyTestEnrichment')); } public function testNewActionTranslationsEmpty() @@ -279,7 +285,7 @@ public function testNewActionCancel() $this->assertRedirectTo('/admin/enrichmentkey', 'Should be a redirect to index action.'); - $this->assertEquals($modelCount, count(Opus_EnrichmentKey::getAll()), 'There should be no new enrichment.'); + $this->assertEquals($modelCount, count(EnrichmentKey::getAll()), 'There should be no new enrichment.'); } public function testNewActionSaveForExistingEnrichment() @@ -321,7 +327,7 @@ public function testEditActionShowFormForUnprotectedEnrichmentKey($enrichmentKey public function testEditActionShowFormForProtectedEnrichmentKey() { $protectedEnrichmentKeyName = 'ClassRvk'; - $this->assertNotNull(new Opus_EnrichmentKey($protectedEnrichmentKeyName)); + $this->assertNotNull(new EnrichmentKey($protectedEnrichmentKeyName)); $this->dispatch($this->getControllerPath() . '/edit/id/' . $protectedEnrichmentKeyName); @@ -329,19 +335,15 @@ public function testEditActionShowFormForProtectedEnrichmentKey() $this->assertRedirectTo($this->getControllerPath()); $this->verifyFlashMessage('controller_crud_model_not_modifiable', self::MESSAGE_LEVEL_FAILURE); - $enrichmentKey = new Opus_EnrichmentKey($protectedEnrichmentKeyName); + $enrichmentKey = new EnrichmentKey($protectedEnrichmentKeyName); $this->assertEquals($protectedEnrichmentKeyName, $enrichmentKey->getName()); } - /** - * @expectedException Opus_Model_NotFoundException - * @expectedExceptionMessage No Opus_Db_EnrichmentKeys with id MyTestEnrichment in database. - */ public function testEditActionSave() { $this->createsModels = true; - $enrichmentKey = new Opus_EnrichmentKey(); + $enrichmentKey = new EnrichmentKey(); $enrichmentKey->setName('MyTestEnrichment'); $enrichmentKey->setType('TextType'); $enrichmentKey->store(); @@ -359,25 +361,26 @@ public function testEditActionSave() $this->assertRedirectTo($this->getControllerPath()); $this->verifyFlashMessage('controller_crud_save_success', self::MESSAGE_LEVEL_NOTICE); - $enrichmentKey = new Opus_EnrichmentKey('MyTestEnrichmentModified'); + $enrichmentKey = new EnrichmentKey('MyTestEnrichmentModified'); $this->assertNotNull($enrichmentKey); $this->assertEquals('MyTestEnrichmentModified', $enrichmentKey->getName()); $this->assertEquals('RegexType', $enrichmentKey->getType()); $this->assertEquals(json_encode(["regex" => "^.*$", "validation" => "strict"]), $enrichmentKey->getOptions()); - new Opus_EnrichmentKey('MyTestEnrichment'); + $this->setExpectedException( + NotFoundException::class, + 'No Opus\Db\EnrichmentKeys with id MyTestEnrichment in database.' + ); + + new EnrichmentKey('MyTestEnrichment'); $this->fail('Previous statement should have thrown exception.'); } - /** - * @expectedException Opus_Model_NotFoundException - * @expectedExceptionMessage No Opus_Db_EnrichmentKeys with id ClassRvkModified in database. - */ public function testEditActionSaveForProtectedEnrichment() { $protectedEnrichmentKeyName = 'ClassRvk'; - $this->assertNotNull(new Opus_EnrichmentKey($protectedEnrichmentKeyName)); + $this->assertNotNull(new EnrichmentKey($protectedEnrichmentKeyName)); $this->getRequest()->setMethod('POST')->setPost([ 'Id' => $protectedEnrichmentKeyName, @@ -394,10 +397,15 @@ public function testEditActionSaveForProtectedEnrichment() $this->assertRedirectTo($this->getControllerPath()); $this->verifyFlashMessage('controller_crud_model_not_modifiable', self::MESSAGE_LEVEL_FAILURE); - $enrichmentKey = new Opus_EnrichmentKey($protectedEnrichmentKeyName); + $enrichmentKey = new EnrichmentKey($protectedEnrichmentKeyName); $this->assertEquals($protectedEnrichmentKeyName, $enrichmentKey->getName()); - new Opus_EnrichmentKey("${protectedEnrichmentKeyName}Modified"); + $this->setExpectedException( + NotFoundException::class, + 'No Opus\Db\EnrichmentKeys with id ClassRvkModified in database.' + ); + + new EnrichmentKey("${protectedEnrichmentKeyName}Modified"); $this->fail('Previous statement should have thrown exception.'); } @@ -405,7 +413,7 @@ public function testEditActionSaveWithoutEnrichmentType() { $this->createsModels = true; - $enrichmentKey = new Opus_EnrichmentKey(); + $enrichmentKey = new EnrichmentKey(); $enrichmentKey->setName('MyTestEnrichment'); $enrichmentKey->setType('TextType'); $enrichmentKey->store(); @@ -426,7 +434,7 @@ public function testEditActionSaveWithEmptyEnrichmentType() { $this->createsModels = true; - $enrichmentKey = new Opus_EnrichmentKey(); + $enrichmentKey = new EnrichmentKey(); $enrichmentKey->setName('MyTestEnrichment'); $enrichmentKey->setType('TextType'); $enrichmentKey->store(); @@ -448,7 +456,7 @@ public function testEditActionSaveWithExistingEnrichmentType() { $this->createsModels = true; - $enrichmentKey = new Opus_EnrichmentKey(); + $enrichmentKey = new EnrichmentKey(); $enrichmentKey->setName('MyTestEnrichment'); $enrichmentKey->setType('TextType'); $enrichmentKey->store(); @@ -463,7 +471,7 @@ public function testEditActionSaveWithExistingEnrichmentType() $this->dispatch($this->getControllerPath() . '/edit'); $this->assertResponseCode(302); - $enrichmentKey = Opus_EnrichmentKey::fetchByName('MyTestEnrichment'); + $enrichmentKey = EnrichmentKey::fetchByName('MyTestEnrichment'); $this->assertEquals('BooleanType', $enrichmentKey->getEnrichmentType()->getName()); } @@ -471,7 +479,7 @@ public function testEditActionSaveWithUnknownEnrichmentType() { $this->createsModels = true; - $enrichmentKey = new Opus_EnrichmentKey(); + $enrichmentKey = new EnrichmentKey(); $enrichmentKey->setName('MyTestEnrichment'); $enrichmentKey->store(); @@ -485,19 +493,15 @@ public function testEditActionSaveWithUnknownEnrichmentType() $this->dispatch($this->getControllerPath() . '/edit'); $this->assertResponseCode(200); - $this->assertNull(Opus_EnrichmentKey::fetchByName('MyTestEnrichmentModified')); - $this->assertNotNull(Opus_EnrichmentKey::fetchByName('MyTestEnrichment')); + $this->assertNull(EnrichmentKey::fetchByName('MyTestEnrichmentModified')); + $this->assertNotNull(EnrichmentKey::fetchByName('MyTestEnrichment')); } - /** - * @expectedException Opus_Model_NotFoundException - * @expectedExceptionMessage No Opus_Db_EnrichmentKeys with id MyTestEnrichmentModified in database. - */ public function testEditActionCancel() { $this->createsModels = true; - $enrichmentKey = new Opus_EnrichmentKey(); + $enrichmentKey = new EnrichmentKey(); $enrichmentKey->setName('MyTestEnrichment'); $enrichmentKey->setType('TextType'); $enrichmentKey->store(); @@ -514,26 +518,27 @@ public function testEditActionCancel() $this->dispatch($this->getControllerPath() . '/edit'); $this->assertRedirectTo($this->getControllerPath()); - $enrichmentKey = new Opus_EnrichmentKey('MyTestEnrichment'); + $enrichmentKey = new EnrichmentKey('MyTestEnrichment'); $this->assertNotNull($enrichmentKey); $this->assertEquals('MyTestEnrichment', $enrichmentKey->getName()); $this->assertEquals('TextType', $enrichmentKey->getType()); $this->assertNull($enrichmentKey->getOptions()); - new Opus_EnrichmentKey('MyTestEnrichmentModified'); + $this->setExpectedException( + NotFoundException::class, + 'No Opus\Db\EnrichmentKeys with id MyTestEnrichmentModified in database.' + ); + + new EnrichmentKey('MyTestEnrichmentModified'); $this->fail('Previous statement should have thrown exception.'); } - /** - * @expectedException Opus_Model_NotFoundException - * @expectedExceptionMessage No Opus_Db_EnrichmentKeys with id ClassRvkModified in database. - */ public function testEditActionCancelForProtectedEnrichment() { $protectedEnrichmentKeyName = 'ClassRvk'; - $this->assertNotNull(new Opus_EnrichmentKey($protectedEnrichmentKeyName)); + $this->assertNotNull(new EnrichmentKey($protectedEnrichmentKeyName)); $this->getRequest()->setMethod('POST')->setPost([ 'Id' => $protectedEnrichmentKeyName, @@ -546,10 +551,15 @@ public function testEditActionCancelForProtectedEnrichment() $this->assertRedirect(); $this->assertRedirectTo($this->getControllerPath()); - $enrichmentKey = new Opus_EnrichmentKey($protectedEnrichmentKeyName); + $enrichmentKey = new EnrichmentKey($protectedEnrichmentKeyName); $this->assertEquals($protectedEnrichmentKeyName, $enrichmentKey->getName()); - new Opus_EnrichmentKey("${protectedEnrichmentKeyName}Modified"); + $this->setExpectedException( + NotFoundException::class, + 'No Opus\Db\EnrichmentKeys with id ClassRvkModified in database.' + ); + + new EnrichmentKey("${protectedEnrichmentKeyName}Modified"); $this->fail('Previous statement should have thrown exception.'); } @@ -567,7 +577,7 @@ public function testDeleteActionShowFormForUnprotectedEnrichmentKey($enrichmentK $this->assertQuery('input#ConfirmYes'); $this->assertQuery('input#ConfirmNo'); - $enrichmentKey = new Opus_EnrichmentKey($enrichmentKeyName); + $enrichmentKey = new EnrichmentKey($enrichmentKeyName); $this->assertNotNull($enrichmentKey); $this->assertEquals($enrichmentKeyName, $enrichmentKey->getName()); @@ -576,7 +586,7 @@ public function testDeleteActionShowFormForUnprotectedEnrichmentKey($enrichmentK public function testDeleteActionShowFormForProtectedEnrichmentKey() { $protectedEnrichmentKeyName = 'ClassRvk'; - $this->assertNotNull(new Opus_EnrichmentKey($protectedEnrichmentKeyName)); + $this->assertNotNull(new EnrichmentKey($protectedEnrichmentKeyName)); $this->dispatch($this->getControllerPath() . '/delete/id/' . $protectedEnrichmentKeyName); @@ -584,14 +594,14 @@ public function testDeleteActionShowFormForProtectedEnrichmentKey() $this->assertRedirectTo($this->getControllerPath()); $this->verifyFlashMessage('controller_crud_model_cannot_delete', self::MESSAGE_LEVEL_FAILURE); - $enrichmentKey = new Opus_EnrichmentKey($protectedEnrichmentKeyName); + $enrichmentKey = new EnrichmentKey($protectedEnrichmentKeyName); $this->assertEquals($protectedEnrichmentKeyName, $enrichmentKey->getName()); } public function testRemoveFromDocsShowFormForProtectedEnrichment() { $protectedEnrichmentKeyName = 'ClassRvk'; - $this->assertNotNull(new Opus_EnrichmentKey($protectedEnrichmentKeyName)); + $this->assertNotNull(new EnrichmentKey($protectedEnrichmentKeyName)); $this->dispatch($this->getControllerPath() . '/removeFromDocs/id/' . $protectedEnrichmentKeyName); @@ -599,14 +609,14 @@ public function testRemoveFromDocsShowFormForProtectedEnrichment() $this->assertRedirectTo($this->getControllerPath()); $this->verifyFlashMessage('controller_crud_model_cannot_delete', self::MESSAGE_LEVEL_FAILURE); - $enrichmentKey = new Opus_EnrichmentKey($protectedEnrichmentKeyName); + $enrichmentKey = new EnrichmentKey($protectedEnrichmentKeyName); $this->assertEquals($protectedEnrichmentKeyName, $enrichmentKey->getName()); } public function testRemoveFromDocsShowFormForUnprotectedEnrichment() { $enrichmentKeyName = 'Audience'; // wird von einem Dokument verwendet - $enrichmentKey = new Opus_EnrichmentKey($enrichmentKeyName); + $enrichmentKey = new EnrichmentKey($enrichmentKeyName); $this->assertEquals($enrichmentKeyName, $enrichmentKey->getName()); $this->useEnglish(); @@ -618,14 +628,14 @@ public function testRemoveFromDocsShowFormForUnprotectedEnrichment() $this->assertQuery('input#ConfirmYes'); $this->assertQuery('input#ConfirmNo'); - $enrichmentKey = new Opus_EnrichmentKey($enrichmentKeyName); + $enrichmentKey = new EnrichmentKey($enrichmentKeyName); $this->assertEquals($enrichmentKeyName, $enrichmentKey->getName()); } public function testRemoveFromDocsForProtectedEnrichmentKey() { $protectedEnrichmentKeyName = 'ClassRvk'; - $this->assertNotNull(new Opus_EnrichmentKey($protectedEnrichmentKeyName)); + $this->assertNotNull(new EnrichmentKey($protectedEnrichmentKeyName)); $post = [ 'Id' => $protectedEnrichmentKeyName, @@ -639,7 +649,7 @@ public function testRemoveFromDocsForProtectedEnrichmentKey() $this->assertRedirectTo($this->getControllerPath()); $this->verifyFlashMessage('controller_crud_model_cannot_delete', self::MESSAGE_LEVEL_FAILURE); - $enrichmentKey = new Opus_EnrichmentKey($protectedEnrichmentKeyName); + $enrichmentKey = new EnrichmentKey($protectedEnrichmentKeyName); $this->assertEquals($protectedEnrichmentKeyName, $enrichmentKey->getName()); } @@ -648,23 +658,23 @@ public function testRemoveFromDocsForUnprotectedEnrichmentKey() $enrichmentKeyName = 'testRemoveFromDocsForUnprotectedEnrichmentKey'; $this->createsModels = true; // damit am Ende des Test ein Cleanup durchgeführt wird (neu angelegter EK wird gelöscht) - $enrichmentKey = new Opus_EnrichmentKey(); + $enrichmentKey = new EnrichmentKey(); $enrichmentKey->setName($enrichmentKeyName); $enrichmentKey->setType('TextType'); $enrichmentKey->store(); - $this->assertContains($enrichmentKeyName, Opus_EnrichmentKey::getAll(true)); + $this->assertContains($enrichmentKeyName, EnrichmentKey::getAll(true)); // assign test document to enrichment key $doc = $this->createTestDocument(); - $enrichment = new Opus_Enrichment(); + $enrichment = new Enrichment(); $enrichment->setKeyName($enrichmentKeyName); $enrichment->setValue('foo'); $doc->addEnrichment($enrichment); $docId = $doc->store(); - $doc = new Opus_Document($docId); + $doc = Document::get($docId); $this->assertCount(1, $doc->getEnrichment()); $this->useEnglish(); @@ -682,10 +692,10 @@ public function testRemoveFromDocsForUnprotectedEnrichmentKey() $this->verifyFlashMessage('controller_crud_delete_success', self::MESSAGE_LEVEL_NOTICE); // EnrichmentKey muss noch vorhanden sein, aber das entsprechende Enrichment im Testdokument wurde gelöscht - $enrichmentKey = new Opus_EnrichmentKey($enrichmentKeyName); + $enrichmentKey = new EnrichmentKey($enrichmentKeyName); $this->assertEquals($enrichmentKeyName, $enrichmentKey->getName()); - $doc = new Opus_Document($docId); + $doc = Document::get($docId); $this->assertCount(0, $doc->getEnrichment()); } @@ -712,7 +722,7 @@ public function testEnrichmentTypeHandlingRoundTrip() $this->assertRedirectRegex('/^\/admin\/enrichmentkey/'); $this->verifyFlashMessage('controller_crud_save_success', self::MESSAGE_LEVEL_NOTICE); - $enrichmentKey = new Opus_EnrichmentKey($enrichmentKeyName); + $enrichmentKey = new EnrichmentKey($enrichmentKeyName); $this->assertNotNull($enrichmentKey); $this->assertEquals($enrichmentKeyName, $enrichmentKey->getName()); $this->assertEquals($post['Type'], $enrichmentKey->getType()); @@ -772,7 +782,7 @@ public function testEnrichmentTypeWithInvalidOptions() $this->assertRedirectRegex('/^\/admin\/enrichmentkey/'); $this->verifyFlashMessage('controller_crud_save_success', self::MESSAGE_LEVEL_NOTICE); - $enrichmentKey = new Opus_EnrichmentKey($enrichmentKeyName); + $enrichmentKey = new EnrichmentKey($enrichmentKeyName); $this->assertNotNull($enrichmentKey); $this->assertEquals($enrichmentKeyName, $enrichmentKey->getName()); $this->assertNull($enrichmentKey->getOptions()); @@ -803,7 +813,7 @@ public function testAllEnrichmentTypesAreAvailableInEditForm() $this->getRequest()->setMethod('GET'); $this->dispatch($this->getControllerPath() . '/new'); - $allEnrichmentTypes = Opus_Enrichment_AbstractType::getAllEnrichmentTypes(false); + $allEnrichmentTypes = AbstractType::getAllEnrichmentTypes(false); $this->assertXpathCount('//select/option', 1 + count($allEnrichmentTypes)); // +1, weil Standardauswahl leer ist $this->assertXpathContentRegex('//select/option[1]', "//"); @@ -829,8 +839,10 @@ public function testProtectedCssClassIsSet() foreach ($protectedKeys as &$value) { if (strpos($response->getBody(), $value) !== false) { // Xpath looks, if value has an protected css-class in enrichmentkeyTable - $this->assertXpathContentContains('//table[@id="enrichmentkeyTable"] - //tr[contains(@class,\'protected\')]', $value); + $this->assertXpathContentContains( + '//table[@id="enrichmentkeyTableUnmanaged"]//tr[contains(@class,\'protected\')]', + $value + ); } } } @@ -842,15 +854,17 @@ public function testProtectedCssClassIsSet() */ public function testUsedCssClassIsSet() { - $usedKeys = Opus_EnrichmentKey::getAllReferenced(); + $usedKeys = EnrichmentKey::getAllReferenced(); $this->dispatch($this->getControllerPath()); $response = $this->getResponse(); $this->checkForBadStringsInHtml($response->getBody()); foreach ($usedKeys as &$value) { if (strpos($response->getBody(), $value) !== false) { // Xpath looks, if value has an used css-class in enrichmentkeyTable - $this->assertXpathContentContains('//table[@id="enrichmentkeyTable"] - //tr[contains(@class,\'used\')]', $value); + $this->assertXpathContentContains( + '//table[@id="enrichmentkeyTableManaged" or @id="enrichmentkeyTableUnmanaged"]//tr[contains(@class,\'used\')]', + $value + ); } } } @@ -870,8 +884,10 @@ public function testProtectedCssClassIsNotSet() foreach ($unprotectedKeys as &$value) { if (strpos($response->getBody(), $value) !== false) { // Xpath looks, if value has an protected css-class in enrichmentkeyTable - $this->assertNotXpathContentContains('//table[@id="enrichmentkeyTable"] - //tr[contains(@class,\'protected\')]', $value); + $this->assertNotXpathContentContains( + '//table[@id="enrichmentkeyTableManaged" or @id="enrichmentkeyTableUnmanaged"]//tr[contains(@class,\'protected\')]', + $value + ); } } } @@ -883,15 +899,17 @@ public function testProtectedCssClassIsNotSet() */ public function testUsedCssClassIsNotSet() { - $unusedKeys = array_diff($this->allEnrichmentKeys, Opus_EnrichmentKey::getAllReferenced()); + $unusedKeys = array_diff($this->allEnrichmentKeys, EnrichmentKey::getAllReferenced()); $this->dispatch($this->getControllerPath()); $response = $this->getResponse(); $this->checkForBadStringsInHtml($response->getBody()); foreach ($unusedKeys as &$value) { if (strpos($response->getBody(), $value) !== false) { // Xpath looks, if value has an unused css-class in enrichmentkeyTable - $this->assertXpathContentContains('//table[@id="enrichmentkeyTable"] - //tr[contains(@class,\'unused\')]', $value); + $this->assertXpathContentContains( + '//table[@id="enrichmentkeyTableManaged" or @id="enrichmentkeyTableUnmanaged"]//tr[contains(@class,\'unused\')]', + $value + ); } } } @@ -908,7 +926,7 @@ public function testInitializedNewFormWithUnregisteredKeyName() { $doc = $this->createTestDocument(); - $enrichment = new Opus_Enrichment(); + $enrichment = new Enrichment(); $enrichment->setKeyName('unregistered'); $enrichment->setValue('value'); @@ -923,13 +941,13 @@ public function testInitializedNewFormWithUnregisteredKeyName() public function testInitializedNewFormWithRegisteredUnusedKeyName() { - $enrichmentKey = new Opus_EnrichmentKey(); + $enrichmentKey = new EnrichmentKey(); $enrichmentKey->setName('unused'); $id = $enrichmentKey->store(); $this->dispatch($this->getControllerPath() . '/new/id/unused'); - $enrichmentKey = new Opus_EnrichmentKey($id); + $enrichmentKey = new EnrichmentKey($id); $enrichmentKey->delete(); // Formularfeld "Name" darf nicht gefüllt sein @@ -938,13 +956,13 @@ public function testInitializedNewFormWithRegisteredUnusedKeyName() public function testInitializedNewFormWithRegisteredUsedKeyName() { - $enrichmentKey = new Opus_EnrichmentKey(); + $enrichmentKey = new EnrichmentKey(); $enrichmentKey->setName('used'); $id = $enrichmentKey->store(); $doc = $this->createTestDocument(); - $enrichment = new Opus_Enrichment(); + $enrichment = new Enrichment(); $enrichment->setKeyName('used'); $enrichment->setValue('value'); @@ -953,7 +971,7 @@ public function testInitializedNewFormWithRegisteredUsedKeyName() $this->dispatch($this->getControllerPath() . '/new/id/used'); - $enrichmentKey = new Opus_EnrichmentKey($id); + $enrichmentKey = new EnrichmentKey($id); $enrichmentKey->delete(); // Formularfeld "Name" darf nicht gefüllt sein @@ -990,7 +1008,7 @@ public function testRemoveFromDocsActionWithUnregisteredId() { $doc = $this->createTestDocument(); - $enrichment = new Opus_Enrichment(); + $enrichment = new Enrichment(); $enrichment->setKeyName('testRemoveFromDocsActionWithUnregisteredId'); $enrichment->setValue('value'); @@ -1004,13 +1022,13 @@ public function testRemoveFromDocsActionWithUnregisteredId() public function testRemoveFromDocsActionWithRegisteredUnusedId() { - $enrichmentKey = new Opus_EnrichmentKey(); + $enrichmentKey = new EnrichmentKey(); $enrichmentKey->setName('unused'); $id = $enrichmentKey->store(); $this->dispatch($this->getControllerPath() . '/removeFromDocs/id/unused'); - $enrichmentKey = new Opus_EnrichmentKey($id); + $enrichmentKey = new EnrichmentKey($id); $enrichmentKey->delete(); $this->assertRedirectTo('/admin/enrichmentkey'); @@ -1018,13 +1036,13 @@ public function testRemoveFromDocsActionWithRegisteredUnusedId() public function testRemoveFromDocsActionWithRegisteredUsedId() { - $enrichmentKey = new Opus_EnrichmentKey(); + $enrichmentKey = new EnrichmentKey(); $enrichmentKey->setName('used'); $id = $enrichmentKey->store(); $doc = $this->createTestDocument(); - $enrichment = new Opus_Enrichment(); + $enrichment = new Enrichment(); $enrichment->setKeyName('used'); $enrichment->setValue('value'); @@ -1033,7 +1051,7 @@ public function testRemoveFromDocsActionWithRegisteredUsedId() $this->dispatch($this->getControllerPath() . '/removeFromDocs/id/used'); - $enrichmentKey = new Opus_EnrichmentKey($id); + $enrichmentKey = new EnrichmentKey($id); $enrichmentKey->delete(); $this->assertResponseCode(200); @@ -1044,7 +1062,7 @@ public function testRemoveFromDocsActionPostWithUnregisteredKey() { $doc = $this->createTestDocument(); - $enrichment = new Opus_Enrichment(); + $enrichment = new Enrichment(); $enrichment->setKeyName('unregistered'); $enrichment->setValue('value'); @@ -1062,19 +1080,19 @@ public function testRemoveFromDocsActionPostWithUnregisteredKey() $this->assertRedirectTo('/admin/enrichmentkey'); // das Testdokument sollte kein Enrichment mehr haben - $doc = new Opus_Document($id); + $doc = Document::get($id); $this->assertNull($doc->getEnrichment('unregistered')); } public function testRemoveFromDocsActionPostWithRegisteredKey() { - $enrichmentKey = new Opus_EnrichmentKey(); + $enrichmentKey = new EnrichmentKey(); $enrichmentKey->setName('used'); $id = $enrichmentKey->store(); $doc = $this->createTestDocument(); - $enrichment = new Opus_Enrichment(); + $enrichment = new Enrichment(); $enrichment->setKeyName('used'); $enrichment->setValue('value'); @@ -1092,9 +1110,9 @@ public function testRemoveFromDocsActionPostWithRegisteredKey() $this->assertRedirectTo('/admin/enrichmentkey'); // das Testdokument sollte kein Enrichment mehr haben; der EnrichmentKey muss weiterhin existieren - $doc = new Opus_Document($docId); + $doc = Document::get($docId); $this->assertNull($doc->getEnrichment('used')); - $enrichmentKey = new Opus_EnrichmentKey($id); + $enrichmentKey = new EnrichmentKey($id); $this->assertNotNull($enrichmentKey); // cleanup @@ -1105,7 +1123,7 @@ public function testIndexPageShowUnregisteredKeys() { $doc = $this->createTestDocument(); - $enrichment = new Opus_Enrichment(); + $enrichment = new Enrichment(); $enrichment->setKeyName('unregistered'); $enrichment->setValue('value'); @@ -1123,13 +1141,13 @@ public function testIndexPageShowUnregisteredKeys() public function testIndexPageShowRegisteredUnusedKeys() { - $enrichmentKey = new Opus_EnrichmentKey(); + $enrichmentKey = new EnrichmentKey(); $enrichmentKey->setName('unused'); $id = $enrichmentKey->store(); $this->dispatch($this->getControllerPath() . '/'); - $enrichmentKey = new Opus_EnrichmentKey($id); + $enrichmentKey = new EnrichmentKey($id); $enrichmentKey->delete(); $this->assertResponseCode(200); @@ -1141,13 +1159,13 @@ public function testIndexPageShowRegisteredUnusedKeys() public function testIndexPageShowRegisteredUsedKeys() { - $enrichmentKey = new Opus_EnrichmentKey(); + $enrichmentKey = new EnrichmentKey(); $enrichmentKey->setName('used'); $id = $enrichmentKey->store(); $doc = $this->createTestDocument(); - $enrichment = new Opus_Enrichment(); + $enrichment = new Enrichment(); $enrichment->setKeyName('used'); $enrichment->setValue('value'); @@ -1156,7 +1174,7 @@ public function testIndexPageShowRegisteredUsedKeys() $this->dispatch($this->getControllerPath() . '/'); - $enrichmentKey = new Opus_EnrichmentKey($id); + $enrichmentKey = new EnrichmentKey($id); $enrichmentKey->delete(); $this->assertResponseCode(200); @@ -1170,7 +1188,7 @@ public function testNewActionWithRenamingUnregisteredKey() { // prepare test document with unregistered enrichment key $doc = $this->createTestDocument(); - $enrichment = new Opus_Enrichment(); + $enrichment = new Enrichment(); $enrichment->setKeyName('unregistered'); $enrichment->setValue('value'); $doc->addEnrichment($enrichment); @@ -1189,13 +1207,13 @@ public function testNewActionWithRenamingUnregisteredKey() $this->assertRedirect(); $this->assertRedirectRegex('/^\/admin\/enrichmentkey/'); - $enrichmentKey = Opus_EnrichmentKey::fetchByName('unregistered'); + $enrichmentKey = EnrichmentKey::fetchByName('unregistered'); $this->assertNull($enrichmentKey); - $enrichmentKey = Opus_EnrichmentKey::fetchByName('unregisterednew'); + $enrichmentKey = EnrichmentKey::fetchByName('unregisterednew'); $this->assertNotNull($enrichmentKey); - $doc = new Opus_Document($id); + $doc = Document::get($id); $enrichments = $doc->getEnrichment(); $this->assertCount(1, $enrichments); $this->assertEquals('unregisterednew', $enrichments[0]->getKeyName()); @@ -1208,7 +1226,7 @@ public function testNewActionWithoutRenamingUnregisteredKey() { // prepare test document with unregistered enrichment key $doc = $this->createTestDocument(); - $enrichment = new Opus_Enrichment(); + $enrichment = new Enrichment(); $enrichment->setKeyName('unregistered'); $enrichment->setValue('value'); $doc->addEnrichment($enrichment); @@ -1227,10 +1245,10 @@ public function testNewActionWithoutRenamingUnregisteredKey() $this->assertRedirect(); $this->assertRedirectRegex('/^\/admin\/enrichmentkey/'); - $enrichmentKey = Opus_EnrichmentKey::fetchByName('unregistered'); + $enrichmentKey = EnrichmentKey::fetchByName('unregistered'); $this->assertNotNull($enrichmentKey); - $doc = new Opus_Document($id); + $doc = Document::get($id); $enrichments = $doc->getEnrichment(); $this->assertCount(1, $enrichments); $this->assertEquals('unregistered', $enrichments[0]->getKeyName()); @@ -1246,4 +1264,130 @@ public function enrichmentKeyNamesProvider() ['Audience'] // referenced enrichment key ]; } + + /** + * Tests the function getUnmanaged() + * + * @covers ::getUnmanaged + */ + public function testGetUnmanaged() + { + $this->dispatch($this->getControllerPath() . '/'); + + $this->assertResponseCode(200); + + $domDoc = new DOMDocument(); + $domDoc->loadHTML($this->getResponse()->getBody()); + $xpath = new DOMXPath($domDoc); + $nodeList = $xpath->query('//table[@id="enrichmentkeyTableUnmanaged"]/tbody/tr'); + $tableRowCount = $nodeList->length; + + $enrichmentKeyLast = new EnrichmentKey(); + $enrichmentKeyLast->setName('unmanagedEKlast'); + $enrichmentKeyLast->store(); + + $enrichmentKeyFirst = new EnrichmentKey(); + $enrichmentKeyFirst->setName('unmanagedEKfirst'); + $enrichmentKeyFirst->store(); + + $this->getResponse()->clearBody(); + + $this->dispatch($this->getControllerPath() . '/'); + + $this->assertResponseCode(200); + + // cleanup + $enrichmentKeyFirst->delete(); + $enrichmentKeyLast->delete(); + + $domDoc = new DOMDocument(); + $domDoc->loadHTML($this->getResponse()->getBody()); + $xpath = new DOMXPath($domDoc); + + // zwei neue Zeilen sollten in Tabelle für unmanaged EKs erscheinen + $nodeList = $xpath->query('//table[@id="enrichmentkeyTableUnmanaged"]/tbody/tr'); + $this->assertEquals(2 + $tableRowCount, $nodeList->length); + + // unmanagedEKfirst sollte direkt vor unmanagedEKlast erscheinen (in der Tabelle für unmanaged EKs) + $foundFirst = false; + $foundLast = false; + foreach ($nodeList as $node) { + $textContent = trim($node->textContent); + if (strpos($textContent, 'unmanagedEKfirst') === 0) { + $foundFirst = true; + continue; + } elseif ($foundFirst) { + if (strpos($textContent, 'unmanagedEKlast') === 0) { + $foundLast = true; + } + break; + } + } + $this->assertTrue($foundFirst); + $this->assertTrue($foundLast); + } + + /** + * Tests the function getManaged() + * + * @covers ::getManaged + */ + public function testGetManaged() + { + $this->dispatch($this->getControllerPath() . '/'); + + $this->assertResponseCode(200); + + $domDoc = new DOMDocument(); + $domDoc->loadHTML($this->getResponse()->getBody()); + $xpath = new DOMXPath($domDoc); + $nodeList = $xpath->query('//table[@id="enrichmentkeyTableManaged"]/tbody/tr'); + $tableRowCount = $nodeList->length; + + $enrichmentKeyLast = new EnrichmentKey(); + $enrichmentKeyLast->setName('managedEKlast'); + $enrichmentKeyLast->setType('TextType'); + $enrichmentKeyLast->store(); + + $enrichmentKeyFirst = new EnrichmentKey(); + $enrichmentKeyFirst->setName('managedEKfirst'); + $enrichmentKeyFirst->setType('TextType'); + $enrichmentKeyFirst->store(); + + $this->getResponse()->clearBody(); + + $this->dispatch($this->getControllerPath() . '/'); + + $this->assertResponseCode(200); + + // cleanup + $enrichmentKeyFirst->delete(); + $enrichmentKeyLast->delete(); + + $domDoc = new DOMDocument(); + $domDoc->loadHTML($this->getResponse()->getBody()); + $xpath = new DOMXPath($domDoc); + + // zwei neue Zeilen sollten in Tabelle für managed EKs erscheinen + $nodeList = $xpath->query('//table[@id="enrichmentkeyTableManaged"]/tbody/tr'); + $this->assertEquals(2 + $tableRowCount, $nodeList->length); + + // managedEKfirst sollte direkt vor managedEKlast erscheinen (in der Tabelle für managed EKs) + $foundFirst = false; + $foundLast = false; + foreach ($nodeList as $node) { + $textContent = trim($node->textContent); + if (strpos($textContent, 'managedEKfirst') === 0) { + $foundFirst = true; + continue; + } elseif ($foundFirst) { + if (strpos($textContent, 'managedEKlast') === 0) { + $foundLast = true; + } + break; + } + } + $this->assertTrue($foundFirst); + $this->assertTrue($foundLast); + } } diff --git a/tests/modules/admin/controllers/FilemanagerControllerTest.php b/tests/modules/admin/controllers/FilemanagerControllerTest.php index abba2f0a7f..45e02571d4 100644 --- a/tests/modules/admin/controllers/FilemanagerControllerTest.php +++ b/tests/modules/admin/controllers/FilemanagerControllerTest.php @@ -33,6 +33,10 @@ * TODO einiges durch Selenium abgedeckt; Unit Tests vielleicht möglich */ +use Opus\Date; +use Opus\Document; +use Opus\UserRole; + /** * @covers Admin_FilemanagerController */ @@ -269,11 +273,11 @@ public function testRemoveGuestAccess() $file->setPathName('testdatei.txt'); $documentId = $document->store(); - $document = new Opus_Document($documentId); + $document = Document::get($documentId); $fileId = $document->getFile(0)->getId(); - $roleGuest = Opus_UserRole::fetchByName('guest'); + $roleGuest = UserRole::fetchByName('guest'); $files = $roleGuest->listAccessFiles(); $this->assertContains($fileId, $files); @@ -297,7 +301,7 @@ public function testRemoveGuestAccess() $this->assertResponseCode(302); $this->assertRedirectTo('/admin/document/index/id/' . $documentId); - $roleGuest = Opus_UserRole::fetchByName('guest'); + $roleGuest = UserRole::fetchByName('guest'); $files = $roleGuest->listAccessFiles(); $this->assertNotContains($fileId, $files); } @@ -331,7 +335,7 @@ public function testFileUploadDate() $docId = $doc->store(); - $dateNow = new Opus_Date(); + $dateNow = new Date(); $dateNow->setNow(); $this->dispatch('admin/filemanager/index/id/' . $docId); @@ -345,7 +349,7 @@ public function testFileUploadDate() public function testFileUploadDateAfterModification() { $this->useGerman(); - $doc = new Opus_Document(305); + $doc = Document::get(305); foreach ($doc->getFile() as $file) { $file->setComment(rand()); diff --git a/tests/modules/admin/controllers/IndexmaintenanceControllerTest.php b/tests/modules/admin/controllers/IndexmaintenanceControllerTest.php index fac57993fb..d1d2ad9beb 100644 --- a/tests/modules/admin/controllers/IndexmaintenanceControllerTest.php +++ b/tests/modules/admin/controllers/IndexmaintenanceControllerTest.php @@ -31,6 +31,10 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Job; +use Opus\Job\Runner; +use Opus\Log; + /** * Class Admin_IndexmaintenanceControllerTest * @@ -46,7 +50,7 @@ class Admin_IndexmaintenanceControllerTest extends ControllerTestCase public function tearDown() { // Cleanup of Log File - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $filename = $config->workspacePath . DIRECTORY_SEPARATOR . 'log' . DIRECTORY_SEPARATOR . 'opus_consistency-check.log'; if (file_exists($filename)) { unlink($filename); @@ -58,7 +62,7 @@ public function tearDown() } // Cleanup of Jobs Table - $jobs = Opus_Job::getByLabels([Opus\Search\Task\ConsistencyCheck::LABEL]); + $jobs = Job::getByLabels([Opus\Search\Task\ConsistencyCheck::LABEL]); foreach ($jobs as $job) { try { $job->delete(); @@ -170,9 +174,9 @@ private function disableAsyncMode() private function setAsyncMode($value) { - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'runjobs' => ['asynchronous' => $value] - ])); + ]); } private function enableAsyncIndexmaintenanceMode() @@ -187,9 +191,9 @@ private function disableAsyncIndexmaintenanceMode() private function setAsyncIndexmaintenanceMode($value) { - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'runjobs' => ['indexmaintenance' => ['asynchronous' => $value]] - ])); + ]); } public function testCheckconsistencyActionWithDisabledFeature() @@ -241,7 +245,7 @@ public function testCheckconsistencyActionWithEnabledFeature() { $this->enableAsyncIndexmaintenanceMode(); - $numOfJobs = Opus_Job::getCountForLabel(Opus\Search\Task\ConsistencyCheck::LABEL); + $numOfJobs = Job::getCountForLabel(Opus\Search\Task\ConsistencyCheck::LABEL); $this->assertEquals(0, $numOfJobs); $this->getRequest()->setMethod('POST'); @@ -250,19 +254,19 @@ public function testCheckconsistencyActionWithEnabledFeature() $this->assertResponseCode(302); $this->assertResponseLocationHeader($this->getResponse(), '/admin/indexmaintenance'); - $this->assertEquals(1, Opus_Job::getCountForLabel(Opus\Search\Task\ConsistencyCheck::LABEL)); + $this->assertEquals(1, Job::getCountForLabel(Opus\Search\Task\ConsistencyCheck::LABEL)); - $jobs = Opus_Job::getByLabels([Opus\Search\Task\ConsistencyCheck::LABEL]); + $jobs = Job::getByLabels([Opus\Search\Task\ConsistencyCheck::LABEL]); $jobs[0]->delete(); - $this->assertEquals(0, Opus_Job::getCountForLabel(Opus\Search\Task\ConsistencyCheck::LABEL)); + $this->assertEquals(0, Job::getCountForLabel(Opus\Search\Task\ConsistencyCheck::LABEL)); } public function testCheckconsistencyActionResult() { $this->enableAsyncIndexmaintenanceMode(); - $this->assertEquals(0, Opus_Job::getCountForLabel(Opus\Search\Task\ConsistencyCheck::LABEL), 'missing cleanup of jobs table'); + $this->assertEquals(0, Job::getCountForLabel(Opus\Search\Task\ConsistencyCheck::LABEL), 'missing cleanup of jobs table'); $this->getRequest()->setMethod('POST'); $this->dispatch('/admin/indexmaintenance/checkconsistency'); @@ -270,7 +274,7 @@ public function testCheckconsistencyActionResult() $this->assertResponseCode(302); $this->assertResponseLocationHeader($this->getResponse(), '/admin/indexmaintenance'); - $this->assertEquals(1, Opus_Job::getCountForLabel(Opus\Search\Task\ConsistencyCheck::LABEL), 'consistency check job was not stored in database'); + $this->assertEquals(1, Job::getCountForLabel(Opus\Search\Task\ConsistencyCheck::LABEL), 'consistency check job was not stored in database'); /* * check if job was scheduled for execution @@ -291,13 +295,13 @@ public function testCheckconsistencyActionResult() /* * run job immediately and check for result */ - $jobrunner = new Opus_Job_Runner(); - $jobrunner->setLogger(Zend_Registry::get('Zend_Log')); + $jobrunner = new Runner(); + $jobrunner->setLogger(Log::get()); $worker = new Opus\Search\Task\ConsistencyCheck(); $jobrunner->registerWorker($worker); $jobrunner->run(); - $jobs = Opus_Job::getByLabels([Opus\Search\Task\ConsistencyCheck::LABEL]); + $jobs = Job::getByLabels([Opus\Search\Task\ConsistencyCheck::LABEL]); if (count($jobs) > 0) { $job = $jobs[0]; $message = 'at least one unexpected job found (Label: \'%s\', State: \'%s\', Data: \'%s\', Errors: \'%s\, SHA1 Hash: \'%s\')'; @@ -309,7 +313,7 @@ public function testCheckconsistencyActionResult() $this->fail(sprintf($message, $label, $state, $data, $errors, $hash)); } - $this->assertEquals(0, Opus_Job::getCountForLabel(Opus\Search\Task\ConsistencyCheck::LABEL), 'consistency check job was not removed from database after execution'); + $this->assertEquals(0, Job::getCountForLabel(Opus\Search\Task\ConsistencyCheck::LABEL), 'consistency check job was not removed from database after execution'); $this->resetResponse(); $this->resetRequest(); diff --git a/tests/modules/admin/controllers/InfoControllerTest.php b/tests/modules/admin/controllers/InfoControllerTest.php index dcd9ca908d..957339f5da 100644 --- a/tests/modules/admin/controllers/InfoControllerTest.php +++ b/tests/modules/admin/controllers/InfoControllerTest.php @@ -43,11 +43,11 @@ class Admin_InfoControllerTest extends ControllerTestCase public function testIndexDisplayVersion() { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $this->dispatch('admin/info'); $this->assertResponseCode(200); - $this->assertQuery('dt#admin_info_version'); - $this->assertQueryContentContains("//dt[@id='admin_info_version']/following-sibling::dd", $config->version); + $this->assertQuery('//div[@class="opus-version-info"]'); + $this->assertQueryContentContains("//div[@class='opus-version-info']", $config->version); $this->validateXHTML(); } @@ -59,10 +59,10 @@ public function testVersionWithOldVersion() $this->useEnglish(); // set version that would otherwise be retrieved from server - $versionHelper = Zend_Controller_Action_HelperBroker::getStaticHelper('version'); + $versionHelper = \Zend_Controller_Action_HelperBroker::getStaticHelper('version'); $versionHelper->setVersion('4.6'); - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $oldVersion = $config->version; $config->version = '4.5-TEST'; $this->dispatch('admin/info/update'); @@ -80,8 +80,8 @@ public function testVersionWithOldVersion() public function testVersionWithCurrentVersion() { $this->useEnglish(); - $helper = Zend_Controller_Action_HelperBroker::getStaticHelper('version'); - $helper->setVersion(Zend_Registry::get('Zend_Config')->version); + $helper = \Zend_Controller_Action_HelperBroker::getStaticHelper('version'); + $helper->setVersion($this->getConfig()->version); $this->dispatch('admin/info/update'); $this->assertQueryContentContains('//div', 'Your OPUS version is up to date.'); diff --git a/tests/modules/admin/controllers/IprangeControllerTest.php b/tests/modules/admin/controllers/IprangeControllerTest.php index 4966d53655..5e4e68fb30 100644 --- a/tests/modules/admin/controllers/IprangeControllerTest.php +++ b/tests/modules/admin/controllers/IprangeControllerTest.php @@ -32,6 +32,9 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Iprange; +use Opus\UserRole; + /** * Basic unit tests for IP range controller in admin module. * @@ -51,20 +54,20 @@ public function setUp() public function getModels() { - return Opus_Iprange::getAll(); + return Iprange::getAll(); } public function createNewModel() { $this->createsModels = true; - $ipRange = new Opus_Iprange(); + $ipRange = new Iprange(); $ipRange->setName('localhost'); $ipRange->setStartingip('127.0.0.1'); $ipRange->setEndingip('127.0.0.2'); $ipRange->setRole([ - Opus_UserRole::fetchByName('reviewer'), - Opus_UserRole::fetchByName('docsadmin') + UserRole::fetchByName('reviewer'), + UserRole::fetchByName('docsadmin') ]); return $ipRange->store(); @@ -72,7 +75,7 @@ public function createNewModel() public function getModel($identifier) { - return new Opus_Iprange($identifier); + return new Iprange($identifier); } public function testShowAction() @@ -150,7 +153,7 @@ public function testNewActionCancel() $this->assertRedirectTo('/admin/iprange', 'Should redirect to index action.'); - $this->assertEquals($modelCount, count(Opus_Iprange::getAll()), 'There should be no new ip range.'); + $this->assertEquals($modelCount, count(Iprange::getAll()), 'There should be no new ip range.'); } public function testEditActionShowForm() @@ -188,7 +191,7 @@ public function testEditActionSave() $this->assertRedirectTo("/admin/iprange/show/id/$iprangeId"); $this->verifyFlashMessage('controller_crud_save_success', self::MESSAGE_LEVEL_NOTICE); - $iprange = new Opus_IpRange($iprangeId); + $iprange = new Iprange($iprangeId); $this->assertEquals('ModifiedName', $iprange->getName()); $this->assertEquals('127.0.0.99', $iprange->getStartingip()); @@ -216,7 +219,7 @@ public function testEditActionCancel() $this->dispatch("/admin/iprange/edit"); $this->assertRedirectTo('/admin/iprange'); - $iprange = new Opus_Iprange($iprangeId); + $iprange = new Iprange($iprangeId); $this->assertEquals('localhost', $iprange->getName()); } diff --git a/tests/modules/admin/controllers/JobControllerTest.php b/tests/modules/admin/controllers/JobControllerTest.php index e324573cd1..4b637e590a 100644 --- a/tests/modules/admin/controllers/JobControllerTest.php +++ b/tests/modules/admin/controllers/JobControllerTest.php @@ -27,9 +27,13 @@ * @category Tests * @package Admin * @author Edouard Simon - * @copyright Copyright (c) 2008-2019, OPUS 4 development team + * @copyright Copyright (c) 2008-2021, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * + */ + +use Opus\Job; + +/** * @covers Admin_JobController */ class Admin_JobControllerTest extends ControllerTestCase @@ -37,7 +41,6 @@ class Admin_JobControllerTest extends ControllerTestCase protected $additionalResources = 'all'; - private $__configBackup; private $jobIds = []; public function setUp() @@ -46,33 +49,29 @@ public function setUp() $this->makeConfigurationModifiable(); - $config = Zend_Registry::get('Zend_Config'); - $this->__configBackup = $config; - $config->merge(new Zend_Config(['runjobs' => ['asynchronous' => self::CONFIG_VALUE_TRUE]])); + $this->adjustConfiguration(['runjobs' => ['asynchronous' => self::CONFIG_VALUE_TRUE]]); - $this->assertEquals(0, Opus_Job::getCount(Opus_Job::STATE_FAILED), 'test data changed.'); + $this->assertEquals(0, Job::getCount(Job::STATE_FAILED), 'test data changed.'); for ($i = 0; $i < 10; $i++) { - $job = new Opus_Job(); + $job = new Job(); $job->setLabel('testjob' . ($i < 5 ? 1 : 2)); $job->setData([ 'documentId' => $i, 'task' => 'get-me-a-coffee' ]); - $job->setState(Opus_Job::STATE_FAILED); + $job->setState(Job::STATE_FAILED); $this->jobIds[] = $job->store(); } } public function tearDown() { - - $testJobs = Opus_Job::getAll($this->jobIds); + $testJobs = Job::getAll($this->jobIds); foreach ($testJobs as $job) { $job->delete(); } - Zend_Registry::set('Zend_Config', $this->__configBackup); parent::tearDown(); } @@ -95,7 +94,7 @@ public function testMonitorFailedWorkerJobs() public function testJobDetailsAction() { - $failedJobsUrl = '/admin/job/detail/label/testjob1/state/' . Opus_Job::STATE_FAILED; + $failedJobsUrl = '/admin/job/detail/label/testjob1/state/' . Job::STATE_FAILED; $this->dispatch($failedJobsUrl); $this->assertResponseCode(200); $this->assertQueryContentContains('table.worker-jobs td div', 'task: get-me-a-coffee'); diff --git a/tests/modules/admin/controllers/LanguageControllerTest.php b/tests/modules/admin/controllers/LanguageControllerTest.php index 7226218523..40e8248395 100644 --- a/tests/modules/admin/controllers/LanguageControllerTest.php +++ b/tests/modules/admin/controllers/LanguageControllerTest.php @@ -31,6 +31,8 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Language; + /** * Basic unit tests for Admin_LanguageController class. * @@ -49,14 +51,14 @@ public function setUp() public function getModels() { - return Opus_Language::getAll(); + return Language::getAll(); } public function testShowAction() { $this->createsModels = true; - $language = new Opus_Language(); + $language = new Language(); $language->setActive(true); $language->setRefName('German'); @@ -71,7 +73,7 @@ public function testShowAction() $this->dispatch('/admin/language/show/id/' . $modelId); - $model = new Opus_Language($modelId); + $model = new Language($modelId); $model->delete(); $this->assertResponseCode(200); @@ -166,7 +168,7 @@ public function testNewActionCancel() $this->assertEquals( $modelCount, - count(Opus_Language::getAll()), + count(Language::getAll()), 'Es sollte keine neue Sprache geben.' ); } @@ -192,7 +194,7 @@ public function testEditActionSave() { $this->createsModels = true; - $model = new Opus_Language(); + $model = new Language(); $model->setRefName('Test'); $model->setPart2T('tst'); @@ -216,7 +218,7 @@ public function testEditActionSave() $this->assertRedirectTo('/admin/language/show/id/' . $modelId); $this->verifyFlashMessage('controller_crud_save_success', self::MESSAGE_LEVEL_NOTICE); - $model = new Opus_Language($modelId); + $model = new Language($modelId); $this->assertEquals(1, $model->getActive()); $this->assertEquals('RefNameModified', $model->getRefName()); @@ -232,7 +234,7 @@ public function testEditActionCancel() { $this->createsModels = true; - $model = new Opus_Language(); + $model = new Language(); $model->setRefName('Test'); $model->setPart2T('tst'); @@ -249,7 +251,7 @@ public function testEditActionCancel() $this->dispatch('/admin/language/edit'); $this->assertRedirectTo('/admin/language'); - $model = new Opus_Language($modelId); + $model = new Language($modelId); $this->assertEquals('Test', $model->getRefName()); } @@ -268,7 +270,7 @@ public function testDeleteActionShowForm() public function createNewModel() { - $model = new Opus_Language(); + $model = new Language(); $model->setRefName('TestLang'); $model->setPart2T('lan'); @@ -278,6 +280,6 @@ public function createNewModel() public function getModel($identifier) { - return new Opus_Language($identifier); + return new Language($identifier); } } diff --git a/tests/modules/admin/controllers/LicenceControllerTest.php b/tests/modules/admin/controllers/LicenceControllerTest.php index 695ef047f0..7fd01874f6 100644 --- a/tests/modules/admin/controllers/LicenceControllerTest.php +++ b/tests/modules/admin/controllers/LicenceControllerTest.php @@ -25,6 +25,8 @@ * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ +use Opus\Licence; + /** * Unit Tests für Klasse Admin_LicenceController. * @@ -51,7 +53,7 @@ public function setUp() public function getModels() { - return Opus_Licence::getAll(); + return Licence::getAll(); } /** @@ -61,7 +63,7 @@ public function testShowAction() { $this->createsModels = true; - $licence = new Opus_Licence(); + $licence = new Licence(); $licence->setActive(true); $licence->setNameLong('TestNameLong'); @@ -80,7 +82,7 @@ public function testShowAction() $this->dispatch('/admin/licence/show/id/' . $licenceId); - $licence = new Opus_Licence($licenceId); + $licence = new Licence($licenceId); $licence->delete(); $this->assertResponseCode(200); @@ -189,7 +191,7 @@ public function testNewActionCancel() $this->assertEquals( $modelCount, - count(Opus_Licence::getAll()), + count(Licence::getAll()), 'Es sollte keine neue Lizenz geben.' ); } @@ -214,7 +216,7 @@ public function testEditActionSave() { $this->createsModels = true; - $licence = new Opus_Licence(); + $licence = new Licence(); $licence->setNameLong('NameLong'); $licence->setLanguage('deu'); @@ -242,7 +244,7 @@ public function testEditActionSave() $this->assertRedirectTo('/admin/licence/show/id/' . $licenceId); $this->verifyFlashMessage('controller_crud_save_success', self::MESSAGE_LEVEL_NOTICE); - $licence = new Opus_Licence($licenceId); + $licence = new Licence($licenceId); $this->assertEquals(1, $licence->getActive()); $this->assertEquals('NameLongModified', $licence->getNameLong()); @@ -261,7 +263,7 @@ public function testEditActionCancel() { $this->createsModels = true; - $licence = new Opus_Licence(); + $licence = new Licence(); $licence->setNameLong('NameLong'); $licence->setLanguage('deu'); @@ -280,7 +282,7 @@ public function testEditActionCancel() $this->dispatch('/admin/licence/edit'); $this->assertRedirectTo('/admin/licence'); - $licence = new Opus_Licence($licenceId); + $licence = new Licence($licenceId); $this->assertEquals('NameLong', $licence->getNameLong()); } @@ -310,7 +312,7 @@ public function testDeleteActionUsedLicence() public function createNewModel() { - $licence = new Opus_Licence(); + $licence = new Licence(); $licence->setNameLong('Test Licence (LicenceControllerTest::testDeleteAction)'); $licence->setLinkLicence('testlink'); @@ -321,6 +323,6 @@ public function createNewModel() public function getModel($identifier) { - return new Opus_Licence($identifier); + return new Licence($identifier); } } diff --git a/tests/modules/admin/controllers/PersonControllerTest.php b/tests/modules/admin/controllers/PersonControllerTest.php index 3d285b0f2e..20180fa6bb 100644 --- a/tests/modules/admin/controllers/PersonControllerTest.php +++ b/tests/modules/admin/controllers/PersonControllerTest.php @@ -1,5 +1,4 @@ * @copyright Copyright (c) 2008-2019, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * + */ + +use Opus\Person; + +/** * @covers Admin_PersonController */ class Admin_PersonControllerTest extends ControllerTestCase @@ -110,7 +113,7 @@ public function testAssignActionAddPerson() preg_match('/person\/(\d+)\//', $location, $matches); $personId = $matches[1]; - $person = new Opus_Person($personId); + $person = new Person($personId); $lastName = $person->getLastName(); @@ -193,7 +196,7 @@ public function testEditlinkedActionSave() { $document = $this->createTestDocument(); - $person = new Opus_Person(); + $person = new Person(); $person->setLastName('Testy-EditlinkedAction'); $person = $document->addPersonTranslator($person); @@ -218,7 +221,7 @@ public function testEditlinkedActionSave() $this->assertRedirectTo('/admin/document/edit/id/' . $documentId . '/continue/updateperson/person/' . $personId); - $person = new Opus_Person($personId); + $person = new Person($personId); $this->assertEquals('Testy', $person->getLastName()); $this->assertEquals('Simone', $person->getFirstName()); @@ -378,7 +381,7 @@ public function testIndexPaginationFirstPage() } /** - * TODO test is affected by other tests creating Opus_Person objects, because deleting test documents does not + * TODO test is affected by other tests creating Person objects, because deleting test documents does not * delete linked persons */ public function testIndexPaginationLastPage() @@ -392,7 +395,7 @@ public function testIndexPaginationLastPage() $this->assertQuery('div.pagination-next'); $this->assertQuery('div.pagination-last'); - $personsCount = Opus_Person::getAllPersonsCount(); + $personsCount = Person::getAllPersonsCount(); $pages = ceil($personsCount / 50); @@ -479,7 +482,7 @@ public function testAdminMenuEntry() $this->assertXpath('//li/a[@href = "/admin/person"]'); } - public function testAccessControl() + public function testAccessControlAdmin() { $this->useEnglish(); $this->enableSecurity(); @@ -490,7 +493,12 @@ public function testAccessControl() $this->assertResponseCode(200); $this->assertQueryContentContains('li.group-sky/a/strong', 'Persons'); $this->assertXpath('//li/a[@href = "/admin/person"]'); + } + public function testAccessControlUser() + { + $this->useEnglish(); + $this->enableSecurity(); $this->loginUser('security2', 'security2pwd'); $this->dispatch('/admin'); diff --git a/tests/modules/admin/controllers/ReportControllerTest.php b/tests/modules/admin/controllers/ReportControllerTest.php index ee66be9d97..f2e10c790f 100644 --- a/tests/modules/admin/controllers/ReportControllerTest.php +++ b/tests/modules/admin/controllers/ReportControllerTest.php @@ -31,6 +31,9 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Document; +use Opus\Identifier; + /** * Unit tests for Admin_ReportController * @@ -41,20 +44,14 @@ class Admin_ReportControllerTest extends ControllerTestCase protected $additionalResources = 'all'; - private $config; - private $docIds; public function setUp() { parent::setUp(); - // backup config - $this->config = Zend_Registry::get('Zend_Config'); - // modify DOI config - $config = Zend_Registry::get('Zend_Config'); - $config->merge(new Zend_Config([ + $this->adjustConfiguration([ 'doi' => [ 'prefix' => '10.5072', 'localPrefix' => 'opustest', @@ -68,20 +65,16 @@ public function setUp() ] ] ] - ])); - Zend_Registry::set('Zend_Config', $config); + ]); } public function tearDown() { - // restore config - Zend_Registry::set('Zend_Config', $this->config); - if (! is_null($this->docIds)) { // removed previously created test documents from database foreach ($this->docIds as $docId) { - $doc = new Opus_Document($docId); - $doc->deletePermanent(); + $doc = Document::get($docId); + $doc->delete(); } } @@ -257,12 +250,12 @@ private function createTestDocs() private function createTestDocWithDoi($serverState, $doiStatus, $local = true) { - $doc = new Opus_Document(); + $doc = Document::new(); $doc->setServerState($serverState); $docId = $doc->store(); $this->docIds[] = $docId; - $doi = new Opus_Identifier(); + $doi = new Identifier(); $doi->setType('doi'); if ($local) { $doi->setValue('10.5072/opustest-' . $docId); diff --git a/tests/modules/admin/controllers/RoleControllerTest.php b/tests/modules/admin/controllers/RoleControllerTest.php index a43c5734d7..ac905f5736 100644 --- a/tests/modules/admin/controllers/RoleControllerTest.php +++ b/tests/modules/admin/controllers/RoleControllerTest.php @@ -30,6 +30,8 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\UserRole; + /** * Basic unit tests for Admin_RoleController class. * @@ -123,7 +125,7 @@ public function testCreateAction() $this->assertController('role'); $this->assertAction('new'); $this->assertRedirect('/admin/role/index'); - $this->assertNotNull(Opus_UserRole::fetchByName('testrole')); + $this->assertNotNull(UserRole::fetchByName('testrole')); } public function testCreateActionCancel() @@ -166,7 +168,7 @@ public function testCreateActionMissingInput() */ public function testUpdateAction() { - $role = Opus_UserRole::fetchByName('testrole'); + $role = UserRole::fetchByName('testrole'); $this->request ->setMethod('POST') @@ -183,7 +185,7 @@ public function testUpdateAction() $this->assertController('role'); $this->assertAction('edit'); $this->assertRedirect(); - $role = Opus_UserRole::fetchByName('testrole2'); + $role = UserRole::fetchByName('testrole2'); $this->assertNotNull($role); $this->assertNotNull($role->getId()); $this->assertEquals('testrole2', $role->getDisplayName()); @@ -194,7 +196,7 @@ public function testUpdateAction() */ public function testUpdateActionInvalidInput() { - $role = Opus_UserRole::fetchByName('testrole2'); + $role = UserRole::fetchByName('testrole2'); $this->request ->setMethod('POST') @@ -218,7 +220,7 @@ public function testUpdateActionInvalidInput() */ public function testDeleteAction() { - $role = Opus_UserRole::fetchByName('testrole2'); + $role = UserRole::fetchByName('testrole2'); $this->assertNotNull($role); $this->getRequest()->setMethod('POST') ->setPost([ diff --git a/tests/modules/admin/controllers/SeriesControllerTest.php b/tests/modules/admin/controllers/SeriesControllerTest.php index 1641448852..5ae75e1ea0 100644 --- a/tests/modules/admin/controllers/SeriesControllerTest.php +++ b/tests/modules/admin/controllers/SeriesControllerTest.php @@ -33,6 +33,8 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Series; + /** * Class Admin_SeriesControllerTest. * @@ -51,12 +53,12 @@ public function setUp() public function getModels() { - return Opus_Series::getAllSortedBySortKey(); + return Series::getAllSortedBySortKey(); } public function createNewModel() { - $series = new Opus_Series(); + $series = new Series(); $series->setTitle('Testseries'); $series->setInfobox('Infotext'); @@ -68,7 +70,7 @@ public function createNewModel() public function getModel($identifier) { - return new Opus_Series($identifier); + return new Series($identifier); } public function testShowAction() @@ -93,7 +95,7 @@ public function testShowNewAction() { $this->dispatch('/admin/series/new'); - $sortOrder = Opus_Series::getMaxSortKey() + 1; + $sortOrder = Series::getMaxSortKey() + 1; $this->assertXPath('//input[@type = "checkbox" and @checked = "checked"]'); $this->assertXPath('//input[@name = "SortOrder" and @value = "' . $sortOrder . '"]'); @@ -155,7 +157,7 @@ public function testNewActionCancel() $this->assertEquals( $modelCount, - count(Opus_Series::getAllSortedBySortKey()), + count(Series::getAllSortedBySortKey()), 'Es sollte keine neue Series geben.' ); } @@ -192,7 +194,7 @@ public function testEditActionSave() $this->assertRedirectTo('/admin/series/show/id/' . $seriesId); $this->verifyFlashMessage('controller_crud_save_success', self::MESSAGE_LEVEL_NOTICE); - $series = new Opus_Series($seriesId); + $series = new Series($seriesId); $this->assertEquals('ModifiedTitle', $series->getTitle()); $this->assertEquals('ModifiedInfo', $series->getInfobox()); @@ -218,7 +220,7 @@ public function testEditActionCancel() $this->dispatch('/admin/series/edit'); $this->assertRedirectTo('/admin/series'); - $series = new Opus_Series($seriesId); + $series = new Series($seriesId); $this->assertEquals('Testseries', $series->getTitle()); } @@ -239,7 +241,7 @@ public function testHideDocumentsLinkForSeriesWithoutDocuments() { $this->dispatch('/admin/series'); - $allSeries = Opus_Series::getAll(); + $allSeries = Series::getAll(); foreach ($allSeries as $series) { $seriesId = $series->getId(); @@ -255,7 +257,7 @@ public function testSeriesVisibilityIsDisplayedCorrectly() { $this->dispatch('/admin/series'); - $allSeries = Opus_Series::getAll(); + $allSeries = Series::getAll(); foreach ($allSeries as $series) { $seriesId = $series->getId(); @@ -271,7 +273,7 @@ public function testSeriesIdIsShownInTable() { $this->dispatch('/admin/series'); - $allSeries = Opus_Series::getAll(); + $allSeries = Series::getAll(); foreach ($allSeries as $series) { $seriesId = $series->getId(); diff --git a/tests/modules/admin/controllers/WorkflowControllerTest.php b/tests/modules/admin/controllers/WorkflowControllerTest.php index bd8e04f954..3e082e73db 100644 --- a/tests/modules/admin/controllers/WorkflowControllerTest.php +++ b/tests/modules/admin/controllers/WorkflowControllerTest.php @@ -32,6 +32,9 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Document; +use Opus\Person; + /** * Class Admin_WorkflowControllerTest. * @@ -44,7 +47,7 @@ class Admin_WorkflowControllerTest extends ControllerTestCase private function enablePublishNotification() { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $config->notification->document->published->enabled = self::CONFIG_VALUE_TRUE; $config->notification->document->published->email = "published@localhost"; } @@ -53,7 +56,7 @@ private function createDocWithSubmitterAndAuthor($submitterMail, $authorMail) { $doc = $this->createTestDocument(); - $author = new Opus_Person(); + $author = new Person(); $author->setFirstName("John"); $author->setLastName("Doe"); if ($author != '') { @@ -61,7 +64,7 @@ private function createDocWithSubmitterAndAuthor($submitterMail, $authorMail) } $doc->addPersonAuthor($author); - $submitter = new Opus_Person(); + $submitter = new Person(); $submitter->setFirstName("John"); $submitter->setLastName("Submitter"); if ($submitterMail != '') { @@ -101,7 +104,7 @@ public function testDeleteActionConfirmNo() $this->assertAction('changestate'); $this->assertRedirect('/admin/document/index'); - $doc = new Opus_Document(24); + $doc = Document::get(24); $this->assertNotEquals('deleted', $doc->getServerState()); } @@ -121,7 +124,7 @@ public function testDeleteActionConfirmYes() $this->assertAction('changestate'); $this->assertRedirect('/admin/document/index'); - $doc = new Opus_Document(102); + $doc = Document::get(102); $this->assertEquals('deleted', $doc->getServerState()); $doc->setServerState('unpublished'); $doc->store(); @@ -164,7 +167,7 @@ public function testPermanentDeleteActionConfirmNo() $this->assertAction('changestate'); $this->assertRedirect('/admin/document/index'); - $doc = new Opus_Document($documentId); + $doc = Document::get($documentId); $this->assertEquals('deleted', $doc->getServerState()); } @@ -184,7 +187,7 @@ public function testPublishActionConfirmYes() $this->assertAction('changestate'); $this->assertRedirect('/admin/document/index'); - $doc = new Opus_Document(100); + $doc = Document::get(100); $this->assertEquals('published', $doc->getServerState()); $doc->setServerState('unpublished'); $doc->store(); @@ -383,18 +386,18 @@ public function testAuthorNotificationForMultipleAuthors() 'author@localhost.de' ); - $author = new Opus_Person(); + $author = new Person(); $author->setFirstName("AFN"); $author->setLastName("ALN"); $author->setEmail("A@localhost.de"); $doc->addPersonAuthor($author); - $author = new Opus_Person(); + $author = new Person(); $author->setFirstName("BFN"); $author->setLastName("BLN"); $doc->addPersonAuthor($author); - $author = new Opus_Person(); + $author = new Person(); $author->setFirstName("CFN"); $author->setLastName("CLN"); $author->setEmail("C@localhost.de"); @@ -433,14 +436,14 @@ public function testShowDocInfoOnConfirmationPage() public function testConfirmationDisabled() { - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'confirmation' => ['document' => ['statechange' => ['enabled' => self::CONFIG_VALUE_FALSE]]] - ])); + ]); $this->dispatch('/admin/workflow/changestate/docId/102/targetState/deleted'); $this->assertRedirectTo('/admin/document/index/id/102'); // Änderung wird sofort durchgefuehrt - $doc = new Opus_Document(102); + $doc = Document::get(102); $this->assertEquals('deleted', $doc->getServerState()); $doc->setServerState('unpublished'); $doc->store(); diff --git a/tests/modules/admin/forms/AbstractDocumentSubFormTest.php b/tests/modules/admin/forms/AbstractDocumentSubFormTest.php index d2a3e49b5a..cf782a44a4 100644 --- a/tests/modules/admin/forms/AbstractDocumentSubFormTest.php +++ b/tests/modules/admin/forms/AbstractDocumentSubFormTest.php @@ -25,6 +25,8 @@ * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ +use Opus\Licence; + /** * Unit Tests fuer abstrakte Parent-Klasse fuer Metadaten Unterformulare. * @@ -70,7 +72,7 @@ public function testInit() */ public function testPopulateFromModel() { - $this->form->populateFromModel(new Opus_Licence()); + $this->form->populateFromModel(new Licence()); } /** diff --git a/tests/modules/admin/forms/AccountTest.php b/tests/modules/admin/forms/AccountTest.php index 126ea1b3dc..9e8b5c6160 100644 --- a/tests/modules/admin/forms/AccountTest.php +++ b/tests/modules/admin/forms/AccountTest.php @@ -30,6 +30,8 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Account; + class Admin_Form_AccountTest extends ControllerTestCase { @@ -41,7 +43,7 @@ public function setUp() { parent::setUp(); - $user = new Opus_Account(); + $user = new Account(); $user->setLogin('user'); $user->setPassword('userpwd'); $user->store(); @@ -66,7 +68,7 @@ public function testCreateForm() public function testCreateFormForUser() { - $user = new Opus_Account(null, null, 'user'); + $user = new Account(null, null, 'user'); $form = new Admin_Form_Account($user->getId()); $this->assertNotNUll($form); $this->assertEquals('user', $form->getElement('username')->getValue()); @@ -79,7 +81,7 @@ public function testCreateFormForUser() public function testCreateFormForCurrentUser() { $this->loginUser('admin', 'adminadmin'); - $user = new Opus_Account(null, null, 'admin'); + $user = new Account(null, null, 'admin'); $form = new Admin_Form_Account($user->getId()); $this->assertNotNull($form); $element = $form->getSubForm(Admin_Form_Account::SUBFORM_ROLES)->getElement('administrator'); @@ -91,7 +93,7 @@ public function testCreateFormForCurrentUser() */ public function testDoNotLowerCaseUsername() { - $user = new Opus_Account(null, null, 'user'); + $user = new Account(null, null, 'user'); $form = new Admin_Form_Account($user->getId()); @@ -106,7 +108,7 @@ public function testDoNotLowerCaseUsername() public function testChangedLoginNameValidationExistingLoginNameAccount() { - $user = new Opus_Account(null, null, 'user'); + $user = new Account(null, null, 'user'); $form = new Admin_Form_Account($user->getId()); @@ -124,7 +126,7 @@ public function testChangedLoginNameValidationExistingLoginNameAccount() public function testChangedLoginNameValidationNewLoginName() { - $user = new Opus_Account(null, null, 'user'); + $user = new Account(null, null, 'user'); $form = new Admin_Form_Account($user->getId()); @@ -142,7 +144,7 @@ public function testChangedLoginNameValidationNewLoginName() public function testEditValidationSameAccount() { - $user = new Opus_Account(null, null, 'user'); + $user = new Account(null, null, 'user'); $form = new Admin_Form_Account($user->getId()); @@ -217,4 +219,18 @@ public function testPopulate() $this->assertContains('jobaccess', $selected); $this->assertContains('guest', $selected); } + + public function testValidationNewAccountMissingPassword() + { + $form = new Admin_Form_Account(); + + $postData = [ + 'username' => 'newaccount' + ]; + + $this->assertFalse($form->isValid($postData)); + + $this->assertContains('isEmpty', $form->getErrors('password')); + $this->assertContains('isEmpty', $form->getErrors('confirmPassword')); + } } diff --git a/tests/modules/admin/forms/ActionBoxTest.php b/tests/modules/admin/forms/ActionBoxTest.php index add480b5ca..e971909065 100644 --- a/tests/modules/admin/forms/ActionBoxTest.php +++ b/tests/modules/admin/forms/ActionBoxTest.php @@ -36,17 +36,17 @@ class Admin_Form_ActionBoxTest extends ControllerTestCase public function testGetJumpLinks() { - $testForm = new Zend_Form(); + $testForm = new \Zend_Form(); - $subform = new Zend_Form_SubForm(); + $subform = new \Zend_Form_SubForm(); $subform->setLegend('Subform 1'); $testForm->addSubForm($subform, 'form1'); - $subform = new Zend_Form_SubForm(); + $subform = new \Zend_Form_SubForm(); $subform->setLegend('Subform 2'); $testForm->addSubForm($subform, 'form2'); - $subform = new Zend_Form_SubForm(); + $subform = new \Zend_Form_SubForm(); $subform->setLegend(null); $testForm->addSubForm($subform, 'form3'); diff --git a/tests/modules/admin/forms/CollectionRoleTest.php b/tests/modules/admin/forms/CollectionRoleTest.php index 7817a9e65a..5a08894046 100644 --- a/tests/modules/admin/forms/CollectionRoleTest.php +++ b/tests/modules/admin/forms/CollectionRoleTest.php @@ -31,6 +31,8 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\CollectionRole; + class Admin_Form_CollectionRoleTest extends ControllerTestCase { @@ -40,7 +42,7 @@ public function testConstructForm() { $form = new Admin_Form_CollectionRole(); - $this->assertEquals(15, count($form->getElements())); + $this->assertCount(15, $form->getElements()); $this->assertNotNull($form->getElement('Name')); $this->assertNotNull($form->getElement('DisplayName')); @@ -65,7 +67,7 @@ public function testPopulateFromModel() { $form = new Admin_Form_CollectionRole(); - $model = new Opus_CollectionRole(); + $model = new CollectionRole(); $model->setName('TestName'); $model->setOaiName('TestOaiName'); @@ -103,7 +105,7 @@ public function testPopulateFromModelWithId() { $form = new Admin_Form_CollectionRole(); - $model = new Opus_CollectionRole(2); + $model = new CollectionRole(2); $form->populateFromModel($model); @@ -135,7 +137,7 @@ public function testUpdateModel() $form->getElement('AssignLeavesOnly')->setValue(1); $form->getElement('HideEmptyCollections')->setValue(1); - $model = new Opus_CollectionRole(); + $model = new CollectionRole(); $form->updateModel($model); diff --git a/tests/modules/admin/forms/CollectionTest.php b/tests/modules/admin/forms/CollectionTest.php index 8abc2feb67..3800076891 100644 --- a/tests/modules/admin/forms/CollectionTest.php +++ b/tests/modules/admin/forms/CollectionTest.php @@ -31,6 +31,8 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Collection; + class Admin_Form_CollectionTest extends ControllerTestCase { @@ -40,7 +42,7 @@ public function testConstructForm() { $form = new Admin_Form_Collection(); - $this->assertEquals('7', count($form->getElements())); + $this->assertCount(7, $form->getElements()); $this->assertNotNull($form->getElement('Name')); $this->assertNotNull($form->getElement('Number')); $this->assertNotNull($form->getElement('Visible')); @@ -56,7 +58,7 @@ public function testPopulateFromModel() { $form = new Admin_Form_Collection(); - $model = new Opus_Collection(); + $model = new Collection(); $model->setName('TestName'); $model->setNumber('50'); @@ -77,7 +79,7 @@ public function testHandlingOfNullValue() { $form = new Admin_Form_Collection(); - $model = new Opus_Collection(); + $model = new Collection(); $model->setName('TestName'); $model->setNumber(null); @@ -94,7 +96,7 @@ public function testPopulateFromModelWithId() { $form = new Admin_Form_Collection(); - $model = new Opus_Collection(3); + $model = new Collection(3); $form->populateFromModel($model); @@ -113,7 +115,7 @@ public function testUpdateModel() $form->getElement('OaiSubset')->setValue('TestSubset'); // $form->getElement('Theme')->setValue('plain'); - $model = new Opus_Collection(); + $model = new Collection(); $form->updateModel($model); diff --git a/tests/modules/admin/forms/ConfigurationTest.php b/tests/modules/admin/forms/ConfigurationTest.php index c177effef4..12fe339ce8 100644 --- a/tests/modules/admin/forms/ConfigurationTest.php +++ b/tests/modules/admin/forms/ConfigurationTest.php @@ -49,7 +49,7 @@ public function testPopulateFromModel() { $form = new Admin_Form_Configuration(); - $form->populateFromModel(new Zend_Config([ + $form->populateFromModel(new \Zend_Config([ 'searchengine' => ['solr' => ['parameterDefaults' => ['rows' => '20']]] ])); // searchengine.solr.parameterDefaults.rows @@ -65,7 +65,7 @@ public function testUpdateModel() $form->getElement('maxSearchResults')->setValue(15); - $config = new Zend_Config([], true); + $config = new \Zend_Config([], true); $form->updateModel($config); diff --git a/tests/modules/admin/forms/DnbInstituteTest.php b/tests/modules/admin/forms/DnbInstituteTest.php index 734060dd79..95a52d2e87 100644 --- a/tests/modules/admin/forms/DnbInstituteTest.php +++ b/tests/modules/admin/forms/DnbInstituteTest.php @@ -31,6 +31,8 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\DnbInstitute; + class Admin_Form_DnbInstituteTest extends ControllerTestCase { @@ -40,7 +42,7 @@ public function testConstructForm() { $form = new Admin_Form_DnbInstitute(); - $this->assertEquals(11, count($form->getElements())); + $this->assertCount(11, $form->getElements()); $this->assertNotNull($form->getElement('Name')); $this->assertNotNull($form->getElement('Department')); @@ -60,7 +62,7 @@ public function testPopulateFromModel() { $form = new Admin_Form_DnbInstitute(); - $model = new Opus_DnbInstitute(); + $model = new DnbInstitute(); $model->setName('TestName'); $model->setDepartment('TestDepartment'); $model->setAddress('TestAddress'); @@ -88,7 +90,7 @@ public function testPopulateFromModelWithId() { $form = new Admin_Form_DnbInstitute(); - $model = new Opus_DnbInstitute(2); + $model = new DnbInstitute(2); $form->populateFromModel($model); @@ -108,7 +110,7 @@ public function testUpdateModel() $form->getElement('IsGrantor')->setChecked(true); $form->getElement('IsPublisher')->setChecked(false); - $model = new Opus_DnbInstitute(); + $model = new DnbInstitute(); $form->updateModel($model); diff --git a/tests/modules/admin/forms/Document/AbstractTest.php b/tests/modules/admin/forms/Document/AbstractTest.php index e8d0c7b80a..b951da360d 100644 --- a/tests/modules/admin/forms/Document/AbstractTest.php +++ b/tests/modules/admin/forms/Document/AbstractTest.php @@ -30,6 +30,9 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Document; +use Opus\TitleAbstract; + /** * Unit Tests fuer Unterformular fuer Zusammenfassungen. */ @@ -52,7 +55,7 @@ public function testPopulateFromModel() { $form = new Admin_Form_Document_Abstract(); - $doc = new Opus_Document(146); + $doc = Document::get(146); $abstracts = $doc->getTitleAbstract(); @@ -74,7 +77,7 @@ public function testUpdateModel() $form->getElement('Language')->setValue('eng'); $form->getElement('Value')->setValue('Test Zusammenfassung!'); - $abstract = new Opus_TitleAbstract(); + $abstract = new TitleAbstract(); $form->updateModel($abstract); @@ -86,7 +89,7 @@ public function testGetModel() { $form = new Admin_Form_Document_Abstract(); - $doc = new Opus_Document(146); + $doc = Document::get(146); $abstracts = $doc->getTitleAbstract(); diff --git a/tests/modules/admin/forms/Document/BibliographicTest.php b/tests/modules/admin/forms/Document/BibliographicTest.php index 37d0741ba2..87ae43f4c2 100644 --- a/tests/modules/admin/forms/Document/BibliographicTest.php +++ b/tests/modules/admin/forms/Document/BibliographicTest.php @@ -30,6 +30,8 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Document; + /** * Unit Tests fuer Unterformular fuer bibliographische Information im Metadaten-Formular. */ @@ -78,7 +80,7 @@ public function testPopulateFromModel() { $form = new Admin_Form_Document_Bibliographic(); - $doc = new Opus_Document(146); + $doc = Document::get(146); $form->populateFromModel($doc); diff --git a/tests/modules/admin/forms/Document/CollectionTest.php b/tests/modules/admin/forms/Document/CollectionTest.php index 74a121e1db..f6c2a54779 100644 --- a/tests/modules/admin/forms/Document/CollectionTest.php +++ b/tests/modules/admin/forms/Document/CollectionTest.php @@ -31,6 +31,8 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Collection; + /** * Tests fuer Admin_Form_Document_Collection Unterformular Klasse. */ @@ -43,7 +45,7 @@ public function createForm() { $form = new Admin_Form_Document_Collection(); - $this->assertEquals(3, count($form->getElements())); + $this->assertCount(3, $form->getElements()); $this->assertNotNull($form->getElement('Id')); $this->assertNotNull($form->getElement('Edit')); @@ -54,7 +56,7 @@ public function testPopulateFromModel() { $form = new Admin_Form_Document_Collection(); - $collection = new Opus_Collection(499); + $collection = new Collection(499); $form->populateFromModel($collection); @@ -68,7 +70,7 @@ public function testPopulateFromModelWithRootCollectionWithoutName() $form = new Admin_Form_Document_Collection(); - $collection = new Opus_Collection(2); // Root-Collection DDC-Klassifikation + $collection = new Collection(2); // Root-Collection DDC-Klassifikation $form->populateFromModel($collection); @@ -122,7 +124,7 @@ public function testPopulateFromPost() $form->populateFromPost($post); - $collection = new Opus_Collection(499); + $collection = new Collection(499); $this->assertEquals($collection->getDisplayName(), $form->getLegend()); $this->assertEquals($collection->getId(), $form->getElement('Id')->getValue()); diff --git a/tests/modules/admin/forms/Document/CollectionsTest.php b/tests/modules/admin/forms/Document/CollectionsTest.php index 3c8bc8f91a..59ead8de88 100644 --- a/tests/modules/admin/forms/Document/CollectionsTest.php +++ b/tests/modules/admin/forms/Document/CollectionsTest.php @@ -31,6 +31,8 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Document; + class Admin_Form_Document_CollectionsTest extends ControllerTestCase { @@ -55,7 +57,7 @@ public function testAddGetSubformWithDashInName() { $form = new Admin_Form_Document_Collections(); - $subform = new Zend_Form_SubForm(); + $subform = new \Zend_Form_SubForm(); $form->addSubForm($subform, 'ddc-2'); @@ -94,7 +96,7 @@ public function testPopulateFromPost() */ public function testFormNameRendering() { - $form = new Zend_Form(); + $form = new \Zend_Form(); $form->setName('ddc-2'); $html = $form->render(); @@ -104,7 +106,7 @@ public function testFormNameRendering() public function testGetGroupedCollections() { - $document = new Opus_Document(146); + $document = Document::get(146); $form = new Admin_Form_Document_Collections(); @@ -116,6 +118,6 @@ public function testGetGroupedCollections() $ddc = $grouped['ddc']; $this->assertCount(4, $ddc); - $this->assertInstanceOf('Opus_Collection', $ddc[0]); + $this->assertInstanceOf('Opus\Collection', $ddc[0]); } } diff --git a/tests/modules/admin/forms/Document/EnrichmentTest.php b/tests/modules/admin/forms/Document/EnrichmentTest.php index 8ba8fdb2ad..d9624749ca 100644 --- a/tests/modules/admin/forms/Document/EnrichmentTest.php +++ b/tests/modules/admin/forms/Document/EnrichmentTest.php @@ -31,13 +31,20 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Document; +use Opus\Enrichment; +use Opus\EnrichmentKey; +use Opus\Enrichment\RegexType; +use Opus\Enrichment\SelectType; +use Opus\Enrichment\TextType; + /** * Unit Test für Unterformular für ein Enrichment im Metadaten-Formular. */ class Admin_Form_Document_EnrichmentTest extends ControllerTestCase { - protected $additionalResources = ['database']; + protected $additionalResources = ['database', 'translation']; public function testCreateForm() { @@ -55,7 +62,7 @@ public function testPopulateFromModelWithoutType() { $enrichmentKey = $this->createTestEnrichmentKey('keywithouttype'); - $enrichment = new Opus_Enrichment(); + $enrichment = new Enrichment(); $enrichment->setValue('foo'); $enrichment->setKeyName('keywithouttype'); @@ -69,7 +76,7 @@ public function testPopulateFromModelWithUnknownType() { $enrichmentKey = $this->createTestEnrichmentKey('keywithunknowntype', 'FooBarType'); - $enrichment = new Opus_Enrichment(); + $enrichment = new Enrichment(); $enrichment->setValue('foo'); $enrichment->setKeyName('keywithunknowntype'); @@ -83,7 +90,7 @@ public function testPopulateFromModelBooleanTypeChecked() { $enrichmentKey = $this->createTestEnrichmentKey('boolean', 'BooleanType'); - $enrichment = new Opus_Enrichment(); + $enrichment = new Enrichment(); $enrichment->setValue(1); $enrichment->setKeyName('boolean'); @@ -97,7 +104,7 @@ public function testPopulateFromModelBooleanTypeUnchecked() { $enrichmentKey = $this->createTestEnrichmentKey('boolean', 'BooleanType'); - $enrichment = new Opus_Enrichment(); + $enrichment = new Enrichment(); $enrichment->setValue(0); $enrichment->setKeyName('boolean'); @@ -118,7 +125,7 @@ public function testPopulateFromModelSelectType() ); foreach ($options as $option) { - $enrichment = new Opus_Enrichment(); + $enrichment = new Enrichment(); $enrichment->setValue($option); $enrichment->setKeyName('select'); @@ -138,7 +145,7 @@ public function testPopulateFromModelSelectTypeWithInvalidValue() ['values' => $options, 'validation' => 'strict'] ); - $enrichment = new Opus_Enrichment(); + $enrichment = new Enrichment(); $enrichment->setValue('foobar'); // dieser Wert ist gemäß Konfiguration nicht gültig $enrichment->setKeyName('select'); @@ -151,7 +158,7 @@ public function testPopulateFromModelTextType() { $enrichmentKey = $this->createTestEnrichmentKey('text', 'TextType'); - $enrichment = new Opus_Enrichment(); + $enrichment = new Enrichment(); $enrichment->setValue('foo'); $enrichment->setKeyName('text'); @@ -164,7 +171,7 @@ public function testPopulateFromModelTextareaType() { $enrichmentKey = $this->createTestEnrichmentKey('textarea', 'TextareaType'); - $enrichment = new Opus_Enrichment(); + $enrichment = new Enrichment(); $enrichment->setValue("foo\nbar\baz"); $enrichment->setKeyName('textarea'); @@ -177,7 +184,7 @@ public function testPopulateFromModelRegexType() { $enrichmentKey = $this->createTestEnrichmentKey('regexkey', 'RegexType', ["regex" => "^foo$"]); - $enrichment = new Opus_Enrichment(); + $enrichment = new Enrichment(); $enrichment->setValue("foo"); $enrichment->setKeyName('regexkey'); @@ -197,7 +204,7 @@ public function testPopulateFromModelRegexTypeWithInvalidValue() ] ); - $enrichment = new Opus_Enrichment(); + $enrichment = new Enrichment(); $enrichment->setValue("bar"); // dieser Wert ist gemäß der Typkonfiguration nicht gültig $enrichment->setKeyName('regexkey'); @@ -241,16 +248,16 @@ private function assertFormElementValues($enrichment, $valueFormElementName) public function testUpdateModel() { - $keyNames = Opus_EnrichmentKey::getAll(); + $keyNames = EnrichmentKey::getAll(); $keyName = $keyNames[1]->getName(); // Geht davon aus, dass mindestens 2 Enrichment Keys existieren $form = new Admin_Form_Document_Enrichment(); - $form->initEnrichmentValueElement($keyName); + $form->initValueFormElement($keyName); $form->getElement('KeyName')->setValue($keyName); $form->getElement('Value')->setValue('Test Enrichment Value'); - $enrichment = new Opus_Enrichment(); + $enrichment = new Enrichment(); $form->updateModel($enrichment); $this->assertEquals($keyName, $enrichment->getKeyName()); @@ -266,12 +273,12 @@ public function testUpdateModelWithSelectType() ); $form = new Admin_Form_Document_Enrichment(); - $form->initEnrichmentValueElement('select'); + $form->initValueFormElement('select'); $form->getElement('KeyName')->setValue('select'); $form->getElement('Value')->setValue(1); // Index des ausgewählten Werts - $enrichment = new Opus_Enrichment(); + $enrichment = new Enrichment(); $enrichment->setValue('foo'); // das Enrichment-Formular wird nur für Enrichments mit gesetztem Wert aufgerufen $form->updateModel($enrichment); @@ -281,7 +288,7 @@ public function testUpdateModelWithSelectType() $this->assertEquals('bar', $enrichment->getValue()); } - public function testUpdateModelWithSelectTypeWithInvalidValueAndNoValidationAndInvalidValue() + public function testUpdateModelWithSelectTypeWithInvalidValueAndNoValidation() { $enrichmentKey = $this->createTestEnrichmentKey( 'select', @@ -292,21 +299,21 @@ public function testUpdateModelWithSelectTypeWithInvalidValueAndNoValidationAndI ] ); - $enrichmentId = $this->createTestDocWithEnrichmentOfGivenKey('select', 'foobar'); + $enrichmentId = $this->createTestDocWithEnrichmentOfGivenKey('select'); $form = new Admin_Form_Document_Enrichment(); - $form->initEnrichmentValueElement('select', $enrichmentId); + $form->initValueFormElement('select', $enrichmentId); $form->getElement('KeyName')->setValue('select'); $form->getElement('Value')->setValue(0); // Index des ausgewählten Werts: der Ursprungswert des Enrichments (foobar) - $enrichment = new Opus_Enrichment(); - $enrichment->setValue('foobar'); // das Enrichment-Formular wird nur für Enrichments mit gesetztem Wert aufgerufen + $enrichment = new Enrichment($enrichmentId); $form->updateModel($enrichment); + // cleanup $enrichmentKey->delete(); $this->assertEquals('select', $enrichment->getKeyName()); - $this->assertEquals('foobar', $enrichment->getValue()); + $this->assertEquals('testvalue', $enrichment->getValue()); } public function testUpdateModelWithSelectTypeWithInvalidValueAndNoValidationAndValidValue() @@ -320,15 +327,14 @@ public function testUpdateModelWithSelectTypeWithInvalidValueAndNoValidationAndV ] ); - $enrichmentId = $this->createTestDocWithEnrichmentOfGivenKey('select', 'foobar'); + $enrichmentId = $this->createTestDocWithEnrichmentOfGivenKey('select'); $form = new Admin_Form_Document_Enrichment(); - $form->initEnrichmentValueElement('select', $enrichmentId); + $form->initValueFormElement('select', $enrichmentId); $form->getElement('KeyName')->setValue('select'); $form->getElement('Value')->setValue(1); // Index des ausgewählten Werts: foo - $enrichment = new Opus_Enrichment(); - $enrichment->setValue('foobar'); // das Enrichment-Formular wird nur für Enrichments mit gesetztem Wert aufgerufen + $enrichment = new Enrichment($enrichmentId); $form->updateModel($enrichment); $enrichmentKey->delete(); @@ -339,15 +345,15 @@ public function testUpdateModelWithSelectTypeWithInvalidValueAndNoValidationAndV public function testGetModel() { - $document = new Opus_Document(146); + $document = Document::get(146); $enrichments = $document->getEnrichment(); $enrichment = $enrichments[0]; - $keyNames = Opus_EnrichmentKey::getAll(); + $keyNames = EnrichmentKey::getAll(); $keyName = $keyNames[1]->getName(); // Geht davon aus, dass mindestens 2 Enrichment Keys existieren $form = new Admin_Form_Document_Enrichment(); - $form->initEnrichmentValueElement($keyName); + $form->initValueFormElement($keyName); $form->getElement('Id')->setValue($enrichment->getId()); $form->getElement('KeyName')->setValue($keyName); $form->getElement('Value')->setValue('Test Enrichment Value'); @@ -361,11 +367,11 @@ public function testGetModel() public function testGetNewModel() { - $keyNames = Opus_EnrichmentKey::getAll(); + $keyNames = EnrichmentKey::getAll(); $keyName = $keyNames[1]->getName(); // Geht davon aus, dass mindestens 2 Enrichment Keys existieren $form = new Admin_Form_Document_Enrichment(); - $form->initEnrichmentValueElement($keyName); + $form->initValueFormElement($keyName); $form->getElement('KeyName')->setValue($keyName); $form->getElement('Value')->setValue('Test Enrichment Value'); @@ -379,11 +385,11 @@ public function testGetNewModel() public function testGetModelUnknownId() { - $keyNames = Opus_EnrichmentKey::getAll(); + $keyNames = EnrichmentKey::getAll(); $keyName = $keyNames[1]->getName(); // Geht davon aus, dass mindestens 2 Enrichment Keys existieren $form = new Admin_Form_Document_Enrichment(); - $form->initEnrichmentValueElement($keyName); + $form->initValueFormElement($keyName); $logger = new MockLogger(); @@ -406,11 +412,11 @@ public function testGetModelUnknownId() public function testGetModelBadId() { - $keyNames = Opus_EnrichmentKey::getAll(); + $keyNames = EnrichmentKey::getAll(); $keyName = $keyNames[1]->getName(); // Geht davon aus, dass mindestens 2 Enrichment Keys existieren $form = new Admin_Form_Document_Enrichment(); - $form->initEnrichmentValueElement($keyName); + $form->initValueFormElement($keyName); $form->getElement('Id')->setValue('bad'); $form->getElement('KeyName')->setValue($keyName); @@ -425,12 +431,12 @@ public function testGetModelBadId() public function testValidationWithoutType() { - $keyNames = Opus_EnrichmentKey::getAll(); - $keyName = $keyNames[1]->getName(); // Geht davon aus, dass mindestens 2 Enrichment Keys existieren + $keyNames = EnrichmentKey::getAll(); + $keyName = $keyNames[1]->getName(); // Test geht davon aus, dass mindestens 2 Enrichment Keys existieren $form = new Admin_Form_Document_Enrichment(); $form->setName('Enrichment0'); - $form->initEnrichmentValueElement($keyName); + $form->initValueFormElement($keyName); $post = [ 'Enrichment0' => [ @@ -446,52 +452,112 @@ public function testValidationWithoutType() $this->assertContains('notInArray', $form->getErrors('KeyName')); $this->assertCount(1, $form->getErrors('Value')); - $this->assertContains('isEmpty', $form->getErrors('Value')); + $this->assertContains('admin_enrichment_errorMessage', $form->getElement('Value')->getErrorMessages()); } - public function testValidationWithSelectType() + private function createTestSelectType($options, $strictValidation = false) { - $options = ['foo', 'bar', 'baz']; $selectOptions = ['values' => $options]; - $type = new Opus_Enrichment_SelectType(); + if ($strictValidation) { + $selectOptions['validation'] = 'strict'; + } else { + $selectOptions['validation'] = 'none'; + } + + $type = new SelectType(); $type->setOptions($selectOptions); + return $type; + } + + private function createTestRegexType($regex, $strictValidation = false) + { + $options = ['regex' => $regex]; + if ($strictValidation) { + $options['validation'] = 'strict'; + } else { + $options['validation'] = 'none'; + } - $enrichmentKey = $this->createEnrichmentKeyAndForm('select', $type); + $type = new RegexType(); + $type->setOptions($options); + return $type; + } + + public function testValidationNoneWithSelectTypeFirstOption() + { + $options = ['foo', 'bar', 'baz']; + $type = $this->createTestSelectType($options); + + $enrichmentKey = $this->createEnrichmentKey('select', $type); + $enrichmentId = $this->createTestDocWithEnrichmentOfGivenKey('select', $options[0]); $form = new Admin_Form_Document_Enrichment(); $form->setName('Enrichment0'); - $form->initEnrichmentValueElement('select'); + $form->initValueFormElement('select'); $post = [ 'Enrichment0' => [ + 'Id' => $enrichmentId, 'KeyName' => 'select', - 'Value' => 1 + 'Value' => 0 // entspricht dem ersten Auswahlwert (foo) ] ]; $result = $form->isValid($post); + + // cleanup + $enrichmentKey->delete(); + $this->assertTrue($result); $this->assertCount(0, $form->getErrors('KeyName')); $this->assertCount(0, $form->getErrors('Value')); + } + public function testValidationNoneWithSelectTypeLastOption() + { + $options = ['foo', 'bar', 'baz']; + $type = $this->createTestSelectType($options); + + $enrichmentKey = $this->createEnrichmentKey('select', $type); + $enrichmentId = $this->createTestDocWithEnrichmentOfGivenKey('select', $options[count($options) - 1]); + + $form = new Admin_Form_Document_Enrichment(); + $form->setName('Enrichment0'); + $form->initValueFormElement('select'); + + $post = [ + 'Enrichment0' => [ + 'Id' => $enrichmentId, + 'KeyName' => 'select', + 'Value' => count($options) - 1 // entspricht dem letzten Auswahlwert (baz) + ] + ]; + + $result = $form->isValid($post); + + // cleanup $enrichmentKey->delete(); + + $this->assertTrue($result); + + $this->assertCount(0, $form->getErrors('KeyName')); + $this->assertCount(0, $form->getErrors('Value')); } - public function testValidationWithSelectTypeMissingValue() + public function testValidationNoneWithSelectTypeAndMissingValue() { $options = ['foo', 'bar', 'baz']; - $selectOptions = ['values' => $options]; - $type = new Opus_Enrichment_SelectType(); - $type->setOptions($selectOptions); + $type = $this->createTestSelectType($options); - $enrichmentKey = $this->createEnrichmentKeyAndForm('select', $type); + $enrichmentKey = $this->createEnrichmentKey('select', $type); $enrichmentId = $this->createTestDocWithEnrichmentOfGivenKey('select'); $form = new Admin_Form_Document_Enrichment(); $form->setName('Enrichment0'); - $form->initEnrichmentValueElement('select'); + $form->initValueFormElement('select'); + // im POST-Request fehlt die Angabe des ausgewählten Wertes des Select-Formularfelds $post = [ 'Enrichment0' => [ 'Id' => $enrichmentId, @@ -499,126 +565,237 @@ public function testValidationWithSelectTypeMissingValue() ] ]; - $this->assertFalse($form->isValid($post)); + $result = $form->isValid($post); + + // cleanup + $enrichmentKey->delete(); + + $this->assertFalse($result); $this->assertCount(0, $form->getErrors('KeyName')); $this->assertCount(1, $form->getErrors('Value')); - $this->assertContains('isEmpty', $form->getErrors('Value')); - - $enrichmentKey->delete(); + $this->assertContains('admin_enrichment_errorMessage', $form->getElement('Value')->getErrorMessages()); } - public function testValidationWithSelectTypeInvalidValue() + public function testValidationNoneWithSelectTypeAndInvalidValue() { $options = ['foo', 'bar', 'baz']; - $selectOptions = ['values' => $options]; - $type = new Opus_Enrichment_SelectType(); - $type->setOptions($selectOptions); + $type = $this->createTestSelectType($options); - $enrichmentKey = $this->createEnrichmentKeyAndForm('select', $type); + $enrichmentKey = $this->createEnrichmentKey('select', $type); $enrichmentId = $this->createTestDocWithEnrichmentOfGivenKey('select'); $form = new Admin_Form_Document_Enrichment(); $form->setName('Enrichment0'); - $form->initEnrichmentValueElement('select'); + $form->initValueFormElement('select'); $post = [ 'Enrichment0' => [ 'Id' => $enrichmentId, 'KeyName' => 'select', - 'Value' => 3 // es gibt keine 4. Option (nur Werte von 0 bis 2 erlaubt) + 'Value' => count($options) + 1 // diese Option nicht zulässig ] ]; - $this->assertFalse($form->isValid($post)); + $result = $form->isValid($post); + + // cleanup + $enrichmentKey->delete(); + + $this->assertFalse($result); $this->assertCount(0, $form->getErrors('KeyName')); $this->assertCount(1, $form->getErrors('Value')); - $this->assertContains('notInArray', $form->getErrors('Value')); + $this->assertContains('admin_enrichment_errorMessage', $form->getElement('Value')->getErrorMessages()); + } + public function testValidationNoneWithSelectTypeAndValidValue() + { + $options = ['foo', 'bar', 'baz']; + $type = $this->createTestSelectType($options); + + $enrichmentKey = $this->createEnrichmentKey('select', $type); + $enrichmentId = $this->createTestDocWithEnrichmentOfGivenKey('select'); + + $form = new Admin_Form_Document_Enrichment(); + $form->setName('Enrichment0'); + $form->initValueFormElement('select', $enrichmentId, count($options)); + + $post = [ + 'Enrichment0' => [ + 'Id' => $enrichmentId, + 'KeyName' => 'select', + 'Value' => count($options) // Option ist zulässig (weil Select-Liste um ungültigen Wert ergänzt wurde) + ] + ]; + + $result = $form->isValid($post); + + $enrichment = new Enrichment($enrichmentId); + $form->updateModel($enrichment); + $enrichmentValue = $enrichment->getValue(); + + // cleanup $enrichmentKey->delete(); + + $this->assertTrue($result); + + $this->assertCount(0, $form->getErrors('KeyName')); + $this->assertCount(0, $form->getErrors('Value')); + + $this->assertEquals($options[count($options) - 1], $enrichmentValue); } - public function testValidationWithSelectTypeAndStrictValidationAndInvalidValue() + public function testValidationNoneWithSelectTypeAndAcceptedValue() { $options = ['foo', 'bar', 'baz']; - $selectOptions = ['values' => $options, 'validation' => 'strict']; - $type = new Opus_Enrichment_SelectType(); - $type->setOptions($selectOptions); + $type = $this->createTestSelectType($options); - $enrichmentKey = $this->createEnrichmentKeyAndForm('select', $type); - $enrichmentId = $this->createTestDocWithEnrichmentOfGivenKey('select', 'foobar'); + $enrichmentKey = $this->createEnrichmentKey('select', $type); + $enrichmentId = $this->createTestDocWithEnrichmentOfGivenKey('select'); $form = new Admin_Form_Document_Enrichment(); $form->setName('Enrichment0'); - $form->initEnrichmentValueElement('select', $enrichmentId); + $form->initValueFormElement('select', $enrichmentId, count($options)); $post = [ 'Enrichment0' => [ 'Id' => $enrichmentId, 'KeyName' => 'select', - 'Value' => 0 // wählt den im Enrichment gespeicherten Wert (foobar) aus + 'Value' => 0 // Option ist zulässig (weil Select-Liste um ungültigen Wert ergänzt wurde) ] ]; - $this->assertFalse($form->isValid($post)); + $result = $form->isValid($post); + + $enrichment = new Enrichment($enrichmentId); + $form->updateModel($enrichment); + $enrichmentValue = $enrichment->getValue(); + + // cleanup + $enrichmentKey->delete(); + + $this->assertTrue($result); $this->assertCount(0, $form->getErrors('KeyName')); + $this->assertCount(0, $form->getErrors('Value')); - $this->assertCount(1, $form->getErrors('Value')); - $this->assertContains('notInArray', $form->getErrors('Value')); + $this->assertEquals('testvalue', $enrichmentValue); + } + + public function testValidationStrictWithSelectTypeAndInvalidValue() + { + $options = ['foo', 'bar', 'baz']; + $type = $this->createTestSelectType($options, true); + + $enrichmentKey = $this->createEnrichmentKey('select', $type); + $enrichmentId = $this->createTestDocWithEnrichmentOfGivenKey('select'); + + $form = new Admin_Form_Document_Enrichment(); + $form->setName('Enrichment0'); + $form->initValueFormElement('select', $enrichmentId); + $post = [ + 'Enrichment0' => [ + 'Id' => $enrichmentId, + 'KeyName' => 'select', + 'Value' => 0 // wählt den im Enrichment gespeicherten Wert (foobar) aus, der aber nicht mehr zulässig ist + ] + ]; + + $result = $form->isValid($post); + + // cleanup $enrichmentKey->delete(); + + $this->assertFalse($result); + + $this->assertCount(0, $form->getErrors('KeyName')); + + $this->assertCount(1, $form->getElement('Value')->getErrorMessages()); } - public function testValidationWithSelectTypeAndStrictValidationAndValidValue() + public function testValidationStrictWithSelectTypeAndFirstValidValue() { $options = ['foo', 'bar', 'baz']; - $selectOptions = ['values' => $options, 'validation' => 'strict']; - $type = new Opus_Enrichment_SelectType(); - $type->setOptions($selectOptions); + $type = $this->createTestSelectType($options, true); - $enrichmentKey = $this->createEnrichmentKeyAndForm('select', $type); - $enrichmentId = $this->createTestDocWithEnrichmentOfGivenKey('select', 'foobar'); + $enrichmentKey = $this->createEnrichmentKey('select', $type); + $enrichmentId = $this->createTestDocWithEnrichmentOfGivenKey('select'); $form = new Admin_Form_Document_Enrichment(); $form->setName('Enrichment0'); - $form->initEnrichmentValueElement('select', $enrichmentId); + $form->initValueFormElement('select', $enrichmentId); $post = [ 'Enrichment0' => [ 'Id' => $enrichmentId, 'KeyName' => 'select', - 'Value' => 3 // wählt den baz aus + 'Value' => 1 // wählt den ersten Auswahlfeld aus Typkonfiguration (foo) aus ] ]; - $this->assertTrue($form->isValid($post)); + $result = $form->isValid($post); + + $this->assertTrue($result); $this->assertCount(0, $form->getErrors('KeyName')); $this->assertCount(0, $form->getErrors('Value')); - $enrichment = new Opus_Enrichment($enrichmentId); + $enrichment = new Enrichment($enrichmentId); $form->updateModel($enrichment); - $this->assertEquals('baz', $enrichment->getValue()); + $this->assertEquals($options[0], $enrichment->getValue()); - $enrichmentKey->delete(); + // cleanup (darf erst nach dem Aufruf der updateModel-Methode passieren) + $enrichmentKey->delete(false); + } + + public function testValidationStrictWithSelectTypeAndLastValidValue() + { + $options = ['foo', 'bar', 'baz']; + $type = $this->createTestSelectType($options, true); + + $enrichmentKey = $this->createEnrichmentKey('select', $type); + $enrichmentId = $this->createTestDocWithEnrichmentOfGivenKey('select'); + + $form = new Admin_Form_Document_Enrichment(); + $form->setName('Enrichment0'); + $form->initValueFormElement('select', $enrichmentId); + + $post = [ + 'Enrichment0' => [ + 'Id' => $enrichmentId, + 'KeyName' => 'select', + 'Value' => count($options) // wählt den letzten Auswahlfeld aus Typkonfiguration (baz) aus + ] + ]; + + $result = $form->isValid($post); + + $this->assertTrue($result); + $this->assertCount(0, $form->getErrors('KeyName')); + $this->assertCount(0, $form->getErrors('Value')); + + $enrichment = new Enrichment($enrichmentId); + $form->updateModel($enrichment); + $this->assertEquals($options[count($options) - 1], $enrichment->getValue()); + + // cleanup (darf erst nach dem Aufruf der updateModel-Methode passieren) + $enrichmentKey->delete(false); } public function testValidationWithSelectTypeAndNoValidationAndInvalidValue() { $options = ['foo', 'bar', 'baz']; - $selectOptions = ['values' => $options, 'validation' => 'none']; - $type = new Opus_Enrichment_SelectType(); - $type->setOptions($selectOptions); + $type = $this->createTestSelectType($options); - $enrichmentKey = $this->createEnrichmentKeyAndForm('select', $type); - $enrichmentId = $this->createTestDocWithEnrichmentOfGivenKey('select', 'foobar'); + $enrichmentKey = $this->createEnrichmentKey('select', $type); + $enrichmentId = $this->createTestDocWithEnrichmentOfGivenKey('select'); $form = new Admin_Form_Document_Enrichment(); $form->setName('Enrichment0'); - $form->initEnrichmentValueElement('select', $enrichmentId); + $form->initValueFormElement('select', $enrichmentId); $post = [ 'Enrichment0' => [ @@ -632,24 +809,23 @@ public function testValidationWithSelectTypeAndNoValidationAndInvalidValue() $this->assertCount(0, $form->getErrors('KeyName')); $this->assertCount(0, $form->getErrors('Value')); - $enrichment = new Opus_Enrichment($enrichmentId); + $enrichment = new Enrichment($enrichmentId); $form->updateModel($enrichment); - $this->assertEquals('foobar', $enrichment->getValue()); + $this->assertEquals('testvalue', $enrichment->getValue()); $enrichmentKey->delete(); } public function testValidationWithRegexType() { - $type = new Opus_Enrichment_RegexType(); - $type->setOptions(['regex' => '^abc$']); + $type = $this->createTestRegexType('^abc$'); - $enrichmentKey = $this->createEnrichmentKeyAndForm('regex', $type); + $enrichmentKey = $this->createEnrichmentKey('regex', $type); $enrichmentId = $this->createTestDocWithEnrichmentOfGivenKey('regex'); $form = new Admin_Form_Document_Enrichment(); $form->setName('Enrichment0'); - $form->initEnrichmentValueElement('regex'); + $form->initValueFormElement('regex'); $post = [ 'Enrichment0' => [ @@ -661,25 +837,24 @@ public function testValidationWithRegexType() $this->assertFalse($form->isValid($post)); - $this->assertCount(0, $form->getErrors('KeyName')); + // cleanup + $enrichmentKey->delete(); + $this->assertCount(0, $form->getErrors('KeyName')); $this->assertCount(1, $form->getErrors('Value')); - $this->assertContains('regexNotMatch', $form->getErrors('Value')); - - $enrichmentKey->delete(); + $this->assertContains('admin_enrichment_errorMessage', $form->getElement('Value')->getErrorMessages()); } public function testValidationWithRegexTypeWithMissingValue() { - $type = new Opus_Enrichment_RegexType(); - $type->setOptions(['regex' => '^.*$']); + $type = $this->createTestRegexType('^.*$'); - $enrichmentKey = $this->createEnrichmentKeyAndForm('regex', $type); + $enrichmentKey = $this->createEnrichmentKey('regex', $type); $enrichmentId = $this->createTestDocWithEnrichmentOfGivenKey('regex'); $form = new Admin_Form_Document_Enrichment(); $form->setName('Enrichment0'); - $form->initEnrichmentValueElement('regex'); + $form->initValueFormElement('regex'); $post = [ 'Enrichment0' => [ @@ -691,27 +866,26 @@ public function testValidationWithRegexTypeWithMissingValue() $this->assertFalse($form->isValid($post)); - $this->assertCount(0, $form->getErrors('KeyName')); + // cleanup + $enrichmentKey->delete(); + $this->assertCount(0, $form->getErrors('KeyName')); $this->assertCount(1, $form->getErrors('Value')); - $this->assertContains('isEmpty', $form->getErrors('Value')); - - $enrichmentKey->delete(); + $this->assertContains('admin_enrichment_errorMessage', $form->getElement('Value')->getErrorMessages()); } public function testValidationWithRegexTypeUsedByFirstEnrichmentKey() { - $type = new Opus_Enrichment_RegexType(); - $type->setOptions(['regex' => '^abc$']); + $type = $this->createTestRegexType('^abc$'); // mit dem Namen soll sichergestellt werden, dass dieser Enrichment-Key // in der Auswahlliste als erster Eintrag auftritt - $enrichmentKey = $this->createEnrichmentKeyAndForm('aaaaaaaa', $type); + $enrichmentKey = $this->createEnrichmentKey('aaaaaaaa', $type); $enrichmentId = $this->createTestDocWithEnrichmentOfGivenKey('aaaaaaaa'); $form = new Admin_Form_Document_Enrichment(); $form->setName('Enrichment0'); - $form->initEnrichmentValueElement(); + $form->initValueFormElement(); $post = [ 'Enrichment0' => [ @@ -723,25 +897,24 @@ public function testValidationWithRegexTypeUsedByFirstEnrichmentKey() $this->assertFalse($form->isValid($post)); - $this->assertCount(0, $form->getErrors('KeyName')); + // cleanup + $enrichmentKey->delete(); + $this->assertCount(0, $form->getErrors('KeyName')); $this->assertCount(1, $form->getErrors('Value')); - $this->assertContains('regexNotMatch', $form->getErrors('Value')); - - $enrichmentKey->delete(); + $this->assertContains('admin_enrichment_errorMessage', $form->getElement('Value')->getErrorMessages()); } - public function testValidationWithRegexTypeAndStrictValidationWithInvalidOriginalValue() + public function testValidationStrictWithRegexTypeAndInvalidOriginalValue() { - $type = new Opus_Enrichment_RegexType(); - $type->setOptions(['regex' => '^abc$', 'validation' => 'strict']); + $type = $this->createTestRegexType('^abc$', true); - $enrichmentKey = $this->createEnrichmentKeyAndForm('regex', $type); + $enrichmentKey = $this->createEnrichmentKey('regex', $type); $enrichmentId = $this->createTestDocWithEnrichmentOfGivenKey('regex', 'invalidvalue'); $form = new Admin_Form_Document_Enrichment(); $form->setName('Enrichment0'); - $form->initEnrichmentValueElement('regex', $enrichmentId); + $form->initValueFormElement('regex', $enrichmentId); $post = [ 'Enrichment0' => [ @@ -753,25 +926,24 @@ public function testValidationWithRegexTypeAndStrictValidationWithInvalidOrigina $this->assertFalse($form->isValid($post)); - $this->assertCount(0, $form->getErrors('KeyName')); + // cleanup + $enrichmentKey->delete(); + $this->assertCount(0, $form->getErrors('KeyName')); $this->assertCount(1, $form->getErrors('Value')); - $this->assertContains('regexNotMatch', $form->getErrors('Value')); - - $enrichmentKey->delete(); + $this->assertContains('admin_enrichment_errorMessage', $form->getElement('Value')->getErrorMessages()); } - public function testValidationWithRegexTypeAndStrictValidationWithInvalidChangedValue() + public function testValidationStrictWithRegexTypeAndInvalidChangedValue() { - $type = new Opus_Enrichment_RegexType(); - $type->setOptions(['regex' => '^abc$', 'validation' => 'strict']); + $type = $this->createTestRegexType('^abc$', true); - $enrichmentKey = $this->createEnrichmentKeyAndForm('regex', $type); + $enrichmentKey = $this->createEnrichmentKey('regex', $type); $enrichmentId = $this->createTestDocWithEnrichmentOfGivenKey('regex', 'invalidvalue'); $form = new Admin_Form_Document_Enrichment(); $form->setName('Enrichment0'); - $form->initEnrichmentValueElement('regex', $enrichmentId); + $form->initValueFormElement('regex', $enrichmentId); $post = [ 'Enrichment0' => [ @@ -783,25 +955,24 @@ public function testValidationWithRegexTypeAndStrictValidationWithInvalidChanged $this->assertFalse($form->isValid($post)); - $this->assertCount(0, $form->getErrors('KeyName')); + // cleanup + $enrichmentKey->delete(); + $this->assertCount(0, $form->getErrors('KeyName')); $this->assertCount(1, $form->getErrors('Value')); - $this->assertContains('regexNotMatch', $form->getErrors('Value')); - - $enrichmentKey->delete(); + $this->assertContains('admin_enrichment_errorMessage', $form->getElement('Value')->getErrorMessages()); } - public function testValidationWithRegexTypeAndStrictValidationWithValidValue() + public function testValidationStrictWithRegexTypeAndValidValue() { - $type = new Opus_Enrichment_RegexType(); - $type->setOptions(['regex' => '^abc$', 'validation' => 'strict']); + $type = $this->createTestRegexType('^abc$', true); - $enrichmentKey = $this->createEnrichmentKeyAndForm('regex', $type); + $enrichmentKey = $this->createEnrichmentKey('regex', $type); $enrichmentId = $this->createTestDocWithEnrichmentOfGivenKey('regex', 'abc'); $form = new Admin_Form_Document_Enrichment(); $form->setName('Enrichment0'); - $form->initEnrichmentValueElement('regex', $enrichmentId); + $form->initValueFormElement('regex', $enrichmentId); $post = [ 'Enrichment0' => [ @@ -813,23 +984,23 @@ public function testValidationWithRegexTypeAndStrictValidationWithValidValue() $this->assertTrue($form->isValid($post)); + //cleanup + $enrichmentKey->delete(); + $this->assertCount(0, $form->getErrors('KeyName')); $this->assertCount(0, $form->getErrors('Value')); - - $enrichmentKey->delete(); } - public function testValidationWithRegexTypeAndNoValidationWithInvalidOriginalValue() + public function testValidationNoneWithRegexTypeAndInvalidOriginalValue() { - $type = new Opus_Enrichment_RegexType(); - $type->setOptions(['regex' => '^abc$', 'validation' => 'none']); + $type = $this->createTestRegexType('^abc$'); - $enrichmentKey = $this->createEnrichmentKeyAndForm('regex', $type); + $enrichmentKey = $this->createEnrichmentKey('regex', $type); $enrichmentId = $this->createTestDocWithEnrichmentOfGivenKey('regex', 'invalidvalue'); $form = new Admin_Form_Document_Enrichment(); $form->setName('Enrichment0'); - $form->initEnrichmentValueElement('regex', $enrichmentId); + $form->initValueFormElement('regex', $enrichmentId); $post = [ 'Enrichment0' => [ @@ -841,23 +1012,23 @@ public function testValidationWithRegexTypeAndNoValidationWithInvalidOriginalVal $this->assertTrue($form->isValid($post)); + // cleanup + $enrichmentKey->delete(); + $this->assertCount(0, $form->getErrors('KeyName')); $this->assertCount(0, $form->getErrors('Value')); - - $enrichmentKey->delete(); } - public function testValidationWithRegexTypeAndNoValidationWithInvalidChangedValue() + public function testValidationNoneWithRegexTypeAndInvalidChangedValue() { - $type = new Opus_Enrichment_RegexType(); - $type->setOptions(['regex' => '^abc$', 'validation' => 'none']); + $type = $this->createTestRegexType('^abc$'); - $enrichmentKey = $this->createEnrichmentKeyAndForm('regex', $type); + $enrichmentKey = $this->createEnrichmentKey('regex', $type); $enrichmentId = $this->createTestDocWithEnrichmentOfGivenKey('regex', 'invalidvalue'); $form = new Admin_Form_Document_Enrichment(); $form->setName('Enrichment0'); - $form->initEnrichmentValueElement('regex', $enrichmentId); + $form->initValueFormElement('regex', $enrichmentId); $post = [ 'Enrichment0' => [ @@ -869,25 +1040,24 @@ public function testValidationWithRegexTypeAndNoValidationWithInvalidChangedValu $this->assertFalse($form->isValid($post)); - $this->assertCount(0, $form->getErrors('KeyName')); + // cleanup + $enrichmentKey->delete(); + $this->assertCount(0, $form->getErrors('KeyName')); $this->assertCount(1, $form->getErrors('Value')); - $this->assertContains('regexNotMatch', $form->getErrors('Value')); - - $enrichmentKey->delete(); + $this->assertContains('admin_enrichment_errorMessage', $form->getElement('Value')->getErrorMessages()); } - public function testValidationWithRegexTypeAndNoValidationWithValidValue() + public function testValidationNoneWithRegexTypeAndValidValue() { - $type = new Opus_Enrichment_RegexType(); - $type->setOptions(['regex' => '^abc$', 'validation' => 'none']); + $type = $this->createTestRegexType('^abc$'); - $enrichmentKey = $this->createEnrichmentKeyAndForm('regex', $type); + $enrichmentKey = $this->createEnrichmentKey('regex', $type); $enrichmentId = $this->createTestDocWithEnrichmentOfGivenKey('regex', 'abc'); $form = new Admin_Form_Document_Enrichment(); $form->setName('Enrichment0'); - $form->initEnrichmentValueElement('regex', $enrichmentId); + $form->initValueFormElement('regex', $enrichmentId); $post = [ 'Enrichment0' => [ @@ -899,15 +1069,84 @@ public function testValidationWithRegexTypeAndNoValidationWithValidValue() $this->assertTrue($form->isValid($post)); + // cleanup + $enrichmentKey->delete(); + $this->assertCount(0, $form->getErrors('KeyName')); $this->assertCount(0, $form->getErrors('Value')); + } + + public function testEnrichmentKeySpecificTranslationWithRegexType() + { + $translate = Application_Translate::getInstance(); + $translate->setTranslations('admin_enrichment_ektest_errorMessage', ['de' => 'de', 'en' => 'en']); + $translate->loadTranslations(true); + + $type = $this->createTestRegexType('^abc$'); + $enrichmentKey = $this->createEnrichmentKey('ektest', $type); + $enrichmentId = $this->createTestDocWithEnrichmentOfGivenKey('ektest', 'invalidvalue'); + + $form = new Admin_Form_Document_Enrichment(); + $form->setName('Enrichment0'); + $form->initValueFormElement('ektest', $enrichmentId); + + $post = [ + 'Enrichment0' => [ + 'Id' => $enrichmentId, + 'KeyName' => 'ektest', + 'Value' => 'anotherinvalidvalue' // invalid value + ] + ]; + + $this->assertFalse($form->isValid($post)); + // cleanup $enrichmentKey->delete(); + + $this->assertCount(1, $form->getErrors('Value')); + $this->assertContains('admin_enrichment_ektest_errorMessage', $form->getElement('Value')->getErrorMessages()); + } + + public function testEnrichmentKeySpecificTranslationWithSelectType() + { + $translate = Application_Translate::getInstance(); + $translate->setTranslations('admin_enrichment_ektest_errorMessage', ['de' => 'de', 'en' => 'en']); + $translate->loadTranslations(true); + + $options = ['foo', 'bar', 'baz']; + $type = $this->createTestSelectType($options); + + $enrichmentKey = $this->createEnrichmentKey('ektest', $type); + $enrichmentId = $this->createTestDocWithEnrichmentOfGivenKey('ektest'); + + $form = new Admin_Form_Document_Enrichment(); + $form->setName('Enrichment0'); + $form->initValueFormElement('ektest'); + + $post = [ + 'Enrichment0' => [ + 'Id' => $enrichmentId, + 'KeyName' => 'ektest', + 'Value' => count($options) + 1 // diese Option nicht zulässig + ] + ]; + + $result = $form->isValid($post); + + // cleanup + $enrichmentKey->delete(); + + $this->assertFalse($result); + + $this->assertCount(0, $form->getErrors('KeyName')); + + $this->assertCount(1, $form->getErrors('Value')); + $this->assertContains('admin_enrichment_ektest_errorMessage', $form->getElement('Value')->getErrorMessages()); } private function createTestEnrichmentKey($name, $type = null, $options = null) { - $enrichmentKey = new Opus_EnrichmentKey(); + $enrichmentKey = new EnrichmentKey(); $enrichmentKey->setName($name); if (! is_null($type)) { @@ -925,21 +1164,28 @@ private function createTestEnrichmentKey($name, $type = null, $options = null) return $enrichmentKey; } - private function createEnrichmentKeyAndForm($name, $type) + private function createEnrichmentKey($name, $type) { $enrichmentKey = $this->createTestEnrichmentKey($name, $type->getName(), $type->getOptions()); - // Methodenaufruf hier erforderlich, damit der interne Cache, in dem + // Methodenaufruf des All-Finders hier erforderlich, damit der interne Cache, in dem // alle EnrichmentKeys gehalten werden, neu aufgesetzt wird - Opus_EnrichmentKey::getAll(); + EnrichmentKey::getAll(); return $enrichmentKey; } public function testPrepareRenderingAsView() { + $enrichmentKey = $this->createEnrichmentKey('text', new TextType()); + $enrichmentId = $this->createTestDocWithEnrichmentOfGivenKey('text'); + $form = new Admin_Form_Document_Enrichment(); + $form->populateFromModel(new Enrichment($enrichmentId)); $form->prepareRenderingAsView(); + + $enrichmentKey->delete(); + $this->assertFalse($form->isRemoveEmptyCheckbox()); } @@ -954,13 +1200,13 @@ public function testPrepareRenderingAsView() private function createTestDocWithEnrichmentOfGivenKey($keyName, $enrichmentValue = 'testvalue') { $doc = $this->createTestDocument(); - $enrichment = new Opus_Enrichment(); + $enrichment = new Enrichment(); $enrichment->setKeyName($keyName); $enrichment->setValue($enrichmentValue); $doc->addEnrichment($enrichment); $docId = $doc->store(); - $doc = new Opus_Document($docId); + $doc = Document::get($docId); $enrichment = $doc->getEnrichment()[0]; return $enrichment->getId(); } diff --git a/tests/modules/admin/forms/Document/FileTest.php b/tests/modules/admin/forms/Document/FileTest.php index fdb24795e3..92ca88fc1d 100644 --- a/tests/modules/admin/forms/Document/FileTest.php +++ b/tests/modules/admin/forms/Document/FileTest.php @@ -31,6 +31,9 @@ * @copyright Copyright (c) 2008-2019, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ + +use Opus\File; + class Admin_Form_Document_FileTest extends ControllerTestCase { @@ -50,7 +53,7 @@ public function testPopulateFromModel() { $form = new Admin_Form_Document_File(); - $file = new Opus_File(); + $file = new File(); $this->assertNull($form->getModel()); diff --git a/tests/modules/admin/forms/Document/FilesTest.php b/tests/modules/admin/forms/Document/FilesTest.php index b1b3bf2a47..0f9efdb858 100644 --- a/tests/modules/admin/forms/Document/FilesTest.php +++ b/tests/modules/admin/forms/Document/FilesTest.php @@ -1,5 +1,4 @@ assertEquals(1, count($form->getSubForms())); @@ -83,7 +85,7 @@ public function testColumnLabelTranslations() $header = $property->getValue($form); - $translate = Zend_Registry::get('Zend_Translate'); + $translate = Application_Translate::getInstance(); foreach ($header as $column) { if (isset($column['label']) && ! is_null($column['label'])) { diff --git a/tests/modules/admin/forms/Document/GeneralTest.php b/tests/modules/admin/forms/Document/GeneralTest.php index 149ff9cbaa..196a08314d 100644 --- a/tests/modules/admin/forms/Document/GeneralTest.php +++ b/tests/modules/admin/forms/Document/GeneralTest.php @@ -30,6 +30,8 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Document; + /** * Unit Tests fuer Admin_Form_Document_General. */ @@ -54,13 +56,13 @@ public function testCreateForm() } /** - * TODO use temporary Opus_Document instead of doc from test data + * TODO use temporary Document instead of doc from test data */ public function testPopulateFromModel() { $this->useEnglish(); - $document = new Opus_Document(146); + $document = Document::get(146); $form = new Admin_Form_Document_General(); diff --git a/tests/modules/admin/forms/Document/IdentifierTest.php b/tests/modules/admin/forms/Document/IdentifierTest.php index 7f2fbe91fc..7947539626 100644 --- a/tests/modules/admin/forms/Document/IdentifierTest.php +++ b/tests/modules/admin/forms/Document/IdentifierTest.php @@ -30,6 +30,9 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Document; +use Opus\Identifier; + /** * Unit Test fuer Identifier Formular Klasse. */ @@ -52,7 +55,7 @@ public function testCreateForm() } /** - * Testet das Setzen der Elemente entsprechend Opus_Identifier. + * Testet das Setzen der Elemente entsprechend Identifier. * * Dokument 146 wird verwendet, da es vollständig besetzt ist und normalerweise in den Unit Tests nicht modifiziert * wird. @@ -61,7 +64,7 @@ public function testPopulateFromModel() { $form = new Admin_Form_Document_Identifier(); - $document = new Opus_Document(146); + $document = Document::get(146); $identifiers = $document->getIdentifier(); $identifier = $identifiers[0]; @@ -79,7 +82,7 @@ public function testUpdateModel() $form->getElement('Type')->setValue('url'); $form->getElement('Value')->setValue('test-urn-1'); - $identifier = new Opus_Identifier(); + $identifier = new Identifier(); $form->updateModel($identifier); @@ -112,7 +115,7 @@ public function testGetModelExistingIdentifier() { $form = new Admin_Form_Document_Identifier(); - $document = new Opus_Document(146); + $document = Document::get(146); $identifiers = $document->getIdentifier(); $identifierId = $identifiers[0]->getId(); diff --git a/tests/modules/admin/forms/Document/InstituteTest.php b/tests/modules/admin/forms/Document/InstituteTest.php index b3aff3edb4..dae9d25de4 100644 --- a/tests/modules/admin/forms/Document/InstituteTest.php +++ b/tests/modules/admin/forms/Document/InstituteTest.php @@ -31,6 +31,9 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Document; +use Opus\Model\Dependent\Link\DocumentDnbInstitute; + /** * Unit Tests fuer Unterformular fuer Verknuepfung mit einem Institut im Metadaten-Formular. */ @@ -61,7 +64,7 @@ public function testPopulateFromModel() { $form = new Admin_Form_Document_Institute(Admin_Form_Document_Institute::ROLE_PUBLISHER); - $doc = new Opus_Document(146); + $doc = Document::get(146); $publishers = $doc->getThesisPublisher(); $publisher = $publishers[0]; @@ -77,7 +80,7 @@ public function testUpdateModel() $form->getElement('Institute')->setValue(3); - $model = new Opus_Model_Dependent_Link_DocumentDnbInstitute(); + $model = new DocumentDnbInstitute(); $form->updateModel($model); @@ -88,7 +91,7 @@ public function testGetModel() { $form = new Admin_Form_Document_Institute(Admin_Form_Document_Institute::ROLE_PUBLISHER); - $doc = new Opus_Document(146); + $doc = Document::get(146); $publishers = $doc->getThesisPublisher(); $publisher = $publishers[0]; $publisherId = $publisher->getModel()->getId(); diff --git a/tests/modules/admin/forms/Document/LicencesTest.php b/tests/modules/admin/forms/Document/LicencesTest.php index aec480d078..e9c06a7e67 100644 --- a/tests/modules/admin/forms/Document/LicencesTest.php +++ b/tests/modules/admin/forms/Document/LicencesTest.php @@ -30,6 +30,9 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Document; +use Opus\Licence; + /** * Description of Document_LicencesTest */ @@ -42,7 +45,7 @@ public function testCreateForm() { $form = new Admin_Form_Document_Licences(); - $licences = Opus_Licence::getAll(); + $licences = Licence::getAll(); foreach ($licences as $licence) { $element = $form->getElement('licence' . $licence->getId()); @@ -61,11 +64,11 @@ public function testPopulateFromModel() { $form = new Admin_Form_Document_Licences(); - $document = new Opus_Document(146); + $document = Document::get(146); $form->populateFromModel($document); - $licences = Opus_Licence::getAll(); + $licences = Licence::getAll(); foreach ($licences as $licence) { $element = $form->getElement('licence' . $licence->getId()); @@ -124,8 +127,8 @@ public function testHasLicenceFalse() { $form = new Admin_Form_Document_Licences(); - $document = new Opus_Document(146); - $licence = new Opus_Licence(2); + $document = Document::get(146); + $licence = new Licence(2); $this->assertFalse($form->hasLicence($document, $licence)); } @@ -134,7 +137,7 @@ public function testHasLicenceTrue() { $form = new Admin_Form_Document_Licences(); - $document = new Opus_Document(146); + $document = Document::get(146); $this->assertTrue($form->hasLicence($document, 4)); } diff --git a/tests/modules/admin/forms/Document/MultiEnrichmentSubFormTest.php b/tests/modules/admin/forms/Document/MultiEnrichmentSubFormTest.php index 9de45dd833..e70334c8a5 100644 --- a/tests/modules/admin/forms/Document/MultiEnrichmentSubFormTest.php +++ b/tests/modules/admin/forms/Document/MultiEnrichmentSubFormTest.php @@ -31,6 +31,11 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Document; +use Opus\Enrichment; +use Opus\EnrichmentKey; +use Opus\Model\ModelException; + /** * Unit Tests für Admin_Form_Document_MultiEnrichmentSubForm Formular das * mehrere Unterformulare vom Typ Admin_Form_Document_Enrichment verwalten kann. @@ -38,7 +43,7 @@ class Admin_Form_Document_MultiEnrichmentSubFormTest extends ControllerTestCase { - protected $additionalResources = ['database']; + protected $additionalResources = ['database', 'translation']; // dieser Enrichment-Key Name stellt sicher, dass der Enrichment-Key // im Auswahlfeld aller Enrichment-Keys an der ersten Position steht @@ -49,7 +54,7 @@ public function testGetFieldValues() $form = new Admin_Form_Document_MultiEnrichmentSubForm('Admin_Form_Document_Enrichment', 'Enrichment'); // create a test document with four enrichments - $doc = new Opus_Document(); + $doc = Document::new(); $enrichments = []; $enrichments[] = $this->createEnrichment('Audience', 'val1'); @@ -63,7 +68,7 @@ public function testGetFieldValues() $result = $form->getFieldValues($doc); // cleanup: remove latest test document - $doc->deletePermanent(); + $doc->delete(); // die beiden Enrichments mit dem Schlüssel opus.doi/urn.autoCreate // werden gesondert behandelt und erscheinen daher nicht im Unterformular @@ -86,7 +91,7 @@ public function testPopulateFromModel() ); // create a test document with two enrichments - $doc = new Opus_Document(); + $doc = Document::new(); $enrichments = []; $enrichments[] = $this->createEnrichment('Audience', 'val1'); @@ -105,7 +110,7 @@ public function testPopulateFromModel() $this->assertCount(count($enrichments), $form->getSubForms()); // cleanup: remove latest test document - $doc->deletePermanent(); + $doc->delete(); } public function testConstructFromPost() @@ -277,15 +282,15 @@ public function testProcessPostRemove() * Hilfsfunktion zum Erzeugen eines neuen Enrichments für den übergebenen * Enrichment-Key. * - * @param $keyName Name des Enrichment-Keys - * @param $value Wert des Enrichments + * @param string $keyName Name des Enrichment-Keys + * @param string $value Wert des Enrichments * - * @return Opus_Enrichment neu erzeugtes Enrichment-Objekt - * @throws Opus_Model_Exception + * @return Enrichment neu erzeugtes Enrichment-Objekt + * @throws ModelException */ private function createEnrichment($keyName, $value) { - $enrichment = new Opus_Enrichment(); + $enrichment = new Enrichment(); $enrichment->setKeyName($keyName); $enrichment->setValue($value); return $enrichment; @@ -298,12 +303,12 @@ private function createEnrichment($keyName, $value) * @param null $type optionaler Typ des Enrichment-Keys * @param null $options optionale Konfigurationsoptionen des Typs * - * @return Opus_EnrichmentKey neu erzeugter Enrichment-Key - * @throws Opus_Model_Exception + * @return EnrichmentKey neu erzeugter Enrichment-Key + * @throws ModelException */ private function createEnrichmentKey($type = null, $options = null) { - $enrichmentKey = new Opus_EnrichmentKey(); + $enrichmentKey = new EnrichmentKey(); $enrichmentKey->setName(self::$firstEnrichmentKeyName); if (! is_null($type)) { @@ -316,7 +321,7 @@ private function createEnrichmentKey($type = null, $options = null) $enrichmentKey->store(); - $enrichmentKey = Opus_EnrichmentKey::fetchByName(self::$firstEnrichmentKeyName); + $enrichmentKey = EnrichmentKey::fetchByName(self::$firstEnrichmentKeyName); $this->assertNotNull($enrichmentKey); return $enrichmentKey; @@ -350,7 +355,7 @@ private function createTestPostDataAndConstructForm($keyName, $value, $clickedBu ], ]; - Opus_EnrichmentKey::getAll(); + EnrichmentKey::getAll(); // trifft nur zu, wenn der Add-Button gedrückt oder ein Enrichment-Key im Select-Feld ausgewählt wurde if (! is_null($clickedButton)) { diff --git a/tests/modules/admin/forms/Document/MultiSubFormTest.php b/tests/modules/admin/forms/Document/MultiSubFormTest.php index 4115438b8c..18433be7b6 100644 --- a/tests/modules/admin/forms/Document/MultiSubFormTest.php +++ b/tests/modules/admin/forms/Document/MultiSubFormTest.php @@ -30,6 +30,9 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Document; +use Opus\Title; + /** * Unit Tests für MulitSubForm Formular das mehrere Unterformular des gleichen Typs verwalten kann. */ @@ -86,7 +89,7 @@ public function testPopulateFromModel() new Application_Form_Validate_MultiSubForm_RepeatedLanguages() ); - $document = new Opus_Document(146); + $document = Document::get(146); $form->populateFromModel($document); @@ -126,12 +129,12 @@ public function testGetFieldValues() new Application_Form_Validate_MultiSubForm_RepeatedLanguages() ); - $document = new Opus_Document(146); + $document = Document::get(146); $values = $form->getFieldValues($document); $this->assertEquals(2, count($values)); - $this->assertTrue($values[0] instanceof Opus_Title); + $this->assertTrue($values[0] instanceof Title); $this->assertEquals('sub', $values[0]->getType()); } @@ -206,7 +209,7 @@ public function testProcessPostRemove() new Application_Form_Validate_MultiSubForm_RepeatedLanguages() ); - $document = new Opus_Document(146); + $document = Document::get(146); $form->populateFromModel($document); @@ -268,7 +271,7 @@ public function testGetSubFormModels() new Application_Form_Validate_MultiSubForm_RepeatedLanguages() ); - $document = new Opus_Document(146); + $document = Document::get(146); $form->populateFromModel($document); $form->appendSubForm(); @@ -330,7 +333,7 @@ public function testDetermineSubFormForAnchor() new Application_Form_Validate_MultiSubForm_RepeatedLanguages() ); - $document = new Opus_Document(146); + $document = Document::get(146); $this->assertEquals($form, $form->determineSubFormForAnchor(0)); @@ -456,8 +459,8 @@ public function testPrepareSubFormDecoratorsForTableRendering() 'columns' => $columns ]); - $subform = new Zend_Form_SubForm(); - $subform->addPrefixPath('Application_Form_Decorator', 'Application/Form/Decorator', Zend_Form::DECORATOR); + $subform = new \Zend_Form_SubForm(); + $subform->addPrefixPath('Application_Form_Decorator', 'Application/Form/Decorator', \Zend_Form::DECORATOR); $subform->setDecorators([]); $subform->addElement('text', 'test', ['decorators' => [ @@ -491,7 +494,7 @@ public function testAddRemoveButtonForTableRendering() $method = new ReflectionMethod('Admin_Form_Document_MultiSubForm', 'addRemoveButton'); $method->setAccessible(true); - $subform = new Zend_Form_SubForm(); + $subform = new \Zend_Form_SubForm(); $subform->addElement('hidden', 'Id'); $method->invoke($form, $subform); @@ -525,17 +528,17 @@ public function testOddEven() $document = $this->createTestDocument(); - $title = new Opus_Title(); + $title = new Title(); $title->setValue('Titel1'); $title->setLanguage('deu'); $document->addTitleParent($title); - $title = new Opus_Title(); + $title = new Title(); $title->setValue('Titel2'); $title->setLanguage('eng'); $document->addTitleParent($title); - $title = new Opus_Title(); + $title = new Title(); $title->setValue('Titel3'); $title->setLanguage('rus'); $document->addTitleParent($title); @@ -563,17 +566,17 @@ public function testOddEvenAfterRemove() $document = $this->createTestDocument(); - $title = new Opus_Title(); + $title = new Title(); $title->setValue('Titel1'); $title->setLanguage('deu'); $document->addTitleParent($title); - $title = new Opus_Title(); + $title = new Title(); $title->setValue('Titel2'); $title->setLanguage('eng'); $document->addTitleParent($title); - $title = new Opus_Title(); + $title = new Title(); $title->setValue('Titel3'); $title->setLanguage('rus'); $document->addTitleParent($title); @@ -656,7 +659,7 @@ public function testSubformsAppearInOrderOfObjects() { $form = new Admin_Form_Document_MultiSubForm('Admin_Form_Document_Identifier', 'Identifier'); - $doc = new Opus_Document(146); + $doc = Document::get(146); $identifiers = $doc->getIdentifier(); diff --git a/tests/modules/admin/forms/Document/NoteTest.php b/tests/modules/admin/forms/Document/NoteTest.php index 1931218a7c..d3d0843630 100644 --- a/tests/modules/admin/forms/Document/NoteTest.php +++ b/tests/modules/admin/forms/Document/NoteTest.php @@ -30,6 +30,9 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Document; +use Opus\Note; + /** * Description of Document_NoteTest */ @@ -53,7 +56,7 @@ public function testPopulateFromModel() { $form = new Admin_Form_Document_Note(); - $note = new Opus_Note(); + $note = new Note(); $note->setMessage('Message1'); $note->setVisibility('public'); @@ -76,7 +79,7 @@ public function testUpdateModel() $form->getElement('Message')->setValue('Test Message'); $form->getElement('Visibility')->setChecked(true); - $note = new Opus_Note(); + $note = new Note(); $form->updateModel($note); @@ -94,7 +97,7 @@ public function testGetModel() { $form = new Admin_Form_Document_Note(); - $doc = new Opus_Document(146); + $doc = Document::get(146); $notes = $doc->getNote(); @@ -143,7 +146,7 @@ public function testPrepareRenderingAsView() { $form = new Admin_Form_Document_Note(); - $note = new Opus_Note(); + $note = new Note(); $note->setMessage('Message1'); $note->setVisibility('public'); diff --git a/tests/modules/admin/forms/Document/PatentTest.php b/tests/modules/admin/forms/Document/PatentTest.php index 2e6784ef3e..de6beef809 100644 --- a/tests/modules/admin/forms/Document/PatentTest.php +++ b/tests/modules/admin/forms/Document/PatentTest.php @@ -30,6 +30,9 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Document; +use Opus\Patent; + /** * Unit Tests fuer Admin_Form_Document_Patent. */ @@ -59,7 +62,7 @@ public function testPopulateFromModel() $form = new Admin_Form_Document_Patent(); - $document = new Opus_Document(146); + $document = Document::get(146); $patents = $document->getPatent(); $patent = $patents[0]; $patentId = $patent->getId(); @@ -88,7 +91,7 @@ public function testUpdateModel() $form->getElement('Application')->setValue('Patent Title'); $form->getElement('DateGranted')->setValue('2008/03/20'); - $patent = new Opus_Patent(); + $patent = new Patent(); $form->updateModel($patent); @@ -129,7 +132,7 @@ public function testGetModel() { $this->useEnglish(); - $document = new Opus_Document(146); + $document = Document::get(146); $patents = $document->getPatent(); $patentId = $patents[0]->getId(); @@ -243,7 +246,7 @@ public function testRegressionOpusvier2824() $form->getElement('Countries')->setValue('Germany'); $form->getElement('Application')->setValue('description'); - $patent = new Opus_Patent(); + $patent = new Patent(); $form->updateModel($patent); @@ -254,7 +257,7 @@ public function testRegressionOpusvier2824() $documentId = $document->getId(); - $document = new Opus_Document($documentId); + $document = Document::get($documentId); $patents = $document->getPatent(); $patent = $patents[0]; diff --git a/tests/modules/admin/forms/Document/PersonMovesTest.php b/tests/modules/admin/forms/Document/PersonMovesTest.php index 65cd1cf63e..f8fcaa90c3 100644 --- a/tests/modules/admin/forms/Document/PersonMovesTest.php +++ b/tests/modules/admin/forms/Document/PersonMovesTest.php @@ -37,7 +37,7 @@ public function testConstructForm() { $form = new Admin_Form_Document_PersonMoves(); - $this->assertEquals(4, count($form->getElements())); + $this->assertCount(4, $form->getElements()); $this->assertNotNull($form->getElement('First')); $this->assertNotNull($form->getElement('Up')); @@ -49,7 +49,7 @@ public function testConstructFormPositionFirst() { $form = new Admin_Form_Document_PersonMoves(Admin_Form_Document_PersonMoves::POSITION_FIRST); - $this->assertEquals(2, count($form->getElements())); + $this->assertCount(2, $form->getElements()); $this->assertNotNull($form->getElement('Down')); $this->assertNotNull($form->getElement('Last')); @@ -59,7 +59,7 @@ public function testConstructFormPositionLast() { $form = new Admin_Form_Document_PersonMoves(Admin_Form_Document_PersonMoves::POSITION_LAST); - $this->assertEquals(2, count($form->getElements())); + $this->assertCount(2, $form->getElements()); $this->assertNotNull($form->getElement('First')); $this->assertNotNull($form->getElement('Up')); @@ -86,23 +86,23 @@ public function testChangePosition() { $form = new Admin_Form_Document_PersonMoves(); - $this->assertEquals(4, count($form->getElements())); + $this->assertCount(4, $form->getElements()); $form->changePosition(Admin_Form_Document_PersonMoves::POSITION_FIRST); - $this->assertEquals(2, count($form->getElements())); + $this->assertCount(2, $form->getElements()); $this->assertNotNull($form->getElement('Down')); $this->assertNotNull($form->getElement('Last')); $form->changePosition(Admin_Form_Document_PersonMoves::POSITION_LAST); - $this->assertEquals(2, count($form->getElements())); + $this->assertCount(2, $form->getElements()); $this->assertNotNull($form->getElement('First')); $this->assertNotNull($form->getElement('Up')); $form->changePosition(Admin_Form_Document_PersonMoves::POSITION_DEFAULT); - $this->assertEquals(4, count($form->getElements())); + $this->assertCount(4, $form->getElements()); } public function testProcessPostEmpty() diff --git a/tests/modules/admin/forms/Document/PersonRoleTest.php b/tests/modules/admin/forms/Document/PersonRoleTest.php index d1625bee0c..389f40aa23 100644 --- a/tests/modules/admin/forms/Document/PersonRoleTest.php +++ b/tests/modules/admin/forms/Document/PersonRoleTest.php @@ -30,6 +30,8 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License **/ +use Opus\Document; + /** * Unit Tests fuer Unterformular fuer Personen in einer Rolle im Metadaten-Formular. */ @@ -42,8 +44,8 @@ public function testCreateForm() { $form = new Admin_Form_Document_PersonRole('author'); - $this->assertEquals(1, count($form->getElements())); - $this->assertEquals(0, count($form->getSubForms())); + $this->assertCount(1, $form->getElements()); + $this->assertCount(0, $form->getSubForms()); $this->assertEquals('author', $form->getRoleName()); $this->assertNotNull($form->getElement('Add')); } @@ -52,13 +54,13 @@ public function testPopulateFromModel() { $form = new Admin_Form_Document_PersonRole('author'); - $document = new Opus_Document(21); // hat zwei Authoren + $document = Document::get(21); // hat zwei Authoren - $this->assertEquals(0, count($form->getSubForms())); + $this->assertCount(0, $form->getSubForms()); $form->populateFromModel($document); - $this->assertEquals(2, count($form->getSubForms())); + $this->assertCount(2, $form->getSubForms()); } public function testProcessPostAdd() @@ -92,15 +94,15 @@ public function testProcessPostRemove() ] ]; - $document = new Opus_Document(21); // hat zwei Authoren + $document = Document::get(21); // hat zwei Authoren $form->populateFromModel($document); - $this->assertEquals(2, count($form->getSubForms()), 'Ungenügend Unterformulare.'); + $this->assertCount(2, $form->getSubForms(), 'Ungenügend Unterformulare.'); $form->processPost($post, null); - $this->assertEquals(1, count($form->getSubForms()), 'Unterformular wurde nicht entfernt.'); + $this->assertCount(1, $form->getSubForms(), 'Unterformular wurde nicht entfernt.'); // TODO prüfe Namen von Unterformularen } @@ -115,11 +117,11 @@ public function testProcessPostEdit() ] ]; - $document = new Opus_Document(21); // hat zwei Authoren + $document = Document::get(21); // hat zwei Authoren $form->populateFromModel($document); - $this->assertEquals(2, count($form->getSubForms())); + $this->assertCount(2, $form->getSubForms()); $result = $form->processPost($post, null); @@ -517,11 +519,11 @@ public function testGetSubFormModels() { $form = $this->getFormForSorting(); - $doc = new Opus_Document(250); + $doc = Document::get(250); $authors = $form->getSubFormModels($doc); - $this->assertEquals(3, count($authors)); + $this->assertCount(3, $authors); $this->assertEquals(310, $authors[0]->getModel()->getId()); $this->assertEquals(311, $authors[1]->getModel()->getId()); @@ -532,13 +534,13 @@ public function testUpdateModel() { $form = $this->getFormForSorting(); - $doc = new Opus_Document(250); + $doc = Document::get(250); $form->updateModel($doc); $authors = $doc->getPersonAuthor(); - $this->assertEquals(3, count($authors)); + $this->assertCount(3, $authors); $this->assertEquals(310, $authors[0]->getModel()->getId()); $this->assertEquals(311, $authors[1]->getModel()->getId()); @@ -553,7 +555,7 @@ public function testAddPersonLastPosition() $form->addPerson(['person' => '311']); $form->addPerson(['person' => '312']); - $this->assertEquals(3, count($form->getSubForms())); + $this->assertCount(3, $form->getSubForms()); $this->verifyExpectedOrder($form, [310, 311, 312]); } @@ -628,7 +630,7 @@ public function testAttemptToAddPersonTwiceInSameRole() $form->addPerson(['person' => '310']); $form->addPerson(['person' => '310']); - $this->assertEquals(1, count($form->getSubForms())); + $this->assertCount(1, $form->getSubForms()); $this->assertEquals(310, $form->getSubForm('PersonAuthor0')->getElementValue('PersonId')); } @@ -643,11 +645,11 @@ public function testAddPersonWithoutId() $form->addPerson([]); - $this->assertEquals(0, count($form->getSubForms())); + $this->assertCount(0, $form->getSubForms()); $messages = $logger->getMessages(); - $this->assertEquals(1, count($messages)); + $this->assertCount(1, $messages); $this->assertContains('Attempt to add person without ID.', $messages[0]); } @@ -688,7 +690,7 @@ protected function getFormForSorting() { $form = new Admin_Form_Document_PersonRole('author'); - $document = new Opus_Document(250); + $document = Document::get(250); $authors = $document->getPersonAuthor(); $authorId0 = $authors[0]->getModel()->getId(); // 310 diff --git a/tests/modules/admin/forms/Document/PersonTest.php b/tests/modules/admin/forms/Document/PersonTest.php index 36b46bc5ca..7aaaa4789a 100644 --- a/tests/modules/admin/forms/Document/PersonTest.php +++ b/tests/modules/admin/forms/Document/PersonTest.php @@ -30,6 +30,8 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License **/ +use Opus\Document; + /** * Unit Tests fuer Unterformular fuer eine mit einem Dokument verknuepfte Person. */ @@ -97,7 +99,7 @@ public function testGetLinkModel() { $form = new Admin_Form_Document_Person(); - $document = new Opus_Document(146); + $document = Document::get(146); $authors = $document->getPersonAuthor(); diff --git a/tests/modules/admin/forms/Document/PersonsTest.php b/tests/modules/admin/forms/Document/PersonsTest.php index dafd397a63..a38b5414f6 100644 --- a/tests/modules/admin/forms/Document/PersonsTest.php +++ b/tests/modules/admin/forms/Document/PersonsTest.php @@ -30,6 +30,8 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License **/ +use Opus\Document; + /** * Unit Tests fuer Unterformular fuer Personen im Metadaten-Formular. */ @@ -51,7 +53,7 @@ public function testCreateForm() { $form = new Admin_Form_Document_Persons(); - $this->assertEquals(8, count($form->getSubForms())); + $this->assertCount(8, $form->getSubForms()); foreach ($this->roles as $role) { $this->assertNotNull($form->getSubForm($role), "Unterformular '$role' fehlt."); @@ -66,17 +68,17 @@ public function testPopulateFromModel() { $form = new Admin_Form_Document_Persons(); - $document = new Opus_Document(146); // 1 Person in jeder Rolle + $document = Document::get(146); // 1 Person in jeder Rolle $form->populateFromModel($document); foreach ($this->roles as $role) { $subform = $form->getSubForm($role); $this->assertNotNull($subform, "Unterformular '$role' fehlt."); - $this->assertEquals( + $this->assertCount( 1, - count($subform->getSubForms()), - "Unterformular '$role' sollte ein Unterformlar haben." + $subform->getSubForms(), + "Unterformular '$role' sollte ein Unterformular haben." ); } } @@ -254,7 +256,7 @@ public function testProcessPostChangeRole() { $form = new Admin_Form_Document_Persons(); - $document = new Opus_Document(250); + $document = Document::get(250); $form->populateFromModel($document); @@ -292,7 +294,7 @@ public function testProcessPostSort() { $form = new Admin_Form_Document_Persons(); - $document = new Opus_Document(146); + $document = Document::get(146); $form->populateFromModel($document); @@ -328,7 +330,7 @@ public function testProcessPostEmptyWithPersons() { $form = new Admin_Form_Document_Persons(); - $document = new Opus_Document(146); + $document = Document::get(146); $form->populateFromModel($document); @@ -339,7 +341,7 @@ public function testProcessPostResultNull() { $form = new Admin_Form_Document_Persons(); - $document = new Opus_Document(146); + $document = Document::get(146); $form->populateFromModel($document); diff --git a/tests/modules/admin/forms/Document/SeriesTest.php b/tests/modules/admin/forms/Document/SeriesTest.php index 6738a808e6..6eb046384f 100644 --- a/tests/modules/admin/forms/Document/SeriesTest.php +++ b/tests/modules/admin/forms/Document/SeriesTest.php @@ -30,6 +30,9 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Document; +use Opus\Model\Dependent\Link\DocumentSeries; + /** * Unit Tests fuer Unterformular fuer Verknuepfung mit Schriftenreihe in Metadaten-Formular. */ @@ -42,7 +45,7 @@ public function testCreateForm() { $form = new Admin_Form_Document_Series(); - $this->assertEquals(4, count($form->getElements())); + $this->assertCount(4, $form->getElements()); $this->assertNotNull($form->getElement('Id')); $this->assertNotNull($form->getElement('SeriesId')); $this->assertNotNull($form->getElement('Number')); @@ -53,7 +56,7 @@ public function testPopulateFromModel() { $form = new Admin_Form_Document_Series(); - $doc = new Opus_Document(146); + $doc = Document::get(146); $series = $doc->getSeries(); $model = $series[0]; @@ -74,7 +77,7 @@ public function testUpdateModel() $form->getElement('Number')->setValue('III'); $form->getElement('SortOrder')->setValue(2); - $model = new Opus_Model_Dependent_Link_DocumentSeries(); + $model = new DocumentSeries(); $form->updateModel($model); @@ -87,7 +90,7 @@ public function testGetModel() { $form = new Admin_Form_Document_Series(); - $doc = new Opus_Document(146); + $doc = Document::get(146); $series = $doc->getSeries(); $form->getElement('Id')->setValue($doc->getId()); diff --git a/tests/modules/admin/forms/Document/SubjectTest.php b/tests/modules/admin/forms/Document/SubjectTest.php index 8cb2caa5eb..033cdb198c 100644 --- a/tests/modules/admin/forms/Document/SubjectTest.php +++ b/tests/modules/admin/forms/Document/SubjectTest.php @@ -30,6 +30,9 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Document; +use Opus\Subject; + /** * Unit Tests fuer Unterformular fuer ein Subject im Metadaten-Formular. */ @@ -42,7 +45,7 @@ public function testCreateForm() { $form = new Admin_Form_Document_Subject('psyndex'); - $this->assertEquals(4, count($form->getElements())); + $this->assertCount(4, $form->getElements()); $this->assertNotNull($form->getElement('Id')); $this->assertNotNull($form->getElement('Value')); @@ -57,7 +60,7 @@ public function testCreateFormWithLanguage() { $form = new Admin_Form_Document_Subject('swd', 'deu'); - $this->assertEquals(4, count($form->getElements())); + $this->assertCount(4, $form->getElements()); $this->assertNotNull($form->getElement('Id')); $this->assertNotNull($form->getElement('Value')); @@ -76,7 +79,7 @@ public function testPopulateFromModel() { $form = new Admin_Form_Document_Subject('swd', 'deu'); - $document = new Opus_Document(146); + $document = Document::get(146); $subjects = $document->getSubject(); $subjectSwd = $subjects[0]; @@ -98,7 +101,7 @@ public function testUpdateModel() $form->getElement('Value')->setValue('Test Schlagwort'); $form->getElement('ExternalKey')->setValue('Test Schluessel'); - $subject = new Opus_Subject(); + $subject = new Subject(); $form->updateModel($subject); @@ -112,7 +115,7 @@ public function testGetModel() { $form = new Admin_Form_Document_Subject('uncontrolled'); - $document = new Opus_Document(146); + $document = Document::get(146); $subjects = $document->getSubject(); $subject = $subjects[1]; @@ -170,7 +173,7 @@ public function testGetModelUnknownId() $messages = $logger->getMessages(); - $this->assertEquals(1, count($messages)); + $this->assertCount(1, $messages); $this->assertContains('Unknown subject ID = \'7777\'.', $messages[0]); } diff --git a/tests/modules/admin/forms/Document/SubjectTypeTest.php b/tests/modules/admin/forms/Document/SubjectTypeTest.php index 4747753c51..dcf712c5c0 100644 --- a/tests/modules/admin/forms/Document/SubjectTypeTest.php +++ b/tests/modules/admin/forms/Document/SubjectTypeTest.php @@ -30,6 +30,8 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Document; + /** * Unit Tests für Unterformular, daß Subjects eines bestimmten Typs anzeigt. */ @@ -79,7 +81,7 @@ public function testGetFieldValues() { $form = new Admin_Form_Document_SubjectType('swd'); - $document = new Opus_Document(146); + $document = Document::get(146); $values = $form->getFieldValues($document); @@ -94,7 +96,7 @@ public function testUpdateModel() { $form = new Admin_Form_Document_SubjectType('swd'); // Formular ohne Schlagwörter - $document = new Opus_Document(200); + $document = Document::get(200); $this->assertEquals(2, count($document->getSubject())); diff --git a/tests/modules/admin/forms/Document/SubjectsTest.php b/tests/modules/admin/forms/Document/SubjectsTest.php index 3bbfb163af..77d2f3c2cc 100644 --- a/tests/modules/admin/forms/Document/SubjectsTest.php +++ b/tests/modules/admin/forms/Document/SubjectsTest.php @@ -30,6 +30,8 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Document; + class Admin_Form_Document_SubjectsTest extends ControllerTestCase { @@ -39,12 +41,12 @@ public function testConstructForm() { $form = new Admin_Form_Document_Subjects(); - $this->assertEquals(3, count($form->getSubForms())); + $this->assertCount(3, $form->getSubForms()); $this->assertNotNull($form->getSubForm('Swd')); $this->assertNotNull($form->getSubForm('Psyndex')); $this->assertNotNull($form->getSubForm('Uncontrolled')); - $this->assertEquals(1, count($form->getDecorators())); + $this->assertCount(1, $form->getDecorators()); $this->assertNotNull($form->getDecorator('FormElements')); } @@ -54,13 +56,13 @@ public function testUpdateModel() $document = $this->createTestDocument(); - $form->populateFromModel(new Opus_Document(146)); // zwei Schlagwörter + $form->populateFromModel(Document::get(146)); // zwei Schlagwörter $form->updateModel($document); $subjects = $document->getSubject(); - $this->assertEquals(2, count($subjects)); + $this->assertCount(2, $subjects); // Reihenfolge sollte gleich bleiben, solange IDs in Testdaten nicht geändert werden $this->assertEquals('swd', $subjects[0]->getType()); diff --git a/tests/modules/admin/forms/Document/TitleTest.php b/tests/modules/admin/forms/Document/TitleTest.php index 21d742f3d1..12163d0ae0 100644 --- a/tests/modules/admin/forms/Document/TitleTest.php +++ b/tests/modules/admin/forms/Document/TitleTest.php @@ -30,6 +30,9 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Document; +use Opus\Title; + /** * Unit Test fuer Unterformular fuer einen Titel. */ @@ -52,7 +55,7 @@ public function testPopulateFromModel() { $form = new Admin_Form_Document_Title(); - $doc = new Opus_Document(146); + $doc = Document::get(146); $titles = $doc->getTitleMain(); @@ -74,7 +77,7 @@ public function testUpdateModel() $form->getElement('Language')->setValue('rus'); $form->getElement('Value')->setValue('Test Title'); - $title = new Opus_Title(); + $title = new Title(); $form->updateModel($title); @@ -87,7 +90,7 @@ public function testGetModel() { $form = new Admin_Form_Document_Title(); - $doc = new Opus_Document(146); + $doc = Document::get(146); $titles = $doc->getTitleMain(); diff --git a/tests/modules/admin/forms/Document/TitlesMainTest.php b/tests/modules/admin/forms/Document/TitlesMainTest.php index 462b6d5f71..76025cb3c9 100644 --- a/tests/modules/admin/forms/Document/TitlesMainTest.php +++ b/tests/modules/admin/forms/Document/TitlesMainTest.php @@ -28,9 +28,10 @@ * @author Jens Schwidder * @copyright Copyright (c) 2013, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id$ */ +use Opus\Title; + /** * Unit Tests fuer das Unterformular fuer die Haupttitel eines Dokuments. */ @@ -95,11 +96,11 @@ protected function getTestDocument() $document->setLanguage('deu'); - $title1 = new Opus_Title(); + $title1 = new Title(); $title1->setLanguage('deu'); $title1->setValue('Deutscher Titel'); - $title2 = new Opus_Title(); + $title2 = new Title(); $title2->setLanguage('eng'); $title2->setValue('English Title'); diff --git a/tests/modules/admin/forms/DocumentTest.php b/tests/modules/admin/forms/DocumentTest.php index 790b212731..e4bc6cf5d0 100644 --- a/tests/modules/admin/forms/DocumentTest.php +++ b/tests/modules/admin/forms/DocumentTest.php @@ -30,6 +30,9 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Document; +use Opus\Title; + /** * Unit Tests für Metadaten-Formular Klasse. */ @@ -72,7 +75,7 @@ public function testPopulateFromModel() { $form = new Admin_Form_Document(); - $document = new Opus_Document(146); + $document = Document::get(146); $form->populateFromModel($document); @@ -86,7 +89,7 @@ public function testPopulateFromModel() public function testGetInstanceFromPost() { - $document = new Opus_Document(146); + $document = Document::get(146); $post = []; @@ -150,7 +153,7 @@ public function testIsValidTrue() $form = new Admin_Form_Document(); $document = $this->createTestDocument(); - $document->addTitleMain(new Opus_Title()); + $document->addTitleMain(new Title()); $form->populateFromModel($document); @@ -186,7 +189,7 @@ public function testIsValidFalse() $form = new Admin_Form_Document(); $document = $this->createTestDocument(); - $document->addTitleMain(new Opus_Title()); + $document->addTitleMain(new Title()); $form->populateFromModel($document); @@ -226,7 +229,7 @@ public function testIsValidFalseDependency() $form = new Admin_Form_Document(); $document = $this->createTestDocument(); - $document->addTitleMain(new Opus_Title()); + $document->addTitleMain(new Title()); $form->populateFromModel($document); @@ -266,8 +269,8 @@ public function testIsValidFalseDependency2() $form = new Admin_Form_Document(); $document = $this->createTestDocument(); - $document->addTitleMain(new Opus_Title()); - $document->addTitleMain(new Opus_Title()); + $document->addTitleMain(new Title()); + $document->addTitleMain(new Title()); $form->populateFromModel($document); @@ -320,7 +323,7 @@ public function testPrepareRenderingAsViewFullDocument() { $form = new Admin_Form_Document(); - $document = new Opus_Document(146); + $document = Document::get(146); $form->populateFromModel($document); $form->prepareRenderingAsView(); @@ -348,7 +351,7 @@ public function testPrepareRenderingAsViewDocumentWithoutFiles() { $form = new Admin_Form_Document(); - $document = new Opus_Document(200); + $document = Document::get(200); $form->populateFromModel($document); $form->prepareRenderingAsView(); @@ -383,7 +386,7 @@ protected function verifySubForms($form, $names) protected function getHash($form) { - $session = new Zend_Session_Namespace('testing'); + $session = new \Zend_Session_Namespace('testing'); $hashElement = $form->getSubForm('Actions')->getElement('OpusHash'); $hashElement->setSession($session); diff --git a/tests/modules/admin/forms/EnrichmentKeyTest.php b/tests/modules/admin/forms/EnrichmentKeyTest.php index 2efe55e73e..bd32c7b6ab 100644 --- a/tests/modules/admin/forms/EnrichmentKeyTest.php +++ b/tests/modules/admin/forms/EnrichmentKeyTest.php @@ -32,6 +32,9 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\EnrichmentKey; +use Opus\Model\ModelException; + /** * Unit Tests for Admin_Form_Enrichmentkey. * @@ -61,7 +64,7 @@ public function testConstructForm() public function testPopulateFromModel() { - $enrichmentKey = new Opus_EnrichmentKey(); + $enrichmentKey = new EnrichmentKey(); $enrichmentKey->setName('Test'); $form = new Admin_Form_EnrichmentKey(); @@ -75,7 +78,7 @@ public function testPopulateFromModel() public function testPopulateFromExistingModel() { - $enrichment = new Opus_EnrichmentKey('City'); + $enrichment = new EnrichmentKey('City'); $this->assertNotNull($enrichment); $form = new Admin_Form_EnrichmentKey(); @@ -89,7 +92,7 @@ public function testPopulateFromExistingModel() public function testPopulateFromModelWithEnrichmentType() { - $enrichmentKey = new Opus_EnrichmentKey(); + $enrichmentKey = new EnrichmentKey(); $enrichmentKey->setName('TestKey'); $enrichmentKey->setType('TextType'); @@ -104,7 +107,7 @@ public function testPopulateFromModelWithEnrichmentType() public function testPopulateFromModelWithUnknownEnrichmentType() { - $enrichmentKey = new Opus_EnrichmentKey(); + $enrichmentKey = new EnrichmentKey(); $enrichmentKey->setName('TestKey'); $enrichmentKey->setType('FooType'); @@ -119,7 +122,7 @@ public function testPopulateFromModelWithUnknownEnrichmentType() public function testPopulateFromModelWithEnrichmentTypeAndOptionsAndStrictValidation() { - $enrichmentKey = new Opus_EnrichmentKey(); + $enrichmentKey = new EnrichmentKey(); $enrichmentKey->setName('TestKey'); $enrichmentKey->setType('RegexType'); $enrichmentKey->setOptions(json_encode(['regex' => '^a$', 'validation' => 'strict'])); @@ -135,7 +138,7 @@ public function testPopulateFromModelWithEnrichmentTypeAndOptionsAndStrictValida public function testPopulateFromModelWithEnrichmentTypeAndOptionsAndNoValidation() { - $enrichmentKey = new Opus_EnrichmentKey(); + $enrichmentKey = new EnrichmentKey(); $enrichmentKey->setName('TestKey'); $enrichmentKey->setType('RegexType'); $enrichmentKey->setOptions(json_encode(['regex' => '^a$', 'validation' => 'none'])); @@ -151,7 +154,7 @@ public function testPopulateFromModelWithEnrichmentTypeAndOptionsAndNoValidation public function testPopulateFromModelWithUnknownEnrichmentTypeAndOptions() { - $enrichmentKey = new Opus_EnrichmentKey(); + $enrichmentKey = new EnrichmentKey(); $enrichmentKey->setName('TestKey'); $enrichmentKey->setType('FooType'); $enrichmentKey->setOptions(json_encode(['regex' => '^a$', 'validation' => 'strict'])); @@ -170,7 +173,7 @@ public function testUpdateModel() $form = new Admin_Form_EnrichmentKey(); $form->getElement(Admin_Form_EnrichmentKey::ELEMENT_NAME)->setValue('TestEnrichmentKey'); - $enrichmentKey = new Opus_EnrichmentKey(); + $enrichmentKey = new EnrichmentKey(); $form->updateModel($enrichmentKey); $this->assertEquals('TestEnrichmentKey', $enrichmentKey->getName()); @@ -184,7 +187,7 @@ public function testUpdateModelWithType() $form->getElement(Admin_Form_EnrichmentKey::ELEMENT_NAME)->setValue('TestEnrichmentKey'); $form->getElement(Admin_Form_EnrichmentKey::ELEMENT_TYPE)->setValue('TextType'); - $enrichmentKey = new Opus_EnrichmentKey(); + $enrichmentKey = new EnrichmentKey(); $form->updateModel($enrichmentKey); $this->assertEquals('TestEnrichmentKey', $enrichmentKey->getName()); @@ -198,7 +201,7 @@ public function testUpdateModelWithUnknownType() $form->getElement(Admin_Form_EnrichmentKey::ELEMENT_NAME)->setValue('TestEnrichmentKey'); $form->getElement(Admin_Form_EnrichmentKey::ELEMENT_TYPE)->setValue('UnknownType'); - $enrichmentKey = new Opus_EnrichmentKey(); + $enrichmentKey = new EnrichmentKey(); $form->updateModel($enrichmentKey); $this->assertEquals('TestEnrichmentKey', $enrichmentKey->getName()); @@ -214,7 +217,7 @@ public function testUpdateModelWithTypeAndOptionsAndStrictValidation() $form->getElement(Admin_Form_EnrichmentKey::ELEMENT_OPTIONS)->setValue('^a$'); $form->getElement(Admin_Form_EnrichmentKey::ELEMENT_VALIDATION)->setValue('1'); - $enrichmentKey = new Opus_EnrichmentKey(); + $enrichmentKey = new EnrichmentKey(); $form->updateModel($enrichmentKey); $this->assertEquals('TestEnrichmentKey', $enrichmentKey->getName()); @@ -230,7 +233,7 @@ public function testUpdateModelWithTypeAndOptionsAndNoValidation() $form->getElement(Admin_Form_EnrichmentKey::ELEMENT_OPTIONS)->setValue('^a$'); $form->getElement(Admin_Form_EnrichmentKey::ELEMENT_VALIDATION)->setValue('0'); - $enrichmentKey = new Opus_EnrichmentKey(); + $enrichmentKey = new EnrichmentKey(); $form->updateModel($enrichmentKey); $this->assertEquals('TestEnrichmentKey', $enrichmentKey->getName()); @@ -246,7 +249,7 @@ public function testUpdateModelWithUnknownTypeAndOptions() $form->getElement(Admin_Form_EnrichmentKey::ELEMENT_OPTIONS)->setValue('^a$'); $form->getElement(Admin_Form_EnrichmentKey::ELEMENT_VALIDATION)->setValue('1'); - $enrichmentKey = new Opus_EnrichmentKey(); + $enrichmentKey = new EnrichmentKey(); $form->updateModel($enrichmentKey); $this->assertEquals('TestEnrichmentKey', $enrichmentKey->getName()); @@ -263,7 +266,7 @@ public function testValidationSuccess() $this->assertTrue($form->isValid($this->createArray('Test', 'RegexType', '^a$'))); $this->assertTrue($form->isValid( $this->createArray( - str_pad('Long', Opus_EnrichmentKey::getFieldMaxLength('Name'), 'g'), + str_pad('Long', EnrichmentKey::getFieldMaxLength('Name'), 'g'), "TextType" ) )); @@ -280,7 +283,7 @@ public function testValidationFailure() $this->assertFalse($form->isValid($this->createArray(' ', 'TextType'))); $this->assertFalse($form->isValid( $this->createArray( - str_pad('toolong', Opus_EnrichmentKey::getFieldMaxLength('Name') + 1, 'g'), + str_pad('toolong', EnrichmentKey::getFieldMaxLength('Name') + 1, 'g'), "TextType" ) )); @@ -300,12 +303,12 @@ public function testValidationFailure() public function testSetNameElementValue() { $form = new Admin_Form_EnrichmentKey(); - $form->populateFromModel(new Opus_EnrichmentKey()); + $form->populateFromModel(new EnrichmentKey()); $form->setNameElementValue('foo'); $this->assertEquals('foo', $form->getElement(Admin_Form_EnrichmentKey::ELEMENT_NAME)->getValue()); - $form->populateFromModel(new Opus_EnrichmentKey()); + $form->populateFromModel(new EnrichmentKey()); $this->assertNull($form->getElement(Admin_Form_EnrichmentKey::ELEMENT_NAME)->getValue()); } @@ -313,12 +316,11 @@ public function testSetNameElementValue() * Hat ein existierender Enrichment Key bereits einen zugeordneten Enrichment Type, * so kann dieser nicht mehr gelöscht, sondern nur auf einen anderen Typ geändert werden. * - * @throws Zend_Form_Exception - * @throws \Opus\Model\Exception + * @throws \Zend_Form_Exception */ public function testTypeIsRequiredForExistingTypedKey() { - $enrichmentKey = new Opus_EnrichmentKey(); + $enrichmentKey = new EnrichmentKey(); $enrichmentKey->setName('TestKey'); $enrichmentKey->setType('BooleanType'); @@ -336,12 +338,11 @@ public function testTypeIsRequiredForExistingTypedKey() * Hat ein existierender Enrichment Key keinen zugeordneten Enrichment Type, * so muss dieser beim erneuten Speichern des Enrichment Keys auch nicht gesetzt werden. * - * @throws Zend_Form_Exception - * @throws \Opus\Model\Exception + * @throws \Zend_Form_Exception */ public function testTypeIsRequiredForExistingUntypedKey() { - $enrichmentKey = new Opus_EnrichmentKey(); + $enrichmentKey = new EnrichmentKey(); $enrichmentKey->setName('TestKey'); $form = new Admin_Form_EnrichmentKey(); @@ -368,7 +369,7 @@ private function createArray($name, $type = null, $options = null) public function testPopulateDisplayName() { - $enrichmentKey = new Opus_EnrichmentKey(); + $enrichmentKey = new EnrichmentKey(); $enrichmentKey->setName('Country'); $form = new Admin_Form_EnrichmentKey(); @@ -386,13 +387,13 @@ public function testUpdateTranslations() { $key = 'MyTestKey'; - $enrichmentKey = new Opus_EnrichmentKey(); + $enrichmentKey = new EnrichmentKey(); $enrichmentKey->setName($key); $enrichmentKey->store(); $this->addModelToCleanup($enrichmentKey); - $database = new Opus_Translate_Dao(); + $database = new \Opus\Translate\Dao(); $database->setTranslation("Enrichment$key", [ 'en' => 'Old', 'de' => 'Alt' @@ -420,13 +421,14 @@ public function testChangeTranslationsKeysWithNameChange() { $oldKey = 'EnrichmentTestKey'; - $database = new Opus_Translate_Dao(); + $database = new \Opus\Translate\Dao(); + $database->removeAll(); $database->setTranslation($oldKey, [ 'en' => 'English', 'de' => 'Deutsch' ], 'default'); - $enrichmentKey = new Opus_EnrichmentKey(); + $enrichmentKey = new EnrichmentKey(); $enrichmentKey->setName('TestKey'); $enrichmentKey->store(); $this->addModelToCleanup($enrichmentKey); @@ -457,13 +459,14 @@ public function testEmptyTranslationRemovesKey() { $key = 'EnrichmentTestKey'; - $database = new Opus_Translate_Dao(); + $database = new \Opus\Translate\Dao(); + $database->removeAll(); $database->setTranslation($key, [ 'en' => 'English', 'de' => 'Deutsch' ], 'default'); - $enrichmentKey = new Opus_EnrichmentKey(); + $enrichmentKey = new EnrichmentKey(); $enrichmentKey->setName('TestKey'); $enrichmentKey->store(); $this->addModelToCleanup($enrichmentKey); @@ -489,7 +492,7 @@ public function testDoNotPopulateTranslationForNewKey() { $form = new Admin_Form_EnrichmentKey(); - $enrichmentKey = new Opus_EnrichmentKey(); + $enrichmentKey = new EnrichmentKey(); $form->populateFromModel($enrichmentKey); diff --git a/tests/modules/admin/forms/File/HashesTest.php b/tests/modules/admin/forms/File/HashesTest.php index 50165ad574..db5989ee52 100644 --- a/tests/modules/admin/forms/File/HashesTest.php +++ b/tests/modules/admin/forms/File/HashesTest.php @@ -1,5 +1,4 @@ populateFromModel($file); - $this->assertEquals(2, count($form->getElements())); + $this->assertCount(2, $form->getElements()); $this->assertNotNull($form->getElement('Hash0')); $this->assertNotNull($form->getElement('Hash1')); } @@ -53,10 +55,10 @@ public function testPopulateFromModelNoHashes() { $form = new Admin_Form_File_Hashes(); - $file = new Opus_File(121); // keine Hashes + $file = new File(121); // keine Hashes $form->populateFromModel($file); - $this->assertEquals(0, count($form->getElements())); + $this->assertCount(0, $form->getElements()); } } diff --git a/tests/modules/admin/forms/File/UploadTest.php b/tests/modules/admin/forms/File/UploadTest.php index ae4c0e8109..d70c17acf7 100644 --- a/tests/modules/admin/forms/File/UploadTest.php +++ b/tests/modules/admin/forms/File/UploadTest.php @@ -25,6 +25,8 @@ * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ +use Opus\Document; + /** * @category Application Unit Test * @package Admin_Form_File @@ -52,13 +54,13 @@ public function testCreateForm() $elements = ['Id', 'File', 'Label', 'Comment', 'Language', 'Save', 'Cancel', 'OpusHash', 'SortOrder']; - $this->assertEquals(count($elements), count($form->getElements())); + $this->assertSameSize($elements, $form->getElements()); foreach ($elements as $element) { $this->assertNotNull($form->getElement($element), "Element '$element' is missing.'"); } - $this->assertEquals(1, count($form->getSubForms())); + $this->assertCount(1, $form->getSubForms()); $this->assertNotNull($form->getSubForm('Info')); $this->assertEquals('admin_filemanager_upload', $form->getLegend()); @@ -66,7 +68,7 @@ public function testCreateForm() public function testPopulateFromModel() { - $document = new Opus_Document(146); + $document = Document::get(146); $form = new Admin_Form_File_Upload(); @@ -118,7 +120,7 @@ public function testUpdateModel() $files = $document->getFile(); - $this->assertEquals(1, count($files)); + $this->assertCount(1, $files); $file = $files[0]; @@ -137,7 +139,7 @@ public function testGetFileInfo() $fileInfo = $form->getFileInfo(); $this->assertInternalType('array', $fileInfo); - $this->assertEquals(0, count($fileInfo)); + $this->assertCount(0, $fileInfo); } public function testSetGetFileInfo() diff --git a/tests/modules/admin/forms/FileManagerTest.php b/tests/modules/admin/forms/FileManagerTest.php index 68f44a0099..b6238a049c 100644 --- a/tests/modules/admin/forms/FileManagerTest.php +++ b/tests/modules/admin/forms/FileManagerTest.php @@ -25,6 +25,8 @@ * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ +use Opus\Document; + /** * Unit Test fuer FileManager Formular. * @@ -65,7 +67,7 @@ public function testPopulateFromModel() { $form = new Admin_Form_FileManager(); - $document = new Opus_Document(92); + $document = Document::get(92); $filesForm = $form->getSubForm(Admin_Form_FileManager::SUBFORM_FILES); @@ -91,7 +93,7 @@ public function testUpdateModel() { $form = new Admin_Form_FileManager(); - $document = new Opus_Document(92); + $document = Document::get(92); $form->populateFromModel($document); @@ -162,7 +164,7 @@ public function testConstructFromPostEmptyAndNoDocument() public function testConstructFromPost() { - $document = new Opus_Document(146); + $document = Document::get(146); $post = [ 'Files' => [ @@ -206,7 +208,7 @@ public function testSetGetMessage() public function testGetInstanceFromPost() { - $document = new Opus_Document(146); + $document = Document::get(146); $post = [ 'Files' => [ diff --git a/tests/modules/admin/forms/FileTest.php b/tests/modules/admin/forms/FileTest.php index a46e10ace7..246fb66202 100644 --- a/tests/modules/admin/forms/FileTest.php +++ b/tests/modules/admin/forms/FileTest.php @@ -1,5 +1,4 @@ useEnglish(); $form = new Admin_Form_File(); - $file = new Opus_File(126); // hängt an Testdokument 146 + $file = new File(126); // hängt an Testdokument 146 $form->populateFromModel($file); @@ -87,7 +89,7 @@ public function testPopulateFromModelFileDoesNotExist() { $form = new Admin_Form_File(); - $file = new Opus_File(123); // von Dokument 122 + $file = new File(123); // von Dokument 122 $form->populateFromModel($file); @@ -178,7 +180,7 @@ public function testGetModel() $form->getElement('Id')->setValue(126); // Datei 'test.pdf' von Dokument 146 - $file = new Opus_File(126); + $file = new File(126); $form->populateFromModel($file); @@ -186,7 +188,7 @@ public function testGetModel() $model = $form->getModel(); - $this->assertInstanceOf('Opus_File', $model); + $this->assertInstanceOf('Opus\File', $model); $this->assertEquals(126, $model->getId()); $this->assertEquals('Testkommentar', $model->getComment()); diff --git a/tests/modules/admin/forms/FilesTest.php b/tests/modules/admin/forms/FilesTest.php index 623c834d50..bdd72ceee9 100644 --- a/tests/modules/admin/forms/FilesTest.php +++ b/tests/modules/admin/forms/FilesTest.php @@ -25,6 +25,8 @@ * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ +use Opus\Document; + /** * Unit Tests fuer Unterformular, das Dateien in FileManager auflistet. * @@ -128,7 +130,7 @@ public function testContinueEdit() { $form = new Admin_Form_Files(); - $document = new Opus_Document(91); + $document = Document::get(91); $form->populateFromModel($document); @@ -141,7 +143,7 @@ public function testContinueEditRemoveSubForm() { $form = new Admin_Form_Files(); - $document = new Opus_Document(91); + $document = Document::get(91); $form->populateFromModel($document); @@ -161,7 +163,7 @@ public function testContinueEditRemoveSubFormAndUpdate() { $form = new Admin_Form_Files(); - $document = new Opus_Document(91); + $document = Document::get(91); $form->populateFromModel($document); @@ -194,7 +196,7 @@ public function testGetSubFormForId() { $form = new Admin_Form_Files(); - $document = new Opus_Document(91); + $document = Document::get(91); $form->populateFromModel($document); @@ -212,7 +214,7 @@ public function testFilesAppearInOrder() { $form = new Admin_Form_Files(); - $document = new Opus_Document(155); + $document = Document::get(155); $form->populateFromModel($document); @@ -236,7 +238,7 @@ public function testGetFieldValues() { $form = new Admin_Form_Files(); - $document = new Opus_Document(155); + $document = Document::get(155); $files = $document->getFile(); diff --git a/tests/modules/admin/forms/InfoBoxTest.php b/tests/modules/admin/forms/InfoBoxTest.php index 6be8dee74c..583a89a410 100644 --- a/tests/modules/admin/forms/InfoBoxTest.php +++ b/tests/modules/admin/forms/InfoBoxTest.php @@ -30,6 +30,9 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Document; +use Opus\Person; + class Admin_Form_InfoBoxTest extends ControllerTestCase { @@ -48,7 +51,7 @@ public function testPopulateFromModel() { $form = new Admin_Form_InfoBox(); - $document = new Opus_Document(146); + $document = Document::get(146); $form->populateFromModel($document); @@ -84,7 +87,7 @@ public function testConstructFromPost() { $form = new Admin_Form_InfoBox(); - $document = new Opus_Document(146); + $document = Document::get(146); $form->constructFromPost([], $document); @@ -107,12 +110,12 @@ public function testConstructFromPostWithBadObject() $logger->clear(); - $form->constructFromPost([], new Opus_Person()); + $form->constructFromPost([], new Person()); $messages = $logger->getMessages(); $this->assertEquals(1, count($messages)); - $this->assertContains('Called with instance of \'Opus_Person\'', $messages[0]); + $this->assertContains('Called with instance of \'Opus\Person\'', $messages[0]); } public function testIsEmpty() diff --git a/tests/modules/admin/forms/IpRangeTest.php b/tests/modules/admin/forms/IpRangeTest.php index c9d418c26f..a043fb7d1f 100644 --- a/tests/modules/admin/forms/IpRangeTest.php +++ b/tests/modules/admin/forms/IpRangeTest.php @@ -30,6 +30,9 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Iprange; +use Opus\UserRole; + /** * Basic unit tests for IP range form. */ @@ -44,7 +47,7 @@ public function setUp() { parent::setUp(); - $model = new Opus_Iprange(); + $model = new Iprange(); $model->setName('localhost'); $model->setStartingip('127.0.0.1'); $model->setEndingip('127.0.0.2'); @@ -54,7 +57,7 @@ public function setUp() public function tearDown() { if (! is_null($this->_modelId)) { - $range = new Opus_Iprange($this->_modelId); + $range = new Iprange($this->_modelId); $range->delete(); } @@ -81,13 +84,13 @@ public function testPopulateFromModel() { $form = new Admin_Form_IpRange(); - $range = new Opus_Iprange(); + $range = new Iprange(); $range->setName('localhost'); $range->setStartingip('127.0.0.1'); $range->setEndingip('127.0.0.100'); $range->setRole([ - Opus_UserRole::fetchByName('docsadmin'), - Opus_UserRole::fetchByName('jobaccess') + UserRole::fetchByName('docsadmin'), + UserRole::fetchByName('jobaccess') ]); $form->populateFromModel($range); @@ -108,7 +111,7 @@ public function testPopulateFromModelWithIp() { $form = new Admin_Form_IpRange(); - $model = new Opus_Iprange($this->_modelId); + $model = new Iprange($this->_modelId); $form->populateFromModel($model); @@ -124,7 +127,7 @@ public function testUpdateModel() $form->getElement('Startingip')->setValue('127.0.0.1'); $form->getElement('Endingip')->setValue('127.0.0.3'); - $model = new Opus_Iprange(); + $model = new Iprange(); $form->updateModel($model); diff --git a/tests/modules/admin/forms/LanguageTest.php b/tests/modules/admin/forms/LanguageTest.php index 57b0e9bfda..20ccc64298 100644 --- a/tests/modules/admin/forms/LanguageTest.php +++ b/tests/modules/admin/forms/LanguageTest.php @@ -31,6 +31,8 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Language; + class Admin_Form_LanguageTest extends ControllerTestCase { @@ -60,7 +62,7 @@ public function testPopulateFromModel() { $form = new Admin_Form_Language(); - $language = new Opus_Language(); + $language = new Language(); $language->setActive(true); $language->setPart2B('ger'); $language->setPart2T('deu'); @@ -87,7 +89,7 @@ public function testPopulateFromModelWithId() { $form = new Admin_Form_Language(); - $language = new Opus_Language(2); + $language = new Language(2); $form->populateFromModel($language); @@ -108,7 +110,7 @@ public function testUpdateModel() $form->getElement('Scope')->setValue('I'); $form->getElement('Type')->setValue('L'); - $language = new Opus_Language(); + $language = new Language(); $form->updateModel($language); diff --git a/tests/modules/admin/forms/LicenceTest.php b/tests/modules/admin/forms/LicenceTest.php index 847b94cf74..d41275eb5c 100644 --- a/tests/modules/admin/forms/LicenceTest.php +++ b/tests/modules/admin/forms/LicenceTest.php @@ -25,6 +25,8 @@ * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ +use Opus\Licence; + /** * Unit Tests fuer Formular fuer eine Lizenz. * @@ -67,7 +69,7 @@ public function testPopulateFromModel() { $form = new Admin_Form_Licence(); - $licence = new Opus_Licence(); + $licence = new Licence(); $licence->setActive(true); $licence->setCommentInternal('Test Internal Comment'); $licence->setDescMarkup('

      Test Markup

      '); @@ -101,7 +103,7 @@ public function testPopulateFromModelWithId() { $form = new Admin_Form_Licence(); - $licence = new Opus_Licence(2); + $licence = new Licence(2); $form->populateFromModel($licence); @@ -126,7 +128,7 @@ public function testUpdateModel() $form->getElement('SortOrder')->setValue(5); $form->getElement('PodAllowed')->setChecked(true); - $licence = new Opus_Licence(); + $licence = new Licence(); $form->updateModel($licence); diff --git a/tests/modules/admin/forms/NotificationTest.php b/tests/modules/admin/forms/NotificationTest.php index a144a016fa..08f656e48b 100644 --- a/tests/modules/admin/forms/NotificationTest.php +++ b/tests/modules/admin/forms/NotificationTest.php @@ -30,6 +30,8 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Document; + class Admin_Form_NotificationTest extends ControllerTestCase { @@ -39,7 +41,7 @@ public function testGetRows() { $form = new Admin_Form_Notification(); - $form->addPublishNotificationSelection(new Opus_Document(146)); + $form->addPublishNotificationSelection(Document::get(146)); $rows = $form->getRows(); diff --git a/tests/modules/admin/forms/Person/DocumentsTest.php b/tests/modules/admin/forms/Person/DocumentsTest.php index e2eeb6f84c..f7fa05b9f3 100644 --- a/tests/modules/admin/forms/Person/DocumentsTest.php +++ b/tests/modules/admin/forms/Person/DocumentsTest.php @@ -81,7 +81,7 @@ public function testSetDocuments() $this->assertArrayHasKey(5, $options); foreach ($options as $docId => $doc) { - $this->assertInstanceOf('Opus_Document', $doc); + $this->assertInstanceOf('Opus\Document', $doc); $this->assertEquals($docId, $doc->getId()); } } diff --git a/tests/modules/admin/forms/PersonLinkTest.php b/tests/modules/admin/forms/PersonLinkTest.php index c814e384a3..f6a4c7f424 100644 --- a/tests/modules/admin/forms/PersonLinkTest.php +++ b/tests/modules/admin/forms/PersonLinkTest.php @@ -30,8 +30,12 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Document; +use Opus\Person; +use Opus\Model\Dependent\Link\DocumentPerson; + /** - * Unit Tests für Formular das Opus_Model_Dependent_Link_DocumentPerson Objekte anzeigt. + * Unit Tests für Formular das DocumentPerson Objekte anzeigt. */ class Admin_Form_PersonLinkTest extends ControllerTestCase { @@ -56,9 +60,9 @@ public function testPopulateFromModel() { $form = new Admin_Form_PersonLink(); - $model = new Opus_Model_Dependent_Link_DocumentPerson(); + $model = new DocumentPerson(); - $person = new Opus_Person(310); // von Testdokument 250 (Personensortierung) + $person = new Person(310); // von Testdokument 250 (Personensortierung) $model->setModel($person); $model->setSortOrder(5); @@ -94,7 +98,7 @@ public function testGetModel() $this->assertNull($form->getModel()); - $document = new Opus_Document(250); + $document = Document::get(250); $authors = $document->getPersonAuthor(); $this->assertEquals(3, count($authors)); @@ -158,7 +162,7 @@ public function testUpdateModel() $form->getElement('SortOrder')->setValue(6); $form->getElement('AllowContact')->setChecked(true); - $model = new Opus_Model_Dependent_Link_DocumentPerson(); + $model = new DocumentPerson(); $form->updateModel($model); diff --git a/tests/modules/admin/forms/PersonTest.php b/tests/modules/admin/forms/PersonTest.php index 60557f01d4..c6a708b1aa 100644 --- a/tests/modules/admin/forms/PersonTest.php +++ b/tests/modules/admin/forms/PersonTest.php @@ -31,6 +31,9 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Document; +use Opus\Person; + /** * Unit Test fuer Formularklasse zum Editieren einer Person. */ @@ -61,7 +64,7 @@ public function testPopulateFromModel() $form = new Admin_Form_Person(); - $person = new Opus_Person(); + $person = new Person(); $person->setFirstName('John'); $person->setLastName('Doe'); @@ -113,7 +116,7 @@ public function testUpdateModel() $form->getElement('IdentifierMisc')->setValue('5678'); - $person = new Opus_Person(); + $person = new Person(); $form->updateModel($person); @@ -145,7 +148,7 @@ public function testUpdateModelBadModel() $messages = $logger->getMessages(); $this->assertEquals(1, count($messages)); - $this->assertContains('not instance of Opus_Person', $messages[0]); + $this->assertContains('not instance of Opus\Person', $messages[0]); } public function testGetModel() @@ -154,7 +157,7 @@ public function testGetModel() $form = new Admin_Form_Person(); - $document = new Opus_Document(146); + $document = Document::get(146); $persons = $document->getPerson(); $person = $persons[0]->getModel(); diff --git a/tests/modules/admin/forms/PersonsTest.php b/tests/modules/admin/forms/PersonsTest.php index a37eebbd00..9bbe255225 100644 --- a/tests/modules/admin/forms/PersonsTest.php +++ b/tests/modules/admin/forms/PersonsTest.php @@ -528,7 +528,7 @@ public function testKeepPostValues() $form->getElement('PlaceOfBirth')->setValue('Köln'); - $output = $form->render(Zend_Registry::get('Opus_View')); + $output = $form->render($this->getView()); $this->assertContains('', $output); $this->assertContains('', $output); diff --git a/tests/modules/admin/forms/RoleTest.php b/tests/modules/admin/forms/RoleTest.php index e2f5542f34..3dac7e01ba 100644 --- a/tests/modules/admin/forms/RoleTest.php +++ b/tests/modules/admin/forms/RoleTest.php @@ -30,6 +30,8 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\UserRole; + class Admin_Form_RoleTest extends ControllerTestCase { @@ -43,14 +45,14 @@ public function testCreateForm() public function testContructWithRole() { - $role = Opus_UserRole::fetchByName('guest'); + $role = UserRole::fetchByName('guest'); $form = new Admin_Form_Role($role->getId()); $this->assertEquals('guest', $form->getElementValue(Admin_Form_Role::ELEMENT_NAME)); } public function testPopulateFromModel() { - $role = Opus_UserRole::fetchByName('administrator'); + $role = UserRole::fetchByName('administrator'); $form = new Admin_Form_Role(); $form->populateFromModel($role); @@ -68,6 +70,8 @@ public function validRoleNameDataProvider() } /** + * @param string $validName Role name + * * @dataProvider validRoleNameDataProvider */ public function testValidRoleName($validName) @@ -91,6 +95,7 @@ public function invalidRoleNameDataProvider() } /** + * @param string $invalidName Role name * @dataProvider invalidRoleNameDataProvider */ public function testInvalidRoleName($invalidName) diff --git a/tests/modules/admin/forms/SeriesTest.php b/tests/modules/admin/forms/SeriesTest.php index fe4a65c63d..a9367d13e3 100644 --- a/tests/modules/admin/forms/SeriesTest.php +++ b/tests/modules/admin/forms/SeriesTest.php @@ -1,5 +1,4 @@ setTitle('TestTitle'); $series->setInfobox('TestInfo'); $series->setVisible(1); @@ -74,7 +76,7 @@ public function testPopulateFromModelWithId() { $form = new Admin_Form_Series(); - $series = new Opus_Series(2); + $series = new Series(2); $form->populateFromModel($series); @@ -90,7 +92,7 @@ public function testUpdateModel() $form->getElement('Visible')->setValue(1); $form->getElement('SortOrder')->setValue(22); - $series = new Opus_Series(); + $series = new Series(); $form->updateModel($series); diff --git a/tests/modules/admin/forms/UserRolesTest.php b/tests/modules/admin/forms/UserRolesTest.php index c35d27edd5..753abab194 100644 --- a/tests/modules/admin/forms/UserRolesTest.php +++ b/tests/modules/admin/forms/UserRolesTest.php @@ -31,6 +31,9 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Account; +use Opus\UserRole; + class Admin_Form_UserRolesTest extends ControllerTestCase { @@ -40,16 +43,16 @@ public function testConstruct() { $form = new Admin_Form_UserRoles(); - $roles = Opus_UserRole::getAll(); + $roles = UserRole::getAll(); $elements = $form->getElements(); - $this->assertEquals(count($roles), count($elements)); + $this->assertSameSize($roles, $elements); } public function testPopulateFromModel() { - $account = Opus_Account::fetchAccountByLogin('sworduser'); + $account = Account::fetchAccountByLogin('sworduser'); $form = new Admin_Form_UserRoles(); @@ -97,7 +100,7 @@ public function testUpdateModel() $form->getElement('administrator')->setValue(1); $form->getElement('sworduser')->setValue(1); - $account = new Opus_Account(); + $account = new Account(); $form->updateModel($account); diff --git a/tests/modules/admin/forms/WorkflowNotificationTest.php b/tests/modules/admin/forms/WorkflowNotificationTest.php index a33c8e88dd..bcd2d24657 100644 --- a/tests/modules/admin/forms/WorkflowNotificationTest.php +++ b/tests/modules/admin/forms/WorkflowNotificationTest.php @@ -31,6 +31,9 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Document; +use Opus\Person; + class Admin_Form_WorkflowNotificationTest extends ControllerTestCase { @@ -42,46 +45,46 @@ protected function setUpTestDocument() { $doc = $this->createTestDocument(); - $author = new Opus_Person(); + $author = new Person(); $author->setFirstName('John'); $author->setLastName('Tester'); $author->setEmail('john@example.org'); $doc->addPersonAuthor($author); - $author = new Opus_Person(); + $author = new Person(); $author->setFirstName('Jane'); $author->setLastName('Doe'); $author->setEmail('jane@example.org'); $doc->addPersonAuthor($author); // This email is used twice for different authors (John & Anton) - $author = new Opus_Person(); + $author = new Person(); $author->setFirstName('Anton'); $author->setLastName('Other'); $author->setEmail('john@example.org'); $doc->addPersonAuthor($author); // Jim doesn't have an email address and won't be a recipient - $author = new Opus_Person(); + $author = new Person(); $author->setFirstName('Jim'); $author->setLastName('Busy'); $doc->addPersonAuthor($author); // Jane is author and submitter - $submitter = new Opus_Person(); + $submitter = new Person(); $submitter->setFirstName('Jane'); $submitter->setLastName('Doe'); $submitter->setEmail('jane@example.org'); $doc->addPersonSubmitter($submitter); // Bob is just submitter - $submitter = new Opus_Person(); + $submitter = new Person(); $submitter->setFirstName('Bob'); $submitter->setLastName('Writer'); $submitter->setEmail('bob@example.org'); $doc->addPersonSubmitter($submitter); - $this->doc = new Opus_Document($doc->store()); + $this->doc = Document::get($doc->store()); } public function testGetRecipients() @@ -143,7 +146,7 @@ public function testGetSelectedRecipients() * Add a checkbox for each PersonSubmitter and PersonAuthor (used to select * recipients for publish notification email) * - * @param Opus_Document $document + * @param Document $document protected function addPublishNotificationSelection($document) { $translator = $this->getTranslator(); diff --git a/tests/modules/admin/models/CollectionRoleTest.php b/tests/modules/admin/models/CollectionRoleTest.php index abc293096a..d4c400394e 100644 --- a/tests/modules/admin/models/CollectionRoleTest.php +++ b/tests/modules/admin/models/CollectionRoleTest.php @@ -29,6 +29,9 @@ * @copyright Copyright (c) 2008-2019, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ + +use Opus\CollectionRole; + class Admin_Model_CollectionRoleTest extends ControllerTestCase { @@ -42,7 +45,7 @@ public function setUp() { parent::setUp(); - $collectionRole = new Opus_CollectionRole(); + $collectionRole = new CollectionRole(); $collectionRole->setName('TestCollectionRole-Name'); $collectionRole->setOaiName('TestCollectionRole-OaiName'); $collectionRole->setVisible(1); @@ -58,11 +61,11 @@ public function setUp() public function tearDown() { - $collectionRole = new Opus_CollectionRole($this->collectionRoleId); + $collectionRole = new CollectionRole($this->collectionRoleId); $collectionRole->delete(); if (! is_null($this->moveTestColId)) { - $collectionRole = new Opus_CollectionRole($this->moveTestColId); + $collectionRole = new CollectionRole($this->moveTestColId); $collectionRole->delete(); } @@ -135,7 +138,7 @@ public function testSetVisibilityTrue() $model->setVisibility(true); - $collectionRole = new Opus_CollectionRole($this->collectionRoleId); + $collectionRole = new CollectionRole($this->collectionRoleId); $this->assertEquals(1, $collectionRole->getVisible()); } @@ -150,14 +153,14 @@ public function testSetVisibilityFalse() $model->setVisibility(false); - $collectionRole = new Opus_CollectionRole($this->collectionRoleId); + $collectionRole = new CollectionRole($this->collectionRoleId); $this->assertEquals(0, $collectionRole->getVisible()); } public function testMove() { - $colRole = new Opus_CollectionRole(); + $colRole = new CollectionRole(); $colRole->setName('MoveTestColRole-Name'); $colRole->setOaiName('MoveTestColRole-OaiName'); $colRole->setDisplayFrontdoor('Number'); @@ -165,7 +168,7 @@ public function testMove() $colRole->setPosition(100); $this->moveTestColId = $colRole->store(); - $colRoles = Opus_CollectionRole::fetchAll(); + $colRoles = CollectionRole::fetchAll(); $colRolesCount = count($colRoles); @@ -176,7 +179,7 @@ public function testMove() $model->move(100); - $colRoles = Opus_CollectionRole::fetchAll(); + $colRoles = CollectionRole::fetchAll(); $colRolesCount = count($colRoles); diff --git a/tests/modules/admin/models/CollectionsTest.php b/tests/modules/admin/models/CollectionsTest.php index 084626eda5..35723d87b4 100644 --- a/tests/modules/admin/models/CollectionsTest.php +++ b/tests/modules/admin/models/CollectionsTest.php @@ -30,6 +30,9 @@ * @copyright Copyright (c) 2008-2019, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ + +use Opus\CollectionRole; + class Admin_Model_CollectionsTest extends ControllerTestCase { @@ -45,7 +48,7 @@ public function setUp() { parent::setUp(); - $collectionRole = new Opus_CollectionRole(); + $collectionRole = new CollectionRole(); $collectionRole->setName('TestCollectionRole-Name'); $collectionRole->setOaiName('TestCollectionRole-OaiName'); $collectionRole->setVisible(1); @@ -60,7 +63,7 @@ public function setUp() $this->collectionRoleId = $collectionRole->store(); $this->model = new Admin_Model_Collections(); - $this->model->setView(Zend_Registry::get('Opus_View')); + $this->model->setView($this->getView()); $document = $this->createTestDocument(); $document->addCollection($root); @@ -69,7 +72,7 @@ public function setUp() public function tearDown() { - $collectionRole = new Opus_CollectionRole($this->collectionRoleId); + $collectionRole = new CollectionRole($this->collectionRoleId); $collectionRole->delete(); parent::tearDown(); @@ -97,9 +100,9 @@ public function testGetCollectionRoleInfo() } $this->assertArrayHasKey('isRoot', $collection); $this->assertArrayHasKey('role', $collection); - $this->assertInstanceOf('Opus_CollectionRole', $collection['role']); + $this->assertInstanceOf('Opus\CollectionRole', $collection['role']); $this->assertArrayHasKey('collection', $collection); - $this->assertInstanceOf('Opus_Collection', $collection['collection']); + $this->assertInstanceOf('Opus\Collection', $collection['collection']); $this->assertArrayHasKey('assigned', $collection); $this->assertFalse($collection['assigned']); } @@ -110,7 +113,7 @@ public function testGetCollectionRoleInfo() */ public function testRoleInvisible() { - $collectionRole = Opus_CollectionRole::fetchByName('TestCollectionRole-Name'); + $collectionRole = CollectionRole::fetchByName('TestCollectionRole-Name'); $collectionRole->setVisible(0); $collectionRole->store(); @@ -131,9 +134,9 @@ public function testRoleInvisible() } $this->assertArrayHasKey('isRoot', $collection); $this->assertArrayHasKey('role', $collection); - $this->assertInstanceOf('Opus_CollectionRole', $collection['role']); + $this->assertInstanceOf('Opus\CollectionRole', $collection['role']); $this->assertArrayHasKey('collection', $collection); - $this->assertInstanceOf('Opus_Collection', $collection['collection']); + $this->assertInstanceOf('Opus\Collection', $collection['collection']); $this->assertArrayHasKey('assigned', $collection); $this->assertFalse($collection['assigned']); } @@ -158,9 +161,9 @@ public function testCollectionRoleWithoutRootNotIncluded() } $this->assertArrayHasKey('isRoot', $collection); $this->assertArrayHasKey('role', $collection); - $this->assertInstanceOf('Opus_CollectionRole', $collection['role']); + $this->assertInstanceOf('Opus\CollectionRole', $collection['role']); $this->assertArrayHasKey('collection', $collection); - $this->assertInstanceOf('Opus_Collection', $collection['collection']); + $this->assertInstanceOf('Opus\Collection', $collection['collection']); $this->assertArrayHasKey('assigned', $collection); $this->assertFalse($collection['assigned']); } diff --git a/tests/modules/admin/models/DocumentEditSessionTest.php b/tests/modules/admin/models/DocumentEditSessionTest.php index 93fdae9439..460923e7b7 100644 --- a/tests/modules/admin/models/DocumentEditSessionTest.php +++ b/tests/modules/admin/models/DocumentEditSessionTest.php @@ -39,13 +39,10 @@ public function testCreateModel() $this->assertEquals(146, $model->getDocumentId()); } - /** - * @expectedException InvalidArgumentException - * @expectedExceptionMessage mit document ID '-1' aufgerufen - */ public function testCreateModelWithBadId() { - $model = new Admin_Model_DocumentEditSession(-1); + $this->setExpectedException(\InvalidArgumentException::class, 'mit document ID \'-1\' aufgerufen'); + new Admin_Model_DocumentEditSession(-1); } public function testAddPerson() @@ -81,7 +78,7 @@ public function testRetrievePersons() $model->addPerson($props); - $this->assertEquals(1, count($model->retrievePersons())); + $this->assertCount(1, $model->retrievePersons()); // retrievePersons removes variable from session $this->assertEmpty($model->retrievePersons()); diff --git a/tests/modules/admin/models/DoiReportTest.php b/tests/modules/admin/models/DoiReportTest.php index e74009f4fa..58a0b78760 100644 --- a/tests/modules/admin/models/DoiReportTest.php +++ b/tests/modules/admin/models/DoiReportTest.php @@ -30,7 +30,12 @@ * @author Jens Schwidder * @copyright Copyright (c) 2018-2019, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * + */ + +use Opus\Document; +use Opus\Identifier; + +/** * TODO test-performance */ class Admin_Model_DoiReportTest extends ControllerTestCase @@ -46,14 +51,12 @@ public function setUp() { parent::setUp(); - $config = Zend_Registry::get('Zend_Config'); - $config->merge(new Zend_Config([ + $this->adjustConfiguration([ 'doi' => [ 'prefix' => '10.5072', 'localPrefix' => 'opustest' ] - ])); - Zend_Registry::set('Zend_Config', $config); + ]); $this->docIds = []; @@ -107,14 +110,14 @@ public function testGetNumDoisForBulkRegistration() public function testGetNumDoisForBulkVerification() { - $finder = new Opus_DocumentFinder(); + $finder = $this->getDocumentFinder(); $finder->setServerState('published'); - $finder->setIdentifierTypeExists('doi'); + $finder->setIdentifierExists('doi'); $expected = 0; - foreach ($finder->ids() as $docId) { - $doc = new Opus_Document($docId); + foreach ($finder->getIds() as $docId) { + $doc = Document::get($docId); $identifier = $doc->getIdentifierDoi(0); if ($identifier->getStatus() === 'registered') { $expected++; @@ -133,7 +136,7 @@ private function createTestDocWithDoi($serverState, $doiStatus, $local = true) $docId = $doc->store(); $this->docIds[] = $docId; - $doi = new Opus_Identifier(); + $doi = new Identifier(); $doi->setType('doi'); if ($local) { $doi->setValue('10.5072/opustest-' . $docId); diff --git a/tests/modules/admin/models/DoiStatusTest.php b/tests/modules/admin/models/DoiStatusTest.php index 2aed7ee37f..8b66809077 100644 --- a/tests/modules/admin/models/DoiStatusTest.php +++ b/tests/modules/admin/models/DoiStatusTest.php @@ -1,5 +1,4 @@ docId)) { // removed previously created test document from database - $doc = new Opus_Document($this->docId); - $doc->deletePermanent(); + $doc = Document::get($this->docId); + $doc->delete(); } parent::tearDown(); } @@ -51,7 +54,7 @@ public function tearDown() public function testWithPublishedDoc() { $this->createTestDocWithDoi('published'); - $doc = new Opus_Document($this->docId); + $doc = Document::get($this->docId); $identifiers = $doc->getIdentifier(); $doi = $identifiers[0]; @@ -66,7 +69,7 @@ public function testWithPublishedDoc() public function testWithUnpublishedDoc() { $this->createTestDocWithDoi('unpublished'); - $doc = new Opus_Document($this->docId); + $doc = Document::get($this->docId); $identifiers = $doc->getIdentifier(); $doi = $identifiers[0]; @@ -80,11 +83,11 @@ public function testWithUnpublishedDoc() private function createTestDocWithDoi($serverState) { - $doc = new Opus_Document(); + $doc = Document::new(); $doc->setServerState($serverState); $this->docId = $doc->store(); - $doi = new Opus_Identifier(); + $doi = new Identifier(); $doi->setType('doi'); $doi->setValue('10.5027/opustest-' . $this->docId); $doi->setStatus('registered'); diff --git a/tests/modules/admin/models/EnrichmentKeysTest.php b/tests/modules/admin/models/EnrichmentKeysTest.php index d1484b2e24..39a4e3f0f9 100644 --- a/tests/modules/admin/models/EnrichmentKeysTest.php +++ b/tests/modules/admin/models/EnrichmentKeysTest.php @@ -42,7 +42,7 @@ class Admin_Model_EnrichmentKeysTest extends ControllerTestCase public function tearDown() { - $database = new Opus_Translate_Dao(); + $database = new \Opus\Translate\Dao(); $database->removeAll(); parent::tearDown(); @@ -52,7 +52,7 @@ public function testGetProtectedEnrichmentKeys() { $model = new Admin_Model_EnrichmentKeys(); - $config = new Zend_Config(['enrichmentkey' => ['protected' => [ + $config = new \Zend_Config(['enrichmentkey' => ['protected' => [ 'modules' => 'pkey1,pkey2', 'migration' => 'pkey3,pkey4' ]]]); @@ -67,7 +67,7 @@ public function testGetProtectedEnrichmentKeys() $this->assertContains('pkey3', $protectedKeys); $this->assertContains('pkey4', $protectedKeys); - $config = new Zend_Config(['enrichmentkey' => ['protected' => [ + $config = new \Zend_Config(['enrichmentkey' => ['protected' => [ 'migration' => 'pkey3,pkey4' ]]]); @@ -80,7 +80,7 @@ public function testGetProtectedEnrichmentKeys() $this->assertContains('pkey3', $protectedKeys); $this->assertContains('pkey4', $protectedKeys); - $config = new Zend_Config(['enrichmentkey' => ['protected' => [ + $config = new \Zend_Config(['enrichmentkey' => ['protected' => [ 'modules' => 'pkey1,pkey2', ]]]); @@ -98,7 +98,7 @@ public function testGetProtectedEnrichmentKeysNotConfigured() { $model = new Admin_Model_EnrichmentKeys(); - $config = new Zend_Config([]); + $config = new \Zend_Config([]); $model->setConfig($config); @@ -110,7 +110,7 @@ public function testGetProtectedEnrichmentKeysNotConfigured() public function testCreateTranslations() { - $database = new Opus_Translate_Dao(); + $database = new \Opus\Translate\Dao(); $database->removeAll(); $model = new Admin_Model_EnrichmentKeys(); @@ -133,7 +133,7 @@ public function testCreateTranslations() public function testCreateTranslationsDoNotOverwriteExistingValues() { - $database = new Opus_Translate_Dao(); + $database = new \Opus\Translate\Dao(); $database->removeAll(); $hintKey = 'hint_EnrichmentMyTestEnrichment'; @@ -174,7 +174,7 @@ public function testCreateTranslationsDoNotOverwriteExistingValues() public function testChangeNamesOfTranslationKeys() { - $database = new Opus_Translate_Dao(); + $database = new \Opus\Translate\Dao(); $database->removeAll(); $model = new Admin_Model_EnrichmentKeys(); @@ -203,7 +203,7 @@ public function testRemoveTranslations() { $model = new Admin_Model_EnrichmentKeys(); - $database = new Opus_Translate_Dao(); + $database = new \Opus\Translate\Dao(); $database->removeAll(); $name = 'TestEnrichment'; diff --git a/tests/modules/admin/models/FileImportTest.php b/tests/modules/admin/models/FileImportTest.php index 6fe5a6c905..3ab1843768 100644 --- a/tests/modules/admin/models/FileImportTest.php +++ b/tests/modules/admin/models/FileImportTest.php @@ -1,5 +1,4 @@ model->addFilesToDocument($this->documentId, ['test.txt']); - $document = new Opus_Document($this->documentId); + $document = Document::get($this->documentId); $files = $document->getFile(); @@ -193,7 +195,7 @@ public function testDeleteFile() $this->model->addFilesToDocument($this->documentId, ['test1.txt', 'test2.txt']); - $document = new Opus_Document($this->documentId); + $document = Document::get($this->documentId); $files = $document->getFile(); @@ -208,7 +210,7 @@ public function testDeleteFile() // eigentlicher Test $this->model->deleteFile($this->documentId, $files[0]->getId()); - $document = new Opus_Document($this->documentId); + $document = Document::get($this->documentId); $files = $document->getFile(); diff --git a/tests/modules/admin/models/HashTest.php b/tests/modules/admin/models/HashTest.php index 686664c665..2e1ee05e87 100644 --- a/tests/modules/admin/models/HashTest.php +++ b/tests/modules/admin/models/HashTest.php @@ -30,13 +30,15 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Document; + class Admin_Model_HashTest extends ControllerTestCase { public function testCreate() { $this->markTestIncomplete('No hash in test data.'); - $doc = new Opus_Document(91); + $doc = Document::get(91); $files = $doc->getFiles(); $file = $files[0]; } diff --git a/tests/modules/admin/models/IndexMaintenanceTest.php b/tests/modules/admin/models/IndexMaintenanceTest.php index 5f9aabd483..29ccd8ae5d 100644 --- a/tests/modules/admin/models/IndexMaintenanceTest.php +++ b/tests/modules/admin/models/IndexMaintenanceTest.php @@ -28,10 +28,15 @@ * @package Tests * @author Sascha Szott * @author Jens Schwidder - * @copyright Copyright (c) 2008-2019, OPUS 4 development team + * @copyright Copyright (c) 2008-2021, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Config; +use Opus\Job; +use Opus\Job\Runner; +use Opus\Log; + class Admin_Model_IndexMaintenanceTest extends ControllerTestCase { @@ -42,11 +47,11 @@ class Admin_Model_IndexMaintenanceTest extends ControllerTestCase public function tearDown() { if (! is_null($this->config)) { - Zend_Registry::set('Zend_Config', $this->config); + Config::set($this->config); // TODO why is this here? } // Cleanup of Log File - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $filename = $config->workspacePath . DIRECTORY_SEPARATOR . 'log' . DIRECTORY_SEPARATOR . 'opus_consistency-check.log'; if (file_exists($filename)) { unlink($filename); @@ -58,7 +63,7 @@ public function tearDown() } // Cleanup of Jobs Table - $jobs = Opus_Job::getByLabels([Opus\Search\Task\ConsistencyCheck::LABEL]); + $jobs = Job::getByLabels([Opus\Search\Task\ConsistencyCheck::LABEL]); foreach ($jobs as $job) { try { $job->delete(); @@ -100,16 +105,16 @@ public function testConstructorWithFeatureEnabledBoth() private function enableAsyncMode() { - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'runjobs' => ['asynchronous' => self::CONFIG_VALUE_TRUE] - ])); + ]); } private function enableAsyncIndexmaintenanceMode() { - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'runjobs' => ['indexmaintenance' => ['asynchronous' => self::CONFIG_VALUE_TRUE]] - ])); + ]); } public function testAllowConsistencyCheck() @@ -144,7 +149,7 @@ public function testNotAllowConsistencyCheck() $model->createJob(); $this->assertFalse($model->allowConsistencyCheck()); - $this->assertEquals(1, Opus_Job::getCountForLabel(Opus\Search\Task\ConsistencyCheck::LABEL)); + $this->assertEquals(1, Job::getCountForLabel(Opus\Search\Task\ConsistencyCheck::LABEL)); } public function testNotAllowConsistencyCheckAlt() @@ -155,7 +160,7 @@ public function testNotAllowConsistencyCheckAlt() $model->createJob(); $this->assertFalse($model->allowConsistencyCheck()); - $this->assertEquals(1, Opus_Job::getCountForLabel(Opus\Search\Task\ConsistencyCheck::LABEL)); + $this->assertEquals(1, Job::getCountForLabel(Opus\Search\Task\ConsistencyCheck::LABEL)); } public function testProcessingStateInvalidContext() @@ -167,15 +172,15 @@ public function testProcessingStateInvalidContext() private function runJobImmediately() { - $this->assertEquals(1, Opus_Job::getCountForLabel(Opus\Search\Task\ConsistencyCheck::LABEL)); + $this->assertEquals(1, Job::getCountForLabel(Opus\Search\Task\ConsistencyCheck::LABEL)); - $jobrunner = new Opus_Job_Runner; - $jobrunner->setLogger(Zend_Registry::get('Zend_Log')); + $jobrunner = new Runner; + $jobrunner->setLogger(Log::get()); $worker = new Opus\Search\Task\ConsistencyCheck(); $jobrunner->registerWorker($worker); $jobrunner->run(); - $this->assertEquals(0, Opus_Job::getCountForLabel(Opus\Search\Task\ConsistencyCheck::LABEL)); + $this->assertEquals(0, Job::getCountForLabel(Opus\Search\Task\ConsistencyCheck::LABEL)); } public function testProcessingStateInitial() @@ -241,9 +246,9 @@ public function testReadLogfileWithNonEmptyFile() { $this->enableAsyncMode(); - $finder = new Opus_DocumentFinder(); + $finder = $this->getDocumentFinder(); $finder->setServerState('published'); - $numOfPublishedDocs = $finder->count(); + $numOfPublishedDocs = $finder->getCount(); $model = new Admin_Model_IndexMaintenance(); $model->createJob(); @@ -263,7 +268,7 @@ public function testReadLogfileWithNonEmptyFile() private function touchLogfile($lock = false) { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); if ($lock) { $filename = $config->workspacePath . DIRECTORY_SEPARATOR . 'log' . DIRECTORY_SEPARATOR . 'opus_consistency-check.log.lock'; } else { diff --git a/tests/modules/admin/models/UrnGeneratorTest.php b/tests/modules/admin/models/UrnGeneratorTest.php index 1101d788d8..98587a42fc 100644 --- a/tests/modules/admin/models/UrnGeneratorTest.php +++ b/tests/modules/admin/models/UrnGeneratorTest.php @@ -34,37 +34,15 @@ class Admin_Model_UrnGeneratorTest extends ControllerTestCase { - private $config; - - public function setUp() - { - parent::setUp(); - - $this->makeConfigurationModifiable(); - } - - public function tearDown() - { - if (! is_null($this->config)) { - // undo modifications in configuration - Zend_Registry::set('Zend_Config', $this->config); - } - } - private function modifyUrnConfig($nss, $nid) { - // backup current config state - $this->config = Zend_Registry::get('Zend_Config'); - // modify current config state - $config = Zend_Registry::get('Zend_Config'); - $config->merge(new Zend_Config([ + $this->adjustConfiguration([ 'urn' => [ 'nss' => $nss, 'nid' => $nid ] - ])); - Zend_Registry::set('Zend_Config', $config); + ]); } public function testWithMissingConfig() diff --git a/tests/modules/citationExport/controller/IndexControllerTest.php b/tests/modules/citationExport/controller/IndexControllerTest.php index 334546847d..13187d3272 100644 --- a/tests/modules/citationExport/controller/IndexControllerTest.php +++ b/tests/modules/citationExport/controller/IndexControllerTest.php @@ -32,6 +32,10 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Document; +use Opus\Identifier; +use Opus\Series; + /** * Class CitationExport_IndexControllerTest. * @@ -65,7 +69,7 @@ public function testMultipleIdentifiersInRis() $this->assertContains('SN - 1-5432-876-9', $response->getBody()); $this->assertContains('SN - 1234-5678', $response->getBody()); $this->assertContains('SN - 4321-8765', $response->getBody()); - $urnResolverUrl = Zend_Registry::get('Zend_Config')->urn->resolverUrl; + $urnResolverUrl = $this->getConfig()->urn->resolverUrl; $this->assertContains('UR - ' . $urnResolverUrl . 'urn:nbn:de:foo:123-bar-456', $response->getBody()); $this->assertContains('UR - ' . $urnResolverUrl . 'urn:nbn:de:foo:123-bar-789', $response->getBody()); $this->assertContains('UR - http://www.myexampledomain.de/foo', $response->getBody()); @@ -134,7 +138,7 @@ public function testIndexActionWithInvalidOutputParam() public function testIndexActionWithUnpublishedDocument() { - $doc = new Opus_Document($this->documentId); + $doc = Document::get($this->documentId); $doc->setServerState('unpublished'); $doc->store(); $this->dispatch('/citationExport/index/index/output/foo/docId/' . $this->documentId); @@ -190,7 +194,6 @@ public function testIndexActionRisDoctypeDoctoralthesis() $this->setDocumentType('doctoralthesis'); $this->dispatch('/citationExport/index/index/output/ris/docId/' . $this->documentId); $this->checkRisAssertions('THES'); - ; } public function testIndexActionRisDoctypeMasterthesis() @@ -316,7 +319,7 @@ public function testIndexActionRisMisc() public function testIndexActionRisSubjectUncontrolled() { - $doc = new Opus_Document($this->documentId); + $doc = Document::get($this->documentId); $doc->addSubject()->setType('uncontrolled')->setValue('Freies Schlagwort'); $doc->store(); $this->dispatch('/citationExport/index/index/output/ris/docId/' . $this->documentId); @@ -327,7 +330,7 @@ public function testIndexActionRisSubjectUncontrolled() public function testIndexActionRisSubjectSwd() { - $doc = new Opus_Document($this->documentId); + $doc = Document::get($this->documentId); $doc->addSubject()->setType('swd')->setValue('SWD-Schlagwort'); $doc->store(); $this->dispatch('/citationExport/index/index/output/ris/docId/' . $this->documentId); @@ -338,8 +341,8 @@ public function testIndexActionRisSubjectSwd() public function testIndexActionRisSeriesVisible() { - $s = new Opus_Series(4); - $doc = new Opus_Document($this->documentId); + $s = new Series(4); + $doc = Document::get($this->documentId); $doc->addSeries($s)->setNumber('SeriesNumber'); $doc->store(); $this->dispatch('/citationExport/index/index/output/ris/docId/' . $this->documentId); @@ -350,8 +353,8 @@ public function testIndexActionRisSeriesVisible() public function testIndexActionRisSeriesInvisible() { - $s = new Opus_Series(3); - $doc = new Opus_Document($this->documentId); + $s = new Series(3); + $doc = Document::get($this->documentId); $doc->addSeries($s)->setNumber('SeriesNumber'); $doc->store(); $this->dispatch('/citationExport/index/index/output/ris/docId/' . $this->documentId); @@ -362,7 +365,7 @@ public function testIndexActionRisSeriesInvisible() public function testIndexActionRisPublicNote() { - $doc = new Opus_Document(146); + $doc = Document::get(146); $this->dispatch('/citationExport/index/index/output/ris/docId/' . $doc->getId()); $this->assertResponseCode(200); $response = $this->getResponse(); @@ -371,7 +374,7 @@ public function testIndexActionRisPublicNote() public function testIndexActionRisPrivateNote() { - $doc = new Opus_Document(146); + $doc = Document::get(146); $this->dispatch('/citationExport/index/index/output/ris/docId/' . $doc->getId()); $this->assertResponseCode(200); $response = $this->getResponse(); @@ -449,8 +452,8 @@ public function testIndexActionBibtexMisc() public function testIndexActionBibtexSeriesVisible() { $this->setDocumentType('preprint'); - $s = new Opus_Series(4); - $doc = new Opus_Document($this->documentId); + $s = new Series(4); + $doc = Document::get($this->documentId); $doc->addSeries($s)->setNumber('SeriesNumber'); $doc->store(); $this->dispatch('/citationExport/index/index/output/bibtex/docId/' . $this->documentId); @@ -463,8 +466,8 @@ public function testIndexActionBibtexSeriesVisible() public function testIndexActionBibtexSeriesInvisible() { $this->setDocumentType('preprint'); - $s = new Opus_Series(3); - $doc = new Opus_Document($this->documentId); + $s = new Series(3); + $doc = Document::get($this->documentId); $doc->addSeries($s)->setNumber('SeriesNumber'); $doc->store(); $this->dispatch('/citationExport/index/index/output/bibtex/docId/' . $this->documentId); @@ -477,11 +480,10 @@ public function testIndexActionBibtexSeriesInvisible() /** Regression Test for OPUSVIER-3251 */ public function testIndexActionBibtexEnrichmentVisibleAsNote() { - $bibtexConfArray = [ + $this->adjustConfiguration([ 'citationExport' => ['bibtex' => ['enrichment' => 'SourceTitle']] - ]; - $bibtexConf = new Zend_Config($bibtexConfArray); - Zend_Registry::getInstance()->get('Zend_Config')->merge($bibtexConf); + ]); + $this->dispatch('/citationExport/index/index/output/bibtex/docId/146'); $this->assertResponseCode(200); $response = $this->getResponse(); @@ -519,7 +521,7 @@ public function testDownloadActionWithInvalidOutputParam() public function testDownloadActionWithUnpublishedDocument() { - $doc = new Opus_Document($this->documentId); + $doc = Document::get($this->documentId); $doc->setServerState('unpublished'); $doc->store(); $this->dispatch('/citationExport/index/download/output/foo/docId/' . $this->documentId); @@ -714,7 +716,7 @@ public function testBibtexNoType() private function setDocumentType($documenttype) { - $doc = new Opus_Document($this->documentId); + $doc = Document::get($this->documentId); $doc->setType($documenttype); $doc->store(); } @@ -750,7 +752,7 @@ public function testDoiRendering() $doc = $this->createTestDocument(); $doc->setType('article'); - $doi = new Opus_Identifier(); + $doi = new Identifier(); $doi->setValue('123_345_678'); $doc->addIdentifierDoi($doi); diff --git a/tests/modules/citationExport/model/HelperTest.php b/tests/modules/citationExport/model/HelperTest.php index 602df8c642..751ee17c0c 100644 --- a/tests/modules/citationExport/model/HelperTest.php +++ b/tests/modules/citationExport/model/HelperTest.php @@ -32,6 +32,9 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\DnbInstitute; +use Opus\Document; + class CitationExport_Model_HelperTest extends ControllerTestCase { @@ -78,10 +81,10 @@ public function testGetAvailableStylesheets() public function testBibtexAttributeSchoolForMasterThesis() { - $document = new Opus_Document($this->_documentId); + $document = Document::get($this->_documentId); $document->setType('masterthesis'); - $institute = new Opus_DnbInstitute(4); + $institute = new DnbInstitute(4); $document->addThesisPublisher($institute); $document->store(); @@ -98,11 +101,11 @@ public function testBibtexAttributeSchoolForMasterThesis() public function testBibtexAttributeSchoolWithDepartment() { - $document = new Opus_Document($this->_documentId); + $document = Document::get($this->_documentId); $document->setType('masterthesis'); - $institute = new Opus_DnbInstitute(); + $institute = new DnbInstitute(); $institute->setName('Test Uni'); $institute->setDepartment('Test Dep'); $institute->setIsPublisher(true); @@ -127,10 +130,10 @@ public function testBibtexAttributeSchoolWithDepartment() public function testBibtexAttributeSchoolForDoctoralThesis() { - $document = new Opus_Document($this->_documentId); + $document = Document::get($this->_documentId); $document->setType('doctoralthesis'); - $institute = new Opus_DnbInstitute(4); + $institute = new DnbInstitute(4); $document->addThesisPublisher($institute); $document->store(); @@ -156,7 +159,7 @@ public function testGetExtension() public function testGetTemplateForDocument() { - $document = new Opus_Document($this->_documentId); + $document = Document::get($this->_documentId); $document->setType('masterthesis'); $document->store(); @@ -176,7 +179,7 @@ public function testGetTemplateForDocument() */ public function testGetTemplateForDocumentInvalidFormat() { - $document = new Opus_Document($this->_documentId); + $document = Document::get($this->_documentId); $document->setType('masterthesis'); $document->store(); @@ -223,7 +226,7 @@ public function testGetDocumentUnpublished() $this->enableSecurity(); $this->loginUser('security7', 'security7pwd'); - $document = new Opus_Document($this->_documentId); + $document = Document::get($this->_documentId); $document->setServerState('unpublished'); $document->store(); @@ -236,7 +239,7 @@ public function testGetDocumentUnpublished() public function testGetPlainOutputRis() { - $document = new Opus_Document(146); + $document = Document::get(146); $output = $this->_helper->getPlainOutput($document, 'ris.xslt'); diff --git a/tests/modules/default/controllers/AuthControllerTest.php b/tests/modules/default/controllers/AuthControllerTest.php index eb70c14e2c..8583d88b6c 100644 --- a/tests/modules/default/controllers/AuthControllerTest.php +++ b/tests/modules/default/controllers/AuthControllerTest.php @@ -106,7 +106,7 @@ public function testLogoutActionAsAdmin() $this->dispatch('/auth/logout/rmodule/home/rcontroller/index/raction/index'); $this->assertResponseLocationHeader($this->response, '/home'); $this->assertResponseCode('302'); - $this->assertNull(Zend_Auth::getInstance()->getIdentity()); + $this->assertNull(\Zend_Auth::getInstance()->getIdentity()); } public function testLogoutActionAsAnonymous() @@ -114,7 +114,7 @@ public function testLogoutActionAsAnonymous() $this->dispatch('/auth/logout/rmodule/home/rcontroller/index/raction/index'); $this->assertResponseLocationHeader($this->response, '/home'); $this->assertResponseCode('302'); - $this->assertNull(Zend_Auth::getInstance()->getIdentity()); + $this->assertNull(\Zend_Auth::getInstance()->getIdentity()); } public function testLogoutActionFromAdministrationModule() @@ -124,7 +124,7 @@ public function testLogoutActionFromAdministrationModule() $this->assertNotContains('Argument 4 passed to Zend_Controller_Action_Helper_Redirector::direct() must be an array, null given', $this->response->outputBody()); $this->assertResponseLocationHeader($this->response, '/home'); $this->assertResponseCode('302'); - $this->assertNull(Zend_Auth::getInstance()->getIdentity()); + $this->assertNull(\Zend_Auth::getInstance()->getIdentity()); } public function testLogoutActionFromAnyModule() @@ -133,6 +133,6 @@ public function testLogoutActionFromAnyModule() $this->dispatch('/auth/logout/rmodule/any/rcontroller/index/raction/index'); $this->assertResponseLocationHeader($this->response, '/home'); $this->assertResponseCode('302'); - $this->assertNull(Zend_Auth::getInstance()->getIdentity()); + $this->assertNull(\Zend_Auth::getInstance()->getIdentity()); } } diff --git a/tests/modules/export/BibtexExportTest.php b/tests/modules/export/BibtexExportTest.php index 6698b4f493..29c92cc030 100644 --- a/tests/modules/export/BibtexExportTest.php +++ b/tests/modules/export/BibtexExportTest.php @@ -42,9 +42,9 @@ public function setUp() { parent::setUp(); - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'searchengine' => ['solr' => ['numberOfDefaultSearchResults' => '10']] - ])); + ]); } /** @@ -77,9 +77,9 @@ public function setUp() public function testExportSingleDocument() { - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'export' => ['download' => self::CONFIG_VALUE_FALSE] - ])); + ]); $this->dispatch('/export/index/bibtex/searchtype/id/docId/146'); @@ -96,10 +96,10 @@ public function testExportSingleDocument() */ public function testExportLatestDocuments() { - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'export' => ['download' => self::CONFIG_VALUE_FALSE], 'searchengine' => ['solr' => ['numberOfDefaultSearchResults' => '10']] - ])); + ]); $this->dispatch('/export/index/bibtex/searchtype/latest'); @@ -112,9 +112,9 @@ public function testExportLatestDocuments() public function testExportLatestDocumentsWithCustomRows() { - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'export' => ['download' => self::CONFIG_VALUE_FALSE] - ])); + ]); $this->dispatch('/export/index/bibtex/searchtype/latest/rows/12'); diff --git a/tests/modules/export/BootstrapTest.php b/tests/modules/export/BootstrapTest.php index e39b3ed120..447f35685f 100644 --- a/tests/modules/export/BootstrapTest.php +++ b/tests/modules/export/BootstrapTest.php @@ -45,13 +45,13 @@ public function testInitExport() $this->dispatch('/frontdoor/index/index/docId/1'); // TODO configuration change has no influence at this point - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'export' => [ 'stylesheet' => [ 'frontdoor' => null ] ] - ])); + ]); $this->assertResponseCode(200); $this->assertQuery('a.export.bibtex'); diff --git a/tests/modules/export/DataCiteExportTest.php b/tests/modules/export/DataCiteExportTest.php index 943f5d830e..e01135c8b4 100644 --- a/tests/modules/export/DataCiteExportTest.php +++ b/tests/modules/export/DataCiteExportTest.php @@ -31,6 +31,13 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Date; +use Opus\Document; +use Opus\Identifier; +use Opus\Model\ModelException; +use Opus\Person; +use Opus\Title; + class Export_DataCiteExportTest extends ControllerTestCase { @@ -41,7 +48,6 @@ class Export_DataCiteExportTest extends ControllerTestCase public function testExportOfValidDataCiteXML() { // DOI Präfix setzen - $oldConfig = Zend_Registry::get('Zend_Config'); $this->adaptDoiConfiguration(); // freigegebenes Testdokument mit allen Pflichtfeldern anlegen @@ -51,9 +57,6 @@ public function testExportOfValidDataCiteXML() $this->dispatch('/export/index/datacite/docId/' . $docId); - // Änderungen an Konfiguration zurücksetzen - Zend_Registry::set('Zend_Config', $oldConfig); - $this->assertResponseCode(200); $this->assertHeaderContains('Content-Type', 'text/xml; charset=UTF-8'); $this->assertNotEmpty($this->getResponse()->getBody()); @@ -90,7 +93,6 @@ public function testExportOfDataCiteXmlStatusPage() public function testExportOfDataCiteXmlStatusPageForUnpublishedDoc() { - $oldConfig = Zend_Registry::get('Zend_Config'); $this->adaptDoiConfiguration(); // nicht freigegebenes Testdokument mit allen Pflichtfeldern erzeugen @@ -101,9 +103,6 @@ public function testExportOfDataCiteXmlStatusPageForUnpublishedDoc() $this->useGerman(); $this->dispatch('/export/index/datacite/docId/' . $docId); - // Änderungen an Konfiguration zurücksetzen - Zend_Registry::set('Zend_Config', $oldConfig); - $this->assertResponseCode(200); $this->assertContains("DataCite XML des nicht freigeschalteten Dokuments $docId ist gültig", $this->getResponse()->getBody()); @@ -114,7 +113,6 @@ public function testExportOfDataCiteXmlStatusPageForUnpublishedDoc() public function testExportOfDataCiteXmlStatusPageForUnpublishedDocWithMissingField() { - $oldConfig = Zend_Registry::get('Zend_Config'); $this->adaptDoiConfiguration(); // nicht freigegebenes Testdokument mit Pflichtfeldern erzeugen @@ -129,9 +127,6 @@ public function testExportOfDataCiteXmlStatusPageForUnpublishedDocWithMissingFie $this->useGerman(); $this->dispatch('/export/index/datacite/docId/' . $docId); - // Änderungen an Konfiguration zurücksetzen - Zend_Registry::set('Zend_Config', $oldConfig); - $this->assertResponseCode(200); $this->assertContains("DataCite XML von Dokument $docId ist nicht gültig", $this->getResponse()->getBody()); @@ -142,21 +137,17 @@ public function testExportOfDataCiteXmlStatusPageForUnpublishedDocWithMissingFie public function testExportOfDataCiteXmlForUnpublishedDocWithServerDatePublished() { - $oldConfig = Zend_Registry::get('Zend_Config'); $this->adaptDoiConfiguration(); // nicht freigegebenes Testdokument mit Pflichtfeldern erzeugen und ServerDatePublished $doc = $this->createTestDocument(); $doc->setServerState('unpublished'); - $doc->setServerDatePublished(new Opus_Date('2019-12-24')); + $doc->setServerDatePublished(new Date('2019-12-24')); $docId = $this->addRequiredFields($doc); $this->useGerman(); $this->dispatch('/export/index/datacite/docId/' . $docId); - // Änderungen an Konfiguration zurücksetzen - Zend_Registry::set('Zend_Config', $oldConfig); - $this->assertResponseCode(200); $this->assertHeaderContains('Content-Type', 'text/xml; charset=UTF-8'); $this->assertNotEmpty($this->getResponse()->getBody()); @@ -164,7 +155,6 @@ public function testExportOfDataCiteXmlForUnpublishedDocWithServerDatePublished( public function testExportOfDataCiteXmlStatusPageForPublishedDocWithoutServerDatePublished() { - $oldConfig = Zend_Registry::get('Zend_Config'); $this->adaptDoiConfiguration(); // freigegebenes Testdokument mit Pflichtfeldern erzeugen @@ -172,16 +162,13 @@ public function testExportOfDataCiteXmlStatusPageForPublishedDocWithoutServerDat $doc->setServerState('published'); $docId = $this->addRequiredFields($doc); - $doc = new Opus_Document($docId); + $doc = Document::get($docId); $doc->setServerDatePublished(''); // dies setzt das Publication Year auf 0001 (ohne Monat und Tag) $doc->store(); $this->useGerman(); $this->dispatch('/export/index/datacite/docId/' . $docId); - // Änderungen an Konfiguration zurücksetzen - Zend_Registry::set('Zend_Config', $oldConfig); - $this->assertResponseCode(200); $this->assertContains("DataCite XML von Dokument $docId ist nicht gültig", $this->getResponse()->getBody()); @@ -195,24 +182,21 @@ public function testExportOfDataCiteXmlStatusPageForPublishedDocWithoutServerDat * Nicht freigeschaltete Dokumente können nur dann exportiert werden, * wenn der Benutzer das Recht 'resource_documents' besitzt. * - * @throws Opus_Model_Exception + * @throws ModelException * @throws Zend_Exception */ public function testExportOfDataCiteXmlWithUnpublishedDocNotAllowed() { $removeAccess = $this->addModuleAccess('export', 'guest'); $this->enableSecurity(); - $config = Zend_Registry::get('Zend_Config'); - - Zend_Registry::get('Zend_Config')->merge( - new Zend_Config( - ['plugins' => - ['export' => - ['datacite' => ['adminOnly' => self::CONFIG_VALUE_FALSE]] - ] + + $this->adjustConfiguration([ + 'plugins' => [ + 'export' => [ + 'datacite' => ['adminOnly' => self::CONFIG_VALUE_FALSE] ] - ) - ); + ] + ]); $doc = $this->createTestDocument(); $doc->setServerState('unpublished'); @@ -226,7 +210,7 @@ public function testExportOfDataCiteXmlWithUnpublishedDocNotAllowed() // revert configuration changes $this->restoreSecuritySetting(); - Zend_Registry::set('Zend_Config', $config); + if ($removeAccess) { $this->removeModuleAccess('export', 'guest'); } @@ -240,17 +224,14 @@ public function testExportOfDataCiteXmlWithUnpublishedDocAllowedForAdmin() $this->useEnglish(); $this->enableSecurity(); - $config = Zend_Registry::get('Zend_Config'); - - Zend_Registry::get('Zend_Config')->merge( - new Zend_Config( - ['plugins' => - ['export' => - ['datacite' => ['adminOnly' => self::CONFIG_VALUE_FALSE]] - ] + + $this->adjustConfiguration([ + 'plugins' => [ + 'export' => [ + 'datacite' => ['adminOnly' => self::CONFIG_VALUE_FALSE] ] - ) - ); + ] + ]); $doc = $this->createTestDocument(); $doc->setServerState('unpublished'); @@ -264,7 +245,6 @@ public function testExportOfDataCiteXmlWithUnpublishedDocAllowedForAdmin() // revert configuration changes $this->restoreSecuritySetting(); - Zend_Registry::set('Zend_Config', $config); $this->assertResponseCode(200); $this->assertContains("DataCite XML of document ${docId} is not valid", $this->getResponse()->getBody()); @@ -276,17 +256,14 @@ public function testExportOfDataCiteXmlWithUnpublishedDocAllowedForNonAdminUserW $removeAccess = $this->addModuleAccess('export', 'docsadmin'); $this->enableSecurity(); - $config = Zend_Registry::get('Zend_Config'); - - Zend_Registry::get('Zend_Config')->merge( - new Zend_Config( - ['plugins' => - ['export' => - ['datacite' => ['adminOnly' => self::CONFIG_VALUE_FALSE]] - ] + + $this->adjustConfiguration([ + 'plugins' => [ + 'export' => [ + 'datacite' => ['adminOnly' => self::CONFIG_VALUE_FALSE] ] - ) - ); + ] + ]); $doc = $this->createTestDocument(); $doc->setServerState('unpublished'); @@ -300,7 +277,7 @@ public function testExportOfDataCiteXmlWithUnpublishedDocAllowedForNonAdminUserW // revert configuration changes $this->restoreSecuritySetting(); - Zend_Registry::set('Zend_Config', $config); + if ($removeAccess) { $this->removeModuleAccess('export', 'docsadmin'); } @@ -315,17 +292,14 @@ public function testExportOfDataCiteXmlWithUnpublishedDocAllowedForNonAdminUserW $removeAccess = $this->addModuleAccess('export', 'collectionsadmin'); $this->enableSecurity(); - $config = Zend_Registry::get('Zend_Config'); - - Zend_Registry::get('Zend_Config')->merge( - new Zend_Config( - ['plugins' => - ['export' => - ['datacite' => ['adminOnly' => self::CONFIG_VALUE_FALSE]] - ] + + $this->adjustConfiguration([ + 'plugins' => [ + 'export' => [ + 'datacite' => ['adminOnly' => self::CONFIG_VALUE_FALSE] ] - ) - ); + ] + ]); $doc = $this->createTestDocument(); $doc->setServerState('unpublished'); @@ -339,7 +313,7 @@ public function testExportOfDataCiteXmlWithUnpublishedDocAllowedForNonAdminUserW // revert configuration changes $this->restoreSecuritySetting(); - Zend_Registry::set('Zend_Config', $config); + if ($removeAccess) { $this->removeModuleAccess('export', 'collectionsadmin'); } @@ -349,7 +323,7 @@ public function testExportOfDataCiteXmlWithUnpublishedDocAllowedForNonAdminUserW } /** - * @param Opus_Document $doc + * @param Document $doc * @return int ID des gespeicherten Dokuments */ private function addRequiredFields($doc) @@ -359,19 +333,19 @@ private function addRequiredFields($doc) $doc->setLanguage('deu'); $docId = $doc->store(); - $doc = new Opus_Document($docId); + $doc = Document::get($docId); - $doi = new Opus_Identifier(); + $doi = new Identifier(); $doi->setType('doi'); $doi->setValue('10.2345/opustest-' . $docId); $doc->setIdentifier([$doi]); - $author = new Opus_Person(); + $author = new Person(); $author->setFirstName('John'); $author->setLastName('Doe'); $doc->setPersonAuthor([$author]); - $title = new Opus_Title(); + $title = new Title(); $title->setValue('Meaningless title'); $title->setLanguage('deu'); $doc->setTitleMain([$title]); @@ -382,14 +356,12 @@ private function addRequiredFields($doc) private function adaptDoiConfiguration() { - Zend_Registry::set('Zend_Config', Zend_Registry::get('Zend_Config')->merge( - new Zend_Config([ - 'doi' => [ - 'autoCreate' => false, - 'prefix' => '10.2345', - 'localPrefix' => 'opustest' - ] - ]) - )); + $this->adjustConfiguration([ + 'doi' => [ + 'autoCreate' => false, + 'prefix' => '10.2345', + 'localPrefix' => 'opustest' + ] + ]); } } diff --git a/tests/modules/export/Marc21ExportTest.php b/tests/modules/export/Marc21ExportTest.php index 4d06cfe9dc..5d1c9ecf6d 100644 --- a/tests/modules/export/Marc21ExportTest.php +++ b/tests/modules/export/Marc21ExportTest.php @@ -32,6 +32,8 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Model\ModelException; + class Export_Marc21ExportTest extends ControllerTestCase { @@ -41,24 +43,19 @@ class Export_Marc21ExportTest extends ControllerTestCase * Nicht freigeschaltete Dokumente können nur dann im Format MARC21-XML exportiert werden, * wenn der Benutzer das Recht 'resource_documents' besitzt. * - * @throws Opus_Model_Exception + * @throws ModelException * @throws Zend_Exception */ public function testMarc21XmlExportWithUnpublishedDocNotAllowed() { $removeAccess = $this->addModuleAccess('export', 'guest'); $this->enableSecurity(); - $config = Zend_Registry::get('Zend_Config'); - - Zend_Registry::get('Zend_Config')->merge( - new Zend_Config( - ['plugins' => - ['export' => - ['marc21' => ['adminOnly' => self::CONFIG_VALUE_FALSE]] - ] + $this->adjustConfiguration([ + 'plugins' => + ['export' => + ['marc21' => ['adminOnly' => self::CONFIG_VALUE_FALSE]] ] - ) - ); + ]); $doc = $this->createTestDocument(); $doc->setServerState('unpublished'); @@ -72,7 +69,7 @@ public function testMarc21XmlExportWithUnpublishedDocNotAllowed() // revert configuration changes $this->restoreSecuritySetting(); - Zend_Registry::set('Zend_Config', $config); + if ($removeAccess) { $this->removeModuleAccess('export', 'guest'); } @@ -84,17 +81,12 @@ public function testMarc21XmlExportWithUnpublishedDocNotAllowed() public function testMarc21XmlExportWithUnpublishedDocAllowedForAdmin() { $this->enableSecurity(); - $config = Zend_Registry::get('Zend_Config'); - - Zend_Registry::get('Zend_Config')->merge( - new Zend_Config( - ['plugins' => - ['export' => - ['marc21' => ['adminOnly' => self::CONFIG_VALUE_FALSE]] - ] + $this->adjustConfiguration([ + 'plugins' => + ['export' => + ['marc21' => ['adminOnly' => self::CONFIG_VALUE_FALSE]] ] - ) - ); + ]); $doc = $this->createTestDocument(); $doc->setServerState('unpublished'); @@ -108,7 +100,6 @@ public function testMarc21XmlExportWithUnpublishedDocAllowedForAdmin() // revert configuration changes $this->restoreSecuritySetting(); - Zend_Registry::set('Zend_Config', $config); $this->assertResponseCode(200); $this->assertXpathContentContains('//marc:leader', '00000naa a22000005 4500'); @@ -126,17 +117,12 @@ public function testMarc21XmlExportWithUnpublishedDocAllowedForNonAdminUserWithP { $removeAccess = $this->addModuleAccess('export', 'docsadmin'); $this->enableSecurity(); - $config = Zend_Registry::get('Zend_Config'); - - Zend_Registry::get('Zend_Config')->merge( - new Zend_Config( - ['plugins' => - ['export' => - ['marc21' => ['adminOnly' => self::CONFIG_VALUE_FALSE]] - ] + $this->adjustConfiguration([ + 'plugins' => + ['export' => + ['marc21' => ['adminOnly' => self::CONFIG_VALUE_FALSE]] ] - ) - ); + ]); $doc = $this->createTestDocument(); $doc->setServerState('unpublished'); @@ -150,7 +136,7 @@ public function testMarc21XmlExportWithUnpublishedDocAllowedForNonAdminUserWithP // revert configuration changes $this->restoreSecuritySetting(); - Zend_Registry::set('Zend_Config', $config); + if ($removeAccess) { $this->removeModuleAccess('export', 'docsadmin'); } @@ -171,17 +157,14 @@ public function testMarc21XmlExportWithPublishedDocNotAllowedForGuest() { $removeAccess = $this->addModuleAccess('export', 'guest'); $this->enableSecurity(); - $config = Zend_Registry::get('Zend_Config'); - - Zend_Registry::get('Zend_Config')->merge( - new Zend_Config( - ['plugins' => - ['export' => - ['marc21' => ['adminOnly' => self::CONFIG_VALUE_TRUE]] - ] + + $this->adjustConfiguration([ + 'plugins' => [ + 'export' => [ + 'marc21' => ['adminOnly' => self::CONFIG_VALUE_TRUE] ] - ) - ); + ] + ]); $doc = $this->createTestDocument(); $doc->setServerState('published'); @@ -193,7 +176,7 @@ public function testMarc21XmlExportWithPublishedDocNotAllowedForGuest() // revert configuration changes $this->restoreSecuritySetting(); - Zend_Registry::set('Zend_Config', $config); + if ($removeAccess) { $this->removeModuleAccess('export', 'guest'); } @@ -206,17 +189,13 @@ public function testMarc21XmlExportWithPublishedDocAllowedForAdmin() { $removeAccess = $this->addModuleAccess('export', 'docsadmin'); $this->enableSecurity(); - $config = Zend_Registry::get('Zend_Config'); - - Zend_Registry::get('Zend_Config')->merge( - new Zend_Config( - ['plugins' => - ['export' => - ['marc21' => ['adminOnly' => self::CONFIG_VALUE_TRUE]] - ] + + $this->adjustConfiguration([ + 'plugins' => + ['export' => + ['marc21' => ['adminOnly' => self::CONFIG_VALUE_TRUE]] ] - ) - ); + ]); $doc = $this->createTestDocument(); $doc->setServerState('published'); @@ -230,7 +209,7 @@ public function testMarc21XmlExportWithPublishedDocAllowedForAdmin() // revert configuration changes $this->restoreSecuritySetting(); - Zend_Registry::set('Zend_Config', $config); + if ($removeAccess) { $this->removeModuleAccess('export', 'docsadmin'); } @@ -253,17 +232,13 @@ public function testMarc21XmlExportWithPublishedDocAllowedForGuest() { $removeAccess = $this->addModuleAccess('export', 'guest'); $this->enableSecurity(); - $config = Zend_Registry::get('Zend_Config'); - - Zend_Registry::get('Zend_Config')->merge( - new Zend_Config( - ['plugins' => - ['export' => - ['marc21' => ['adminOnly' => self::CONFIG_VALUE_FALSE]] - ] + + $this->adjustConfiguration([ + 'plugins' => + ['export' => + ['marc21' => ['adminOnly' => self::CONFIG_VALUE_FALSE]] ] - ) - ); + ]); $doc = $this->createTestDocument(); $doc->setServerState('published'); @@ -275,7 +250,7 @@ public function testMarc21XmlExportWithPublishedDocAllowedForGuest() // revert configuration changes $this->restoreSecuritySetting(); - Zend_Registry::set('Zend_Config', $config); + if ($removeAccess) { $this->removeModuleAccess('export', 'guest'); } @@ -298,17 +273,13 @@ public function testMarc21XmlExportWithUnpublishedDocAllowedForNonAdminUserWitho { $removeAccess = $this->addModuleAccess('export', 'collectionsadmin'); $this->enableSecurity(); - $config = Zend_Registry::get('Zend_Config'); - - Zend_Registry::get('Zend_Config')->merge( - new Zend_Config( - ['plugins' => - ['export' => - ['marc21' => ['adminOnly' => self::CONFIG_VALUE_FALSE]] - ] + + $this->adjustConfiguration([ + 'plugins' => + ['export' => + ['marc21' => ['adminOnly' => self::CONFIG_VALUE_FALSE]] ] - ) - ); + ]); $doc = $this->createTestDocument(); $doc->setServerState('unpublished'); @@ -322,7 +293,7 @@ public function testMarc21XmlExportWithUnpublishedDocAllowedForNonAdminUserWitho // revert configuration changes $this->restoreSecuritySetting(); - Zend_Registry::set('Zend_Config', $config); + if ($removeAccess) { $this->removeModuleAccess('export', 'collectionsadmin'); } diff --git a/tests/modules/export/RisExportTest.php b/tests/modules/export/RisExportTest.php index cb813dba22..7c7783e24b 100644 --- a/tests/modules/export/RisExportTest.php +++ b/tests/modules/export/RisExportTest.php @@ -48,7 +48,7 @@ public function testDoiUrlRendered() $docId = $document->store(); - $doiResolverUrl = Zend_Registry::get('Zend_Config')->doi->resolverUrl; + $doiResolverUrl = $this->getConfig()->doi->resolverUrl; $this->dispatch("/export/index/ris/searchtype/id/docId/$docId"); diff --git a/tests/modules/export/controllers/IndexControllerTest.php b/tests/modules/export/controllers/IndexControllerTest.php index 71d43a786e..7c35d2e5f8 100644 --- a/tests/modules/export/controllers/IndexControllerTest.php +++ b/tests/modules/export/controllers/IndexControllerTest.php @@ -29,12 +29,15 @@ * @author Sascha Szott * @author Michael Lang * @author Jens Schwidder - * @copyright Copyright (c) 2008-2019, OPUS 4 development team + * @copyright Copyright (c) 2008-2021, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Document; +use Opus\File; +use Opus\Title; +use Opus\Model\ModelException; use Opus\Search\Service; -use \Opus\Search\Util\Indexer; /** * Class Export_IndexControllerTest. @@ -188,9 +191,8 @@ public function testRequestToRawXmlIsDenied() $this->_removeExportFromGuest = $this->addAccessOnModuleExportForGuest(); // enable security - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $config->security = self::CONFIG_VALUE_TRUE; - Zend_Registry::set('Zend_Config', $config); $this->dispatch('/export/index/index/export/xml'); @@ -211,13 +213,12 @@ public function testUnavailableSolrServerReturns503() $this->_removeExportFromGuest = $this->addAccessOnModuleExportForGuest(); // manipulate solr configuration - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $host = $config->searchengine->index->host; $port = $config->searchengine->index->port; $this->disableSolr(); $config->security = self::CONFIG_VALUE_TRUE; - Zend_Registry::set('Zend_Config', $config); $this->dispatch('/export/index/index/searchtype/all/export/xml/stylesheet/example'); $body = $this->getResponse()->getBody(); @@ -237,7 +238,7 @@ public function testSolrIndexIsNotUpToDate() $doc1 = $this->createTestDocument(); $doc1->setServerState('published'); $doc1->setLanguage('eng'); - $title = new Opus_Title(); + $title = new Title(); $title->setValue('test document for OPUSVIER-1726'); $title->setLanguage('eng'); $doc1->setTitleMain($title); @@ -248,7 +249,7 @@ public function testSolrIndexIsNotUpToDate() $doc2 = $this->createTestDocument(); $doc2->setServerState('published'); $doc2->setLanguage('eng'); - $title = new Opus_Title(); + $title = new Title(); $title->setValue('another test document for OPUSVIER-1726'); $title->setLanguage('eng'); $doc2->setTitleMain($title); @@ -261,7 +262,7 @@ public function testSolrIndexIsNotUpToDate() $solrXml = $indexer->toSolrDocument($doc2); // delete document from database - $doc2->deletePermanent(); + $doc2->delete(); // add document to search index // TODO fix $methodSendSolrXmlToServer = $class->getMethod('sendSolrXmlToServer'); @@ -275,7 +276,7 @@ public function testSolrIndexIsNotUpToDate() $indexer->removeDocumentFromEntryIndexById($docId2); $indexer->commit(); - $doc1->deletePermanent(); + $doc1->delete(); $body = $this->getResponse()->getBody(); @@ -300,7 +301,7 @@ private function helperForOPUSVIER2488($url, $numOfTestDocs, $rows, $start = 0) $doc = $this->createTestDocument(); $doc->setServerState('published'); $doc->setLanguage('eng'); - $title = new Opus_Title(); + $title = new Title(); $title->setValue('OPUSVIER-2488'); $title->setLanguage('eng'); $doc->setTitleMain($title); @@ -603,16 +604,14 @@ public function testPublistActionWithoutStylesheetParameterInUrl() public function testPublistActionWithoutStylesheetParameterInUrlAndInvalidConfigParameter() { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); if (isset($config->plugins->export->publist->stylesheet)) { $config->plugins->export->publist->stylesheet = 'invalid'; } else { - $config = new Zend_Config(['plugins' => ['export' => [ - 'publist' => ['stylesheet' => 'invalid']], true]]); - // Include the above made configuration changes in the application configuration. - $config->merge(Zend_Registry::get('Zend_Config')); + $this->adjustConfiguration([ + 'plugins' => ['export' => ['publist' => ['stylesheet' => 'invalid']]] + ]); } - Zend_Registry::set('Zend_Config', $config); $this->dispatch('/export/index/publist/role/publists/number/coll_visible'); @@ -623,25 +622,23 @@ public function testPublistActionWithoutStylesheetParameterInUrlAndInvalidConfig public function testPublistActionWithValidStylesheetInConfig() { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); + if (isset($config->plugins->export->publist->stylesheet)) { $config->plugins->export->publist->stylesheet = 'raw'; } else { - $config = new Zend_Config(['plugins' => ['export' => [ - 'publist' => ['stylesheet' => 'raw']], true]]); - // Include the above made configuration changes in the application configuration. - $config->merge(Zend_Registry::get('Zend_Config')); + $this->adjustConfiguration([ + 'plugins' => ['export' => ['publist' => ['stylesheet' => 'raw']], true] + ]); } if (isset($config->plugins->export->publist->stylesheetDirectory)) { $config->plugins->export->publist->stylesheetDirectory = 'stylesheets'; } else { - $config = new Zend_Config(['plugins' => ['export' => [ - 'publist' => ['stylesheetDirectory' => 'stylesheets']], true]]); - // Include the above made configuration changes in the application configuration. - $config->merge(Zend_Registry::get('Zend_Config')); + $this->adjustConfiguration([ + 'plugins' => ['export' => ['publist' => ['stylesheetDirectory' => 'stylesheets']], true] + ]); } - Zend_Registry::set('Zend_Config', $config); $this->dispatch('/export/index/publist/role/publists/number/coll_visible'); @@ -677,7 +674,7 @@ public function testPublistActionUrnResolverUrlCorrect() { $this->dispatch('/export/index/publist/role/ccs/number/H.3'); - $urnResolverUrl = Zend_Registry::get('Zend_Config')->urn->resolverUrl; + $urnResolverUrl = $this->getConfig()->urn->resolverUrl; $this->assertXpathContentContains('//a[starts-with(@href, "' . $urnResolverUrl . '")]', 'URN'); } @@ -686,7 +683,7 @@ public function testPublistActionDoiResolverUrlCorrect() { $this->dispatch('/export/index/publist/role/ddc/number/51'); // contains test document 146 - $doiResolverUrl = Zend_Registry::get('Zend_Config')->doi->resolverUrl; + $doiResolverUrl = $this->getConfig()->doi->resolverUrl; $this->assertXpathContentContains('//a[starts-with(@href, "' . $doiResolverUrl . '")]', 'DOI'); } @@ -704,17 +701,15 @@ protected function setPublistConfig($options) public function testPublistActionGroupedByCompletedYear() { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); // FIXME OPUSVIER-4130 config does not make sense - completely ignores value of setting if (isset($config->plugins->export->publist->groupby->completedyear)) { $config->plugins->export->publist->groupby->completedyear = self::CONFIG_VALUE_TRUE; } else { - $configNew = new Zend_Config(['plugins' => ['export' => [ - 'publist' => ['groupby' => ['completedyear' => self::CONFIG_VALUE_TRUE]]]]], false); - // Include the above made configuration changes in the application configuration. - $config->merge($configNew); + $this->adjustConfiguration([ + 'plugins' => ['export' => ['publist' => ['groupby' => ['completedyear' => self::CONFIG_VALUE_TRUE]]]] + ]); } - Zend_Registry::set('Zend_Config', $config); $this->dispatch('/export/index/publist/role/publists/number/coll_visible'); @@ -795,19 +790,17 @@ public function testPrefixesForIdClassAndAnchorInDefaultLayout() */ public function testPublistActionDisplaysUrlencodedFiles() { - Zend_Registry::get('Zend_Config')->merge( - new Zend_Config(['plugins' => ['export' => [ - 'publist' => [ - 'file' => [ - 'allow' => [ - 'mimetype' => ['application/xhtml+xml' => 'HTML']]]]]]]) - ); + $this->adjustConfiguration([ + 'plugins' => ['export' => ['publist' => ['file' => ['allow' => [ + 'mimetype' => ['application/xhtml+xml' => 'HTML'] + ]]]]] + ]); // explicitly re-initialize mime type config to apply changes in Zend_Config // This is necessary due to static variable in Export_Model_PublicationList // which is not reset between tests. - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $this->assertTrue( isset($config->plugins->export->publist->file->allow->mimetype), 'Failed setting configuration option' @@ -818,9 +811,9 @@ public function testPublistActionDisplaysUrlencodedFiles() 'Failed setting configuration option' ); - $doc = new Opus_Document(92); + $doc = Document::get(92); $file = $doc->getFile(1); - $this->assertTrue($file instanceof Opus_File, 'Test setup has changed.'); + $this->assertTrue($file instanceof File, 'Test setup has changed.'); $this->assertEquals('datei mit unüblichem Namen.xhtml', $file->getPathName(), 'Test setup has changed.'); $collection = $doc->getCollection(0); @@ -899,22 +892,26 @@ public function testXmlExportDoesNotContainUnpublishedDocument() /** * Regressionstest für OPUSVIER-3391. - * // TODO insert host + * // TODO refactor - bootstrapping happens before so the helpers need to be adjusted - better way? */ public function testExportedFilePath() { - Zend_Controller_Front::getInstance()->setBaseUrl('opus4dev'); + $opusUrl = 'https://localhost/opus4'; + + $view = $this->getView(); + $view->getHelper('ServerUrl')->setHost('localhost'); + $view->getHelper('ServerUrl')->setScheme('https'); + \Zend_Controller_Front::getInstance()->setBaseUrl('/opus4'); + $this->dispatch('/export/index/index/docId/146/export/xml/stylesheet/example/searchtype/id'); - $host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ''; - $server = $this->getRequest()->getBasePath(); - $this->assertXpathContentContains('//file', 'https://' . $host . $server . '/files/146/test.pdf'); + $this->assertXpathContentContains('//file', $opusUrl . '/files/146/test.pdf'); } /** * Zugriff auf MARC21 Export standardmäßig nur für Administratoren freigegeben, * auch wenn das Zugriffsrecht auf das Module export vorhanden ist. * - * @throws Opus_Model_Exception + * @throws ModelException */ public function testNonAdminAccessOnRestrictedMarc21ExportForbidden() { @@ -934,7 +931,7 @@ public function testNonAdminAccessOnRestrictedMarc21ExportForbidden() * Zugriff auf DataCite Export standardmäßig nur für Administratoren freigegeben, * auch wenn das Zugriffsrecht auf das Module export vorhanden ist. * - * @throws Opus_Model_Exception + * @throws ModelException */ public function testNonAdminAccessOnRestrictedDataCiteExportForbidden() { @@ -954,7 +951,7 @@ public function testNonAdminAccessOnRestrictedDataCiteExportForbidden() * Zugriff auf RIS Export ist nicht eingeschränkt, wenn Zugriffsrecht auf das * Module export besteht. * - * @throws Opus_Model_Exception + * @throws ModelException */ public function testNonAdminAccessOnUnrestrictedExportAllowed() { @@ -976,11 +973,9 @@ public function testNonAdminAccessOnUnrestrictedExportAllowed() */ public function testNonAdminAccessOnUnrestrictedMarc21ExportAllowed() { - Zend_Registry::get('Zend_Config')->merge( - new Zend_Config( - ['plugins' => ['export' => ['marc21' => ['adminOnly' => self::CONFIG_VALUE_FALSE]]]] - ) - ); + $this->adjustConfiguration([ + 'plugins' => ['export' => ['marc21' => ['adminOnly' => self::CONFIG_VALUE_FALSE]]] + ]); $exportAccessProvided = $this->addAccessOnModuleExportForGuest(); $this->enableSecurity(); @@ -999,7 +994,7 @@ public function testNonAdminAccessOnUnrestrictedMarc21ExportAllowed() * Gibt true zurück, wenn der Zugriff auf das Module export hinzugefügt wurde. * * @return bool - * @throws Opus_Model_Exception + * @throws ModelException */ private function addAccessOnModuleExportForGuest() { diff --git a/tests/modules/export/models/DataciteExportTest.php b/tests/modules/export/models/DataciteExportTest.php index 305b6a7006..06ac66132a 100644 --- a/tests/modules/export/models/DataciteExportTest.php +++ b/tests/modules/export/models/DataciteExportTest.php @@ -30,6 +30,12 @@ * @copyright Copyright (c) 2019, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ + +use Opus\Document; +use Opus\Identifier; +use Opus\Person; +use Opus\Title; + class Export_Model_DataciteExportTest extends ControllerTestCase { @@ -59,37 +65,32 @@ public function testExecuteWithUnknownDocId() public function testExecuteWithValidDoc() { - // DOI Präfix setzen - $oldConfig = Zend_Registry::get('Zend_Config'); - - Zend_Registry::set('Zend_Config', Zend_Registry::get('Zend_Config')->merge( - new Zend_Config([ - 'doi' => [ - 'prefix' => '10.2345', - 'localPrefix' => 'opustest' - ] - ]) - )); + $this->adjustConfiguration([ + 'doi' => [ + 'prefix' => '10.2345', + 'localPrefix' => 'opustest' + ] + ]); // Testdokument mit allen Pflichtfeldern anlegen - $doc = new Opus_Document(); + $doc = Document::new(); $doc->setType('all'); $doc->setServerState('published'); $doc->setPublisherName('Foo Publishing Corp.'); $doc->setLanguage('deu'); $docId = $doc->store(); - $doi = new Opus_Identifier(); + $doi = new Identifier(); $doi->setType('doi'); $doi->setValue('10.2345/opustest-' . $docId); $doc->setIdentifier([$doi]); - $author = new Opus_Person(); + $author = new Person(); $author->setFirstName('John'); $author->setLastName('Doe'); $doc->setPersonAuthor([$author]); - $title = new Opus_Title(); + $title = new Title(); $title->setValue('Meaningless title'); $title->setLanguage('deu'); $doc->setTitleMain([$title]); @@ -105,9 +106,7 @@ public function testExecuteWithValidDoc() $result = $plugin->execute(); // Testdokument wieder löschen - $doc->deletePermanent(); - // Änderungen an Konfiguration zurücksetzen - Zend_Registry::set('Zend_Config', $oldConfig); + $doc->delete(); $this->assertTrue($result); $this->assertHeaderContains('Content-Type', 'text/xml; charset=UTF-8'); @@ -116,7 +115,7 @@ public function testExecuteWithValidDoc() public function testExecuteWithInvalidDoc() { // Testdokument mit fehlenden Pflichtfeldern anlegen - $doc = new Opus_Document(); + $doc = Document::new(); $doc->setServerState('published'); $docId = $doc->store(); @@ -125,13 +124,13 @@ public function testExecuteWithInvalidDoc() $request->setParam('docId', $docId); $plugin->setRequest($request); $plugin->setResponse($this->getResponse()); - $view = new Zend_View(); + $view = new \Zend_View(); $plugin->setView($view); $result = $plugin->execute(); // Testdokument wieder löschen - $doc->deletePermanent(); + $doc->delete(); $this->assertFalse($result); $this->assertTrue(is_array($view->requiredFieldsStatus)); @@ -141,7 +140,7 @@ public function testExecuteWithInvalidDoc() public function testExecuteWithInvalidDocAndInvalidValidateParamValue() { // Testdokument mit fehlenden Pflichtfeldern anlegen - $doc = new Opus_Document(); + $doc = Document::new(); $doc->setServerState('published'); $docId = $doc->store(); @@ -152,13 +151,13 @@ public function testExecuteWithInvalidDocAndInvalidValidateParamValue() $plugin->setRequest($request); $plugin->setResponse($this->getResponse()); - $view = new Zend_View(); + $view = new \Zend_View(); $plugin->setView($view); $result = $plugin->execute(); // Testdokument wieder löschen - $doc->deletePermanent(); + $doc->delete(); $this->assertFalse($result); $this->assertTrue(is_array($view->requiredFieldsStatus)); @@ -167,7 +166,7 @@ public function testExecuteWithInvalidDocAndInvalidValidateParamValue() public function testExecuteWithInvalidDocSkipValidation() { - $doc = new Opus_Document(); + $doc = Document::new(); $doc->setServerState('published'); $docId = $doc->store(); @@ -181,7 +180,7 @@ public function testExecuteWithInvalidDocSkipValidation() $result = $plugin->execute(); // Testdokument wieder löschen - $doc->deletePermanent(); + $doc->delete(); // XML wird in jedem Fall generiert, auch wenn das DataCite-XML nicht valide ist $this->assertTrue($result); diff --git a/tests/modules/export/models/PublistExportTest.php b/tests/modules/export/models/PublistExportTest.php index 6621f3c5b3..c699311359 100644 --- a/tests/modules/export/models/PublistExportTest.php +++ b/tests/modules/export/models/PublistExportTest.php @@ -27,10 +27,12 @@ * @category Application * @package Module_Export * @author Michael Lang - * @copyright Copyright (c) 2008-2019, OPUS 4 development team + * @copyright Copyright (c) 2008-2021, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Config; + class Export_Model_PublistExportTest extends ControllerTestCase { @@ -47,15 +49,15 @@ public function testConstruction() public function testGetMimeTypes() { - $config = Zend_Registry::get('Zend_Config'); - - $config->merge( - new Zend_Config(['plugins' => ['export' => [ + $this->adjustConfiguration([ + 'plugins' => ['export' => [ 'publist' => [ 'file' => [ 'allow' => [ - 'mimetype' => ['application/xhtml+xml' => 'HTML']]]]]]]) - ); + 'mimetype' => ['application/xhtml+xml' => 'HTML']]]]]] + ]); + + $config = Config::get(); $plugin = new Export_Model_PublistExport('publist'); $plugin->setConfig($config->plugins->export->publist); diff --git a/tests/modules/export/models/XmlExportTest.php b/tests/modules/export/models/XmlExportTest.php index 3598960639..462752a8d6 100644 --- a/tests/modules/export/models/XmlExportTest.php +++ b/tests/modules/export/models/XmlExportTest.php @@ -1,4 +1,5 @@ - * @author Jens Schwidder - * @copyright Copyright (c) 2008-2019, OPUS 4 development team + * @copyright Copyright (c) 2008-2022, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Title; +use Opus\Db\DocumentXmlCache; + /** * Class Export_Model_XmlExportTest * @@ -40,7 +40,7 @@ class Export_Model_XmlExportTest extends ControllerTestCase { - protected $additionalResources = ['database', 'authz']; + protected $additionalResources = ['database']; /** * @var \Export_Model_XmlExport @@ -55,7 +55,7 @@ public function setUp() $plugin->setRequest($this->getRequest()); $plugin->setResponse($this->getResponse()); $plugin->init(); - $plugin->setConfig(new Zend_Config([ + $plugin->setConfig(new \Zend_Config([ 'class' => 'Export_Model_XmlExport', 'maxDocumentsGuest' => '100', 'maxDocumentsUser' => '500', @@ -68,7 +68,7 @@ public function testXmlPreparation() { $doc = $this->createTestDocument(); $doc->setServerState('published'); - $title = new Opus_Title(); + $title = new Title(); $title->setLanguage('deu'); $title->setValue('Deutscher Titel'); $doc->setTitleMain($title); @@ -91,7 +91,7 @@ public function testXmlPreparationForFrontdoor() { $doc = $this->createTestDocument(); $doc->setServerState('published'); - $title = new Opus_Title(); + $title = new Title(); $title->setLanguage('deu'); $title->setValue('Deutscher Titel'); $doc->setTitleMain($title); @@ -158,7 +158,7 @@ public function testXmlSortOrder() $thirdDocId = $thirdDoc->store(); // Dokument aus dem Cache löschen - $documentCacheTable = new Opus_Db_DocumentXmlCache(); + $documentCacheTable = new DocumentXmlCache(); $documentCacheTable->delete('document_id = ' . $secondDocId); $documentCacheTable->delete('document_id = ' . $firstDocId); @@ -273,9 +273,9 @@ public function testIsDownloadEnabled() $plugin->setDownloadEnabled(null); - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'export' => ['download' => self::CONFIG_VALUE_FALSE] - ])); + ]); $this->assertFalse($plugin->isDownloadEnabled()); } @@ -290,11 +290,11 @@ public function setDownloadEnabledInvalidArgumentProvider() } /** - * @expectedException InvalidArgumentException * @dataProvider setDownloadEnabledInvalidArgumentProvider */ public function testSetDownloadEnabledInvalidArgument($argument) { + $this->setExpectedException(InvalidArgumentException::class); $this->plugin->setDownloadEnabled($argument); } @@ -304,7 +304,7 @@ public function testGetContentTypeFromConfiguration() $this->assertEquals('text/xml', $plugin->getContentType()); - $config = new Zend_Config(['contentType' => 'text/plain']); + $config = new \Zend_Config(['contentType' => 'text/plain']); $plugin->setContentType(null); // clear cached content type @@ -319,7 +319,7 @@ public function testGetContentTypeFallback() $plugin->setContentType(null); - $plugin->setConfig(new Zend_Config([])); + $plugin->setConfig(new \Zend_Config([])); $this->assertEquals('text/xml', $plugin->getContentType()); } @@ -341,7 +341,7 @@ public function testGetAttachmentFilename() $plugin->setAttachmentFilename(null); // clear cached name - $plugin->setConfig(new Zend_Config(['attachmentFilename' => 'article.pdf'])); + $plugin->setConfig(new \Zend_Config(['attachmentFilename' => 'article.pdf'])); $this->assertEquals('article.pdf', $plugin->getAttachmentFilename()); } diff --git a/tests/modules/frontdoor/controllers/DeliverControllerTest.php b/tests/modules/frontdoor/controllers/DeliverControllerTest.php index d17f6b4dc8..03f3b332e9 100644 --- a/tests/modules/frontdoor/controllers/DeliverControllerTest.php +++ b/tests/modules/frontdoor/controllers/DeliverControllerTest.php @@ -1,4 +1,5 @@ - * @author Jens Schwidder - * @copyright Copyright (c) 2012-2019, OPUS 4 development team + * @copyright Copyright (c) 2012-2022, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ @@ -40,7 +37,7 @@ class Frontdoor_DeliverControllerTest extends ControllerTestCase { - protected $additionalResources = ['database', 'authz', 'view', 'mainMenu', 'translation']; + protected $additionalResources = ['database', 'view', 'mainMenu', 'translation']; public function setUp() { diff --git a/tests/modules/frontdoor/controllers/IndexControllerTest.php b/tests/modules/frontdoor/controllers/IndexControllerTest.php index 7d15cd9394..27ef568578 100644 --- a/tests/modules/frontdoor/controllers/IndexControllerTest.php +++ b/tests/modules/frontdoor/controllers/IndexControllerTest.php @@ -29,10 +29,19 @@ * @author Julian Heise * @author Michael Lang * @author Jens Schwidder - * @copyright Copyright (c) 2008-2019, OPUS 4 development team + * @copyright Copyright (c) 2008-2021, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Collection; +use Opus\CollectionRole; +use Opus\Config; +use Opus\Date; +use Opus\Document; +use Opus\Log; +use Opus\Note; +use Opus\Title; + /** * Class Frontdoor_IndexControllerTest. * @@ -46,7 +55,7 @@ class Frontdoor_IndexControllerTest extends ControllerTestCase /** * Document to count on :) * - * @var Opus_Document + * @var Document */ protected $_document = null; protected $_document_col = null; @@ -62,18 +71,18 @@ public function setUp() parent::setUpWithEnv('production'); $this->assertSecurityConfigured(); - $path = Zend_Registry::get('temp_dir') . '~localstat.xml'; + $path = Config::getInstance()->getTempPath() . '~localstat.xml'; @unlink($path); $this->_document = $this->createTestDocument(); $this->_document->setType("doctoral_thesis"); - $title = new Opus_Title(); + $title = new Title(); $title->setLanguage('deu'); $title->setValue('Titel'); $this->_document->addTitleMain($title); - $title = new Opus_Title(); + $title = new Title(); $title->setLanguage('eng'); $title->setValue('Title'); $this->_document->addTitleMain($title); @@ -87,13 +96,13 @@ public function setUp() // create collection test document $this->_document_col = $this->createTestDocument(); - $this->_document_col->addCollection(new Opus_Collection(40)); // invisible collection - $this->_document_col->addCollection(new Opus_Collection(16214)); // visible collection with invisible collection role - $this->_document_col->addCollection(new Opus_Collection(1031)); // visible collection with visible collection role + $this->_document_col->addCollection(new Collection(40)); // invisible collection + $this->_document_col->addCollection(new Collection(16214)); // visible collection with invisible collection role + $this->_document_col->addCollection(new Collection(1031)); // visible collection with visible collection role // collection role ID = 10 (sichbar) - $this->_document_col->addCollection(new Opus_Collection(16136)); // versteckte Collection (Role = 10) - $this->_document_col->addCollection(new Opus_Collection(15991)); // sichbare Collection (Role = 10); + $this->_document_col->addCollection(new Collection(16136)); // versteckte Collection (Role = 10) + $this->_document_col->addCollection(new Collection(15991)); // sichbare Collection (Role = 10); $this->_document_col->setServerState('published'); $this->_document_col->store(); } @@ -216,7 +225,7 @@ public function testFrontdoorTitleRespectsDocumentLanguageDeu() { $docId = $this->_document->getId(); - $doc = new Opus_Document($docId); + $doc = Document::get($docId); $doc->setLanguage('deu'); $doc->setServerState('published'); $doc->store(); @@ -234,7 +243,7 @@ public function testFrontdoorTitleRespectsDocumentLanguageEng() { $docId = $this->_document->getId(); - $doc = new Opus_Document($docId); + $doc = Document::get($docId); $doc->setLanguage('eng'); $doc->setServerState('published'); $doc->store(); @@ -256,7 +265,7 @@ public function testFrontdoorTitleRespectsDocumentLanguageWithoutCorrespondingTi { $docId = $this->_document->getId(); - $doc = new Opus_Document($docId); + $doc = Document::get($docId); $doc->setLanguage('fra'); $doc->setServerState('published'); $doc->store(); @@ -277,7 +286,7 @@ public function testFrontdoorTitleRespectsDocumentLanguageMultipleCandidates() { $docId = $this->_document->getId(); - $doc = new Opus_Document($docId); + $doc = Document::get($docId); $doc->setLanguage('deu'); $doc->setServerState('published'); $doc->addTitleMain()->setValue('Titel2')->setLanguage('deu'); @@ -295,7 +304,7 @@ public function testFrontdoorTitleRespectsDocumentLanguageMultipleCandidates() */ public function testIdentifierUrlIsHandledProperlyInFrontdoorForNonProtocolURL() { - $d = new Opus_Document('91'); + $d = Document::get('91'); $identifiers = $d->getIdentifierUrl(); $identifier = $identifiers[0]; $this->assertEquals('www.myexampledomain.de/myexamplepath', $identifier->getValue()); @@ -308,7 +317,7 @@ public function testIdentifierUrlIsHandledProperlyInFrontdoorForNonProtocolURL() */ public function testIdentifierUrlIsHandledProperlyInFrontdoorForProtocolURL() { - $d = new Opus_Document('92'); + $d = Document::get('92'); $identifiers = $d->getIdentifierUrl(); $identifier = $identifiers[0]; $this->assertEquals('http://www.myexampledomain.de/myexamplepath', $identifier->getValue()); @@ -321,7 +330,7 @@ public function testIdentifierUrlIsHandledProperlyInFrontdoorForProtocolURL() */ public function testUrlEscapedFileNameDoc1() { - $d = new Opus_Document(1); + $d = Document::get(1); $filePathnames = []; foreach ($d->getFile() as $file) { $filePathnames[] = $file->getPathName(); @@ -345,7 +354,7 @@ public function testUrlEscapedFileNameDoc1() */ public function testUrlEscapedFileNameDoc147() { - $d = new Opus_Document(147); + $d = Document::get(147); $filePathnames = []; foreach ($d->getFile() as $file) { $filePathnames[] = $file->getPathName(); @@ -380,9 +389,9 @@ public function testSubjectSortOrder() public function testSubjectSortOrderAlphabetical() { - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'frontdoor' => ['subjects' => ['alphabeticalSorting' => self::CONFIG_VALUE_TRUE]] - ])); + ]); // frontdoor.subjects.alphabeticalSorting @@ -398,7 +407,7 @@ public function testSubjectSortOrderAlphabetical() */ public function testSeries149InVisible() { - $d = new Opus_Document(149); + $d = Document::get(149); $seriesIds = []; $seriesNumbers = []; foreach ($d->getSeries() as $series) { @@ -429,7 +438,7 @@ public function testSeries149InVisible() */ public function testUrlEncodedAuthorNamesDoc150() { - $d = new Opus_Document(150); + $d = Document::get(150); $firstNames = []; $lastNames = []; @@ -455,12 +464,12 @@ public function testUrlEncodedAuthorNamesDoc150() */ public function testShowLinkForPrintOnDemandIfLicenceAppropriate() { - $podConfArray = ['printOnDemand' => [ - 'url' => 'http://localhost/', - 'button' => '' - ]]; - $podConfig = new Zend_Config($podConfArray); - Zend_Registry::getInstance()->get('Zend_Config')->merge($podConfig); + $this->adjustConfiguration([ + 'printOnDemand' => [ + 'url' => 'http://localhost/', + 'button' => '' + ] + ]); $this->dispatch('/frontdoor/index/index/docId/1'); $this->assertQuery('div#print-on-demand'); @@ -471,12 +480,12 @@ public function testShowLinkForPrintOnDemandIfLicenceAppropriate() */ public function testHideLinkForPrintOnDemandIfLicenceNotAppropriate() { - $podConfArray = ['printOnDemand' => [ - 'url' => 'http://localhost/', - 'button' => '' - ]]; - $podConfig = new Zend_Config($podConfArray); - Zend_Registry::getInstance()->get('Zend_Config')->merge($podConfig); + $this->adjustConfiguration([ + 'printOnDemand' => [ + 'url' => 'http://localhost/', + 'button' => '' + ] + ]); $this->dispatch('/frontdoor/index/index/docId/91'); $this->assertNotQuery('div#print-on-demand'); @@ -503,7 +512,7 @@ public function testDisplayAllUserDefinedCollectionRoles() public function testDisplayAllDocumentFields() { $this->dispatch('/frontdoor/index/index/docId/146'); - $translate = Zend_Registry::getInstance()->get('Zend_Translate'); + $translate = Application_Translate::getInstance(); $path = 'table.result-data.frontdoordata th.name'; @@ -578,7 +587,7 @@ public function testAbstractPreserveSpace() $doc->setLanguage("eng"); $doc->setServerState("published"); - $abstract = new Opus_Title(); + $abstract = new Title(); $abstract->setLanguage("eng"); $abstract->setValue("foo\nbar\n\nbaz"); $doc->addTitleAbstract($abstract); @@ -600,7 +609,7 @@ public function testNotePerserveSpace() $doc->setLanguage("eng"); $doc->setServerState("published"); - $note = new Opus_Note(); + $note = new Note(); $note->setMessage("foo\nbar\n\nbaz"); $note->setVisibility("public"); $doc->addNote($note); @@ -620,7 +629,7 @@ public function testNotePerserveSpace() */ public function testOPUSVIER2651NameNumber() { - $role = new Opus_CollectionRole(7); + $role = new CollectionRole(7); $displayFrontdoor = $role->getDisplayFrontdoor(); $role->setDisplayFrontdoor('Name,Number'); $role->store(); @@ -643,7 +652,7 @@ public function testOPUSVIER2651NameNumber() */ public function testOPUSVIER2651NumberName() { - $role = new Opus_CollectionRole(7); + $role = new CollectionRole(7); $displayFrontdoor = $role->getDisplayFrontdoor(); $role->setDisplayFrontdoor('Number,Name'); $role->store(); @@ -666,7 +675,7 @@ public function testOPUSVIER2651NumberName() */ public function testOPUSVIER2651Name() { - $role = new Opus_CollectionRole(7); + $role = new CollectionRole(7); $displayFrontdoor = $role->getDisplayFrontdoor(); $role->setDisplayFrontdoor('Name'); $role->store(); @@ -690,7 +699,7 @@ public function testOPUSVIER2651Name() */ public function testOPUSVIER2651Number() { - $role = new Opus_CollectionRole(7); + $role = new CollectionRole(7); $displayFrontdoor = $role->getDisplayFrontdoor(); $role->setDisplayFrontdoor('Number'); $role->store(); @@ -790,9 +799,9 @@ public function testValidateXHTML() public function testValidateXHTMLWithShortendAbstracts() { // Aktiviere Kürzung von Abstrakten - $config = Zend_Registry::get('Zend_Config')->merge(new Zend_Config( + $this->adjustConfiguration( ['frontdoor' => ['numOfShortAbstractChars' => '200']] - )); + ); $this->dispatch('/frontdoor/index/index/docId/92'); $this->assertResponseCode(200); @@ -932,7 +941,7 @@ public function testDateFormatEnglish() */ public function testFilesInCustomSortOrder() { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $config->frontdoor->files->customSorting = '1'; $this->dispatch('/frontdoor/index/index/docId/155'); @@ -951,7 +960,7 @@ public function testFilesInCustomSortOrder() */ public function testFilesInAlphabeticSortOrder() { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $config->frontdoor->files->customSorting = self::CONFIG_VALUE_FALSE; $this->dispatch('/frontdoor/index/index/docId/155'); @@ -975,12 +984,12 @@ public function testTitleSortOrderGermanFirst() $functions = ['addTitleMain', 'addTitleParent', 'addTitleSub', 'addTitleAdditional', 'addTitleAbstract']; foreach ($functions as $function) { $doc = $this->createTestDocument(); - $title = new Opus_Title(); + $title = new Title(); $title->setLanguage('deu'); $title->setValue('deutscher Titel'); $doc->$function($title); - $title = new Opus_Title(); + $title = new Title(); $title->setLanguage('eng'); $title->setValue('englischer Titel'); $doc->$function($title); @@ -1020,12 +1029,12 @@ public function testTitleSortOrderEnglishFirst() $functions = ['addTitleMain', 'addTitleParent', 'addTitleSub', 'addTitleAdditional', 'addTitleAbstract']; foreach ($functions as $function) { $doc = $this->createTestDocument(); - $title = new Opus_Title(); + $title = new Title(); $title->setLanguage('deu'); $title->setValue('deutscher Titel'); $doc->$function($title); - $title = new Opus_Title(); + $title = new Title(); $title->setLanguage('eng'); $title->setValue('englischer Titel'); $doc->$function($title); @@ -1194,7 +1203,7 @@ public function testEmbargoDatePassed() $doc->setServerState('published'); $doc->addFile($file); - $date = new Opus_Date(); + $date = new Date(); $date->setYear('2000')->setMonth('00')->setDay('01'); $doc->setEmbargoDate($date); @@ -1217,7 +1226,7 @@ public function testEmbargoDateHasNotPassed() $doc->setServerState('published'); $doc->addFile($file); - $date = new Opus_Date(); + $date = new Date(); $date->setYear('2100')->setMonth('00')->setDay('01'); $doc->setEmbargoDate($date); @@ -1314,8 +1323,7 @@ public function testXmlExportButtonPresentForAdmin() { $this->enableSecurity(); $this->loginUser('admin', 'adminadmin'); - $config = Zend_Registry::get('Zend_Config'); - $config->merge(new Zend_Config(['export' => ['stylesheet' => ['frontdoor' => 'example']]])); + $this->adjustConfiguration(['export' => ['stylesheet' => ['frontdoor' => 'example']]]); $this->dispatch('/frontdoor/index/index/docId/305'); $this->assertQuery( '//a[@href="/export/index/index/docId/305/export/xml/searchtype/id/stylesheet/example"]' @@ -1328,8 +1336,7 @@ public function testXmlExportButtonPresentForAdmin() public function testXmlExportNotButtonPresentForGuest() { $this->enableSecurity(); - $config = Zend_Registry::get('Zend_Config'); - $config->merge(new Zend_Config(['export' => ['stylesheet' => ['frontdoor' => 'example']]])); + $this->adjustConfiguration(['export' => ['stylesheet' => ['frontdoor' => 'example']]]); $this->dispatch('/frontdoor/index/index/docId/305'); $this->assertNotQuery('//a[@href="/frontdoor/index/index/docId/305/export/xml/stylesheet/example"]'); } @@ -1362,9 +1369,9 @@ public function testGoogleScholarLinkEnglish() public function testGoogleScholarOpenInNewWindowEnabled() { - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'googleScholar' => ['openInNewWindow' => self::CONFIG_VALUE_TRUE] - ])); + ]); $this->dispatch('/frontdoor/index/index/docId/146'); $this->assertResponseCode(200); $this->assertXpathCount('//a[contains(@href, "scholar.google.de") and @target = "_blank"]', 1); @@ -1373,9 +1380,9 @@ public function testGoogleScholarOpenInNewWindowEnabled() public function testGoogleScholarOpenInNewWindowDisabled() { - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'googleScholar' => ['openInNewWindow' => self::CONFIG_VALUE_FALSE] - ])); + ]); $this->dispatch('/frontdoor/index/index/docId/146'); $this->assertResponseCode(200); $this->assertXpathCount('//a[contains(@href, "scholar.google.de") and @target = "_blank"]', 0); @@ -1395,9 +1402,9 @@ public function testShowDocumentWithFileWithoutLanguage() public function testTwitterOpenInNewWindowEnabled() { - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'twitter' => ['openInNewWindow' => self::CONFIG_VALUE_TRUE] - ])); + ]); $this->dispatch('/frontdoor/index/index/docId/146'); $this->assertResponseCode(200); $this->assertXpathCount('//a[contains(@href, "twitter.com") and @target = "_blank"]', 1); @@ -1406,9 +1413,9 @@ public function testTwitterOpenInNewWindowEnabled() public function testTwitterOpenInNewWindowDisabled() { - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'twitter' => ['openInNewWindow' => self::CONFIG_VALUE_FALSE] - ])); + ]); $this->dispatch('/frontdoor/index/index/docId/146'); $this->assertResponseCode(200); $this->assertXpathCount('//a[contains(@href, "twitter.com") and @target = "_blank"]', 0); @@ -1419,10 +1426,10 @@ public function testUnableToTranslate() { $filter = new LogFilter(); - $logger = Zend_Registry::get('Zend_Log'); + $logger = Log::get(); $logger->addFilter($filter); - $this->assertEquals(7, Zend_Registry::get('LOG_LEVEL'), 'Log level should be 7 for test.'); + $this->assertEquals(7, $logger->getLevel(), 'Log level should be 7 for test.'); $this->dispatch('/frontdoor/index/index/docId/146'); @@ -1434,7 +1441,7 @@ public function testUnableToTranslate() } } - $output = Zend_Debug::dump($failedTranslations, null, false); + $output = \Zend_Debug::dump($failedTranslations, null, false); // until all messages can be prevented less than 20 is good enough $this->assertLessThanOrEqual(1, count($failedTranslations), $output); @@ -1446,7 +1453,7 @@ public function testMetaTagsForUrns() $this->assertResponseCode(200); - $urnResolverUrl = Zend_Registry::get('Zend_Config')->urn->resolverUrl; + $urnResolverUrl = $this->getConfig()->urn->resolverUrl; $this->assertXpath('//meta[@name="DC.identifier" and @content="urn:nbn:op:123"]'); $this->assertXpath('//meta[@name="DC.identifier" and @content="' . $urnResolverUrl . 'urn:nbn:op:123"]'); @@ -1455,9 +1462,9 @@ public function testMetaTagsForUrns() public function testBelongsToBibliographyTurnedOn() { $this->useEnglish(); - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'frontdoor' => ['metadata' => ['BelongsToBibliography' => self::CONFIG_VALUE_TRUE]] - ])); + ]); $this->dispatch('/frontdoor/index/index/docId/146'); @@ -1467,9 +1474,9 @@ public function testBelongsToBibliographyTurnedOn() public function testBelongsToBibliographyTurnedOff() { - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'frontdoor' => ['metadata' => ['BelongsToBibliography' => self::CONFIG_VALUE_FALSE]] - ])); + ]); $this->dispatch('/frontdoor/index/index/docId/146'); diff --git a/tests/modules/frontdoor/controllers/MailControllerTest.php b/tests/modules/frontdoor/controllers/MailControllerTest.php index afe52d65c6..9ef0dd7f00 100644 --- a/tests/modules/frontdoor/controllers/MailControllerTest.php +++ b/tests/modules/frontdoor/controllers/MailControllerTest.php @@ -31,6 +31,9 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Person; +use Opus\Title; + /** * Class Frontdoor_MailControllerTest. * @@ -53,7 +56,7 @@ public function setUp() $document->setServerState('published'); $document->setType('baz'); - $title = new Opus_Title(); + $title = new Title(); $title->setValue('foobartitle'); $title->setLanguage('deu'); $document->setTitleMain($title); @@ -65,12 +68,12 @@ public function setUp() $document->setServerState('published'); $document->setType('baz'); - $title = new Opus_Title(); + $title = new Title(); $title->setValue('foobartitle'); $title->setLanguage('deu'); $document->setTitleMain($title); - $author = new Opus_Person(); + $author = new Person(); $author->setFirstName('John'); $author->setLastName('Doe'); $author->setEmail('doe@example.org'); diff --git a/tests/modules/frontdoor/forms/AtLeastOneValidatorTest.php b/tests/modules/frontdoor/forms/AtLeastOneValidatorTest.php index 85d7313aac..04dee57290 100644 --- a/tests/modules/frontdoor/forms/AtLeastOneValidatorTest.php +++ b/tests/modules/frontdoor/forms/AtLeastOneValidatorTest.php @@ -37,8 +37,8 @@ public function testValidationSuccess() { $validator = new Frontdoor_Form_AtLeastOneValidator(); - $checkbox1 = new Zend_Form_Element_Checkbox('checkbox1'); - $checkbox2 = new Zend_Form_Element_Checkbox('checkbox2'); + $checkbox1 = new \Zend_Form_Element_Checkbox('checkbox1'); + $checkbox2 = new \Zend_Form_Element_Checkbox('checkbox2'); $validator->addField($checkbox1); $validator->addField($checkbox2); @@ -52,8 +52,8 @@ public function testValidationFailure() { $validator = new Frontdoor_Form_AtLeastOneValidator(); - $checkbox1 = new Zend_Form_Element_Checkbox('checkbox1'); - $checkbox2 = new Zend_Form_Element_Checkbox('checkbox2'); + $checkbox1 = new \Zend_Form_Element_Checkbox('checkbox1'); + $checkbox2 = new \Zend_Form_Element_Checkbox('checkbox2'); $validator->addField($checkbox1); $validator->addField($checkbox2); diff --git a/tests/modules/frontdoor/models/AuthorsTest.php b/tests/modules/frontdoor/models/AuthorsTest.php index d536669619..dddf3a564d 100644 --- a/tests/modules/frontdoor/models/AuthorsTest.php +++ b/tests/modules/frontdoor/models/AuthorsTest.php @@ -30,6 +30,11 @@ * @copyright Copyright (c) 2008-2019, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ + +use Opus\Document; +use Opus\Person; +use Opus\Title; + class Frontdoor_Model_AuthorsTest extends ControllerTestCase { @@ -50,12 +55,12 @@ public function setUp() $document->setType('testtype'); $document->setLanguage('deu'); - $title = new Opus_Title(); + $title = new Title(); $title->setValue('testtitle'); $title->setLanguage('deu'); $document->setTitleMain($title); - $author1 = new Opus_Person(); + $author1 = new Person(); $author1->setFirstName('John'); $author1->setLastName('Doe'); $author1->setEmail('doe@example.org'); @@ -64,7 +69,7 @@ public function setUp() $link_person1 = $document->addPersonAuthor($author1); $link_person1->setAllowEmailContact('1'); - $author2 = new Opus_Person(); + $author2 = new Person(); $author2->setFirstName('Jane'); $author2->setLastName('Doe'); $this->author2Id = $author2->store(); @@ -72,7 +77,7 @@ public function setUp() $link_person2 = $document->addPersonAuthor($author2); $link_person2->setAllowEmailContact('0'); - $author3 = new Opus_Person(); + $author3 = new Person(); $author3->setFirstName('Jimmy'); $author3->setLastName('Doe'); $this->author3Id = $author3->store(); @@ -80,7 +85,7 @@ public function setUp() $link_person3 = $document->addPersonAuthor($author3); $link_person3->setAllowEmailContact('1'); - $author4 = new Opus_Person(); + $author4 = new Person(); $author4->setFirstName('Foo'); $author4->setLastName('Bar'); $author4->setEmail('foo@bar.de'); @@ -197,7 +202,7 @@ public function testUnknownDocumentID() public function testPublishedDocument() { - $doc = new Opus_Document($this->documentId); + $doc = Document::get($this->documentId); $model = new Frontdoor_Model_Authors($doc); $this->assertNotNull($model); } @@ -205,7 +210,7 @@ public function testPublishedDocument() public function testUnpublishedDocument() { $this->markTestIncomplete('TODO: ensure that this method is called with guest privileges'); - $doc = new Opus_Document($this->unpublishedDocumentId); + $doc = Document::get($this->unpublishedDocumentId); $this->setExpectedException('Frontdoor_Model_Exception', 'access to requested document is forbidden'); new Frontdoor_Model_Authors($doc); } diff --git a/tests/modules/frontdoor/models/FileTest.php b/tests/modules/frontdoor/models/FileTest.php index cd5bcaa76b..f64d6798b0 100644 --- a/tests/modules/frontdoor/models/FileTest.php +++ b/tests/modules/frontdoor/models/FileTest.php @@ -1,4 +1,5 @@ - * @author Jens Schwidder - * @copyright Copyright (c) 2008-2019, OPUS 4 development team + * @copyright Copyright (c) 2008-2022, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ + +use Opus\Date; +use Opus\File; + class Frontdoor_Model_FileTest extends ControllerTestCase { - protected $additionalResources = ['database', 'authz']; + protected $additionalResources = ['database']; const FILENAME = 'test.xhtml'; const FILENAME_DELETED_DOC = 'foo.html'; @@ -55,37 +56,28 @@ public function testGetFileObjectSuccessfulCase() $this->assertEquals(self::FILENAME, $opusFile->getPathName()); } - /** - * @expectedException Frontdoor_Model_DocumentNotFoundException - * @expectedExceptionCode 404 - */ public function testGetFileObjectDocumentNotFoundException() { - $file = new Frontdoor_Model_File(99999999999, self::FILENAME); - $realm = new MockRealm(true, true); - $opusFile = $file->getFileObject($realm); + $this->setExpectedException(Frontdoor_Model_DocumentNotFoundException::class, null, 404); + new Frontdoor_Model_File(99999999999, self::FILENAME); } - /** - * @expectedException Frontdoor_Model_DocumentDeletedException - * @expectedExceptionCode 404 - */ public function testGetFileObjectDocumentDeletedExceptionIfDocForbidden() { $file = new Frontdoor_Model_File(123, self::FILENAME_DELETED_DOC); $realm = new MockRealm(true, false); - $opusFile = $file->getFileObject($realm); + + $this->setExpectedException(Frontdoor_Model_DocumentDeletedException::class, null, 404); + $file->getFileObject($realm); } - /** - * @expectedException Frontdoor_Model_FileAccessNotAllowedException - * @expectedExceptionCode 403 - */ public function testGetFileObjectFileAccessNotAllowedExceptionIfFileForbidden() { $file = new Frontdoor_Model_File(123, self::FILENAME_DELETED_DOC); $realm = new MockRealm(false, true); - $opusFile = $file->getFileObject($realm); + + $this->setExpectedException(Frontdoor_Model_FileAccessNotAllowedException::class, null, 403); + $file->getFileObject($realm); } public function testGetFileObjectNoDocumentDeletedExceptionIfAccessAllowed() @@ -94,7 +86,7 @@ public function testGetFileObjectNoDocumentDeletedExceptionIfAccessAllowed() $realm = new MockRealm(true, true); $opusFile = $file->getFileObject($realm); - $this->assertTrue($opusFile instanceof Opus_File); + $this->assertTrue($opusFile instanceof File); $this->assertEquals(self::FILENAME_DELETED_DOC, $opusFile->getPathName()); } @@ -104,48 +96,44 @@ public function testGetFileObjectAccessAllowedForUserWithAccessToDocumentsResour $file->setAclHelper(new MockAccessControl(true)); $realm = new MockRealm(false, false); // sollte egal sein $opusFile = $file->getFileObject($realm); - $this->assertTrue($opusFile instanceof Opus_File); + $this->assertTrue($opusFile instanceof File); } - /** - * @expectedException Frontdoor_Model_FileAccessNotAllowedException - */ public function testGetFileObjectAccessNotAllowedForUser() { $file = new Frontdoor_Model_File(92, self::FILENAME); $file->setAclHelper(new MockAccessControl(false)); $realm = new MockRealm(false, false); // sollte egal sein - $opusFile = $file->getFileObject($realm); + + $this->setExpectedException(Frontdoor_Model_FileAccessNotAllowedException::class); + $file->getFileObject($realm); } - /** - * @expectedException Frontdoor_Model_DocumentAccessNotAllowedException - */ public function testGetFileObjectDocumentAccessNotAllowedException() { $file = new Frontdoor_Model_File(124, self::FILENAME_UNPUBLISHED_DOC); $realm = new MockRealm(true, false); - $opusFile = $file->getFileObject($realm); + + $this->setExpectedException(Frontdoor_Model_DocumentAccessNotAllowedException::class); + $file->getFileObject($realm); } - /** - * @expectedException Frontdoor_Model_FileNotFoundException - */ public function testGetFileObjectFileNotFoundException() { $file = new Frontdoor_Model_File(92, 'this_file_does_not_exist.file'); $realm = new MockRealm(true, true); - $opusFile = $file->getFileObject($realm); + + $this->setExpectedException(Frontdoor_Model_FileNotFoundException::class); + $file->getFileObject($realm); } - /** - * @expectedException Frontdoor_Model_FileAccessNotAllowedException - */ public function testGetFileObjectFileAccessNotAllowedException() { $file = new Frontdoor_Model_File(92, self::FILENAME); $realm = new MockRealm(false, true); - $opusFile = $file->getFileObject($realm); + + $this->setExpectedException(Frontdoor_Model_FileAccessNotAllowedException::class); + $file->getFileObject($realm); } public function testConstructorDocIdEmpty() @@ -213,24 +201,22 @@ public function testConstructorFilenameHigherLevelDir() } } - /** - * @expectedException Frontdoor_Model_DocumentAccessNotAllowedException - */ public function testWrongTypeOfRealmNoDocAccess() { $file = new Frontdoor_Model_File(124, self::FILENAME_UNPUBLISHED_DOC); $realm = 'this is an invalid realm object'; - $opusFile = $file->getFileObject($realm); + + $this->setExpectedException(Frontdoor_Model_DocumentAccessNotAllowedException::class); + $file->getFileObject($realm); } - /** - * @expectedException Frontdoor_Model_FileAccessNotAllowedException - */ public function testWrongTypeOfRealmNoFileAccess() { $file = new Frontdoor_Model_File(92, self::FILENAME); $realm = 'this is an invalid realm object'; - $opusFile = $file->getFileObject($realm); + + $this->setExpectedException(Frontdoor_Model_FileAccessNotAllowedException::class); + $file->getFileObject($realm); } public function testGetAclHelper() @@ -263,8 +249,6 @@ public function testSetAclHelper() /** * Dateien, die nicht sichtbar sind in Frontdoor dürfen nicht heruntergeladen werden. - * - * @expectedException Frontdoor_Model_FileAccessNotAllowedException */ public function testFileAccessDeniedIfNotVisibleInFrontdoorForGuest() { @@ -272,11 +256,12 @@ public function testFileAccessDeniedIfNotVisibleInFrontdoorForGuest() $realm = new MockRealm(true, true); - $opusFile = new Opus_File(128); + $opusFile = new File(128); $this->assertEquals(0, $opusFile->getVisibleInFrontdoor(), "Testdaten geändert."); $this->assertEquals("frontdoor_invisible.txt", $opusFile->getPathName(), "Testdaten geändert."); + $this->setExpectedException(Frontdoor_Model_FileAccessNotAllowedException::class); $model->getFileObject($realm); } @@ -318,7 +303,6 @@ public function testFileAccessAllowedWhenNotVisibleInFrontdoorForAdmin() /** * Dateien dürfen nicht heruntergeladen werden, wenn das Embargo-Datum nicht vergangen ist. * Regressiontest for OPUSVIER-3313. - * @expectedException Frontdoor_Model_FileAccessNotAllowedException */ public function testAccessDeniedForEmbargoedDocument() { @@ -327,7 +311,7 @@ public function testAccessDeniedForEmbargoedDocument() $doc->setServerState('published'); $doc->addFile($file); - $date = new Opus_Date(); + $date = new Date(); $date->setYear('2100')->setMonth('00')->setDay('01'); $doc->setEmbargoDate($date); @@ -335,6 +319,8 @@ public function testAccessDeniedForEmbargoedDocument() $model = new Frontdoor_Model_File($docId, "test.pdf"); $realm = new MockRealm(true, true); + + $this->setExpectedException(Frontdoor_Model_FileAccessNotAllowedException::class); $model->getFileObject($realm); } @@ -350,7 +336,7 @@ public function testAccessForEmbargoedDocumentForDocumentsAdmin() $doc->setServerState('published'); $doc->addFile($file); - $date = new Opus_Date(); + $date = new Date(); $date->setYear('2100')->setMonth('00')->setDay('01'); $doc->setEmbargoDate($date); @@ -375,7 +361,7 @@ public function testAccessForEmbargoedDocumentForAdmin() $doc->setServerState('published'); $doc->addFile($file); - $date = new Opus_Date(); + $date = new Date(); $date->setYear('2100')->setMonth('00')->setDay('01'); $doc->setEmbargoDate($date); @@ -395,7 +381,7 @@ public function testGetFileObjectForUnpublishedFileForDocumentsAdmin() $doc->setServerState('unpublished'); $doc->addFile($file); - $date = new Opus_Date(); + $date = new Date(); $date->setYear('2100')->setMonth('00')->setDay('01'); $doc->setEmbargoDate($date); diff --git a/tests/modules/frontdoor/models/HtmlMetaTagsTest.php b/tests/modules/frontdoor/models/HtmlMetaTagsTest.php index 6fa7d1d110..a6de78e0e8 100644 --- a/tests/modules/frontdoor/models/HtmlMetaTagsTest.php +++ b/tests/modules/frontdoor/models/HtmlMetaTagsTest.php @@ -31,6 +31,17 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Date; +use Opus\DnbInstitute; +use Opus\Document; +use Opus\Identifier; +use Opus\Licence; +use Opus\Model\ModelException; +use Opus\Person; +use Opus\Subject; +use Opus\Title; +use Opus\TitleAbstract; + class Frontdoor_Model_HtmlMetaTagsTest extends ControllerTestCase { @@ -42,7 +53,7 @@ class Frontdoor_Model_HtmlMetaTagsTest extends ControllerTestCase private $htmlMetaTags; /** - * @var Opus_Date + * @var Date */ private $currDate; @@ -50,11 +61,11 @@ public function setUp() { parent::setUp(); $this->htmlMetaTags = new Frontdoor_Model_HtmlMetaTags( - Zend_Registry::get('Zend_Config'), + $this->getConfig(), 'http://localhost/opus' ); - $this->currDate = new Opus_Date(new Zend_Date()); + $this->currDate = new Date(new \Zend_Date()); } public function testCreateTagsForMinimalDocument() @@ -85,7 +96,7 @@ public function testCreateTagsForJournalPaper() public function testCreateTagsForCustomTypeJournalPaper() { - Zend_Registry::get('Zend_Config')->merge(new Zend_Config( + $this->htmlMetaTags->setConfig($this->adjustConfiguration( ['metatags' => ['mapping' => ['journal_paper' => ['customdoctype']]]] )); @@ -94,7 +105,7 @@ public function testCreateTagsForCustomTypeJournalPaper() } /** - * @param Opus_Document $doc + * @param Document $doc */ private function handleJournalPaper($doc) { @@ -116,7 +127,7 @@ public function testCreateTagsForConferencePaper() public function testCreateTagsForCustomTypeConferencePaper() { - Zend_Registry::get('Zend_Config')->merge(new Zend_Config( + $this->htmlMetaTags->setConfig($this->adjustConfiguration( ['metatags' => ['mapping' => ['conference_paper' => ['customdoctype']]]] )); @@ -125,7 +136,7 @@ public function testCreateTagsForCustomTypeConferencePaper() } /** - * @param Opus_Document $doc + * @param Document $doc */ private function handleConferencePaper($doc) { @@ -147,7 +158,7 @@ public function testCreateTagsForThesis() public function testCreateTagsForCustomTypeThesis() { - Zend_Registry::get('Zend_Config')->merge(new Zend_Config( + $this->htmlMetaTags->setConfig($this->adjustConfiguration( ['metatags' => ['mapping' => ['thesis' => ['customdoctype']]]] )); @@ -156,7 +167,7 @@ public function testCreateTagsForCustomTypeThesis() } /** - * @param Opus_Document $doc + * @param Document $doc */ private function handleThesis($doc) { @@ -176,7 +187,7 @@ public function testCreateTagsForWorkingPaper() public function testCreateTagsForCustomTypeWorkingPaper() { - Zend_Registry::get('Zend_Config')->merge(new Zend_Config( + $this->htmlMetaTags->setConfig($this->adjustConfiguration( ['metatags' => ['mapping' => ['working_paper' => ['customdoctype']]]] )); @@ -185,7 +196,7 @@ public function testCreateTagsForCustomTypeWorkingPaper() } /** - * @param Opus_Document $doc + * @param Document $doc */ private function handleWorkingPaper($doc) { @@ -209,7 +220,7 @@ public function testCreateTagsForWorkingPaperWithContributingCorporation() public function testCreateTagsForCustomTypeWorkingPaperWithContributingCorporation() { - Zend_Registry::get('Zend_Config')->merge(new Zend_Config( + $this->htmlMetaTags->setConfig($this->adjustConfiguration( ['metatags' => ['mapping' => ['working_paper' => ['customdoctype']]]] )); @@ -221,7 +232,7 @@ public function testCreateTagsForCustomTypeWorkingPaperWithContributingCorporati } /** - * @param Opus_Document $doc + * @param Document $doc */ private function handleWorkingPaperWithContributingCorporation($doc) { @@ -243,7 +254,7 @@ public function testCreateTagsForWorkingPaperWithPublisher() public function testCreateTagsForCustomTypeWorkingPaperWithPublisher() { - Zend_Registry::get('Zend_Config')->merge(new Zend_Config( + $this->htmlMetaTags->setConfig($this->adjustConfiguration( ['metatags' => ['mapping' => ['working_paper' => ['customdoctype']]]] )); @@ -256,7 +267,7 @@ public function testCreateTagsForCustomTypeWorkingPaperWithPublisher() } /** - * @param Opus_Document $doc + * @param Document $doc */ private function handleWorkingPaperWithPublisher($doc) { @@ -274,7 +285,7 @@ public function testCreateTagsForBook() public function testCreateTagsForCustomTypeBook() { - Zend_Registry::get('Zend_Config')->merge(new Zend_Config( + $this->htmlMetaTags->setConfig($this->adjustConfiguration( ['metatags' => ['mapping' => ['book' => ['customdoctype']]]] )); @@ -283,7 +294,7 @@ public function testCreateTagsForCustomTypeBook() } /** - * @param Opus_Document $doc + * @param Document $doc */ private function handleBook($doc) { @@ -302,7 +313,7 @@ public function testCreateTagsForBookPart() public function testCreateTagsForCustomTypeBookPart() { - Zend_Registry::get('Zend_Config')->merge(new Zend_Config( + $this->htmlMetaTags->setConfig($this->adjustConfiguration( ['metatags' => ['mapping' => ['book_part' => ['customdoctype']]]] )); @@ -311,7 +322,7 @@ public function testCreateTagsForCustomTypeBookPart() } /** - * @param Opus_Document $doc + * @param Document $doc */ private function handleBookPart($doc) { @@ -521,7 +532,7 @@ private function assertAbstract($tags) } /** - * @param tags $tags + * @param array $tags Tags */ private function assertLicenceLink($tags) { @@ -548,7 +559,7 @@ private function assertFile($tags, $docId) } /** - * @param Opus_Document $doc + * @param Document $doc * @param array $tags */ private function assertThesisPublisher($doc, $tags) @@ -578,7 +589,7 @@ private function assertInstitution($tags, $value) } /** - * @return Opus_Document + * @return Document */ private function createJournalPaper() { @@ -617,8 +628,8 @@ private function createOther() /** * @param string $docType - * @return Opus_Document - * @throws Opus_Model_Exception + * @return Document + * @throws ModelException */ private function createTestDoc($docType) { @@ -637,7 +648,7 @@ private function createTestDoc($docType) // hier bereits store aufrufen, weil wir die DocId für URN und DOI brauchen $docId = $doc->store(); - $doc = new Opus_Document($docId); + $doc = Document::get($docId); $this->addAuthors($doc, 3); $this->addTitles($doc); $this->addAbstracts($doc); @@ -648,18 +659,18 @@ private function createTestDoc($docType) $this->addLicence($doc); $doc->store(); - return new Opus_Document($docId); + return Document::get($docId); } /** - * @param Opus_Document $doc + * @param Document $doc * @param int $num */ private function addAuthors($doc, $num) { $authors = []; for ($i = 0; $i < $num; $i++) { - $author = new Opus_Person(); + $author = new Person(); $author->setLastName('lastName-' . $i); if ($i % 2 == 0) { // nur jeder zweite Autor bekommt einen Vornamen @@ -671,18 +682,18 @@ private function addAuthors($doc, $num) } /** - * @param Opus_Document $doc + * @param Document $doc */ private function addTitles($doc) { $titles = []; - $title = new Opus_Title(); + $title = new Title(); $title->setType('main'); $title->setLanguage('deu'); $title->setValue('titlemain-deu'); $titles[] = $title; - $title = new Opus_Title(); + $title = new Title(); $title->setType('main'); $title->setLanguage('eng'); $title->setValue('titlemain-eng'); @@ -692,7 +703,7 @@ private function addTitles($doc) $titles = []; - $title = new Opus_Title(); + $title = new Title(); $title->setType('sub'); $title->setLanguage('eng'); $title->setValue('titlesub-eng'); @@ -702,7 +713,7 @@ private function addTitles($doc) $titles = []; - $title = new Opus_Title(); + $title = new Title(); $title->setType('parent'); $title->setLanguage('deu'); $title->setValue('titleparent-eng'); @@ -712,19 +723,19 @@ private function addTitles($doc) } /** - * @param Opus_Document $doc + * @param Document $doc */ private function addAbstracts($doc) { $abstracts = []; - $abstr = new Opus_TitleAbstract(); + $abstr = new TitleAbstract(); $abstr->setType('abstract'); $abstr->setLanguage('deu'); $abstr->setValue('abstract1-deu'); $abstracts[] = $abstr; - $abstr = new Opus_TitleAbstract(); + $abstr = new TitleAbstract(); $abstr->setType('abstract'); $abstr->setLanguage('deu'); $abstr->setValue('abstract2-deu'); @@ -734,28 +745,28 @@ private function addAbstracts($doc) } /** - * @param Opus_Document $doc + * @param Document $doc */ private function addIdentifiers($doc) { $identifers = []; - $identifer = new Opus_Identifier(); + $identifer = new Identifier(); $identifer->setType('doi'); $identifer->setValue('doi' . $doc->getId()); $identifers[] = $identifer; - $identifer = new Opus_Identifier(); + $identifer = new Identifier(); $identifer->setType('urn'); $identifer->setValue('urn' . $doc->getId()); $identifers[] = $identifer; - $identifer = new Opus_Identifier(); + $identifer = new Identifier(); $identifer->setType('issn'); $identifer->setValue('issn'); $identifers[] = $identifer; - $identifer = new Opus_Identifier(); + $identifer = new Identifier(); $identifer->setType('isbn'); $identifer->setValue('isbn'); $identifers[] = $identifer; @@ -764,19 +775,19 @@ private function addIdentifiers($doc) } /** - * @param Opus_Document $doc + * @param Document $doc */ private function addSubjects($doc) { $subjects = []; - $subject = new Opus_Subject(); + $subject = new Subject(); $subject->setType('type1'); $subject->setValue('value1'); $subject->setLanguage('deu'); $subjects[] = $subject; - $subject = new Opus_Subject(); + $subject = new Subject(); $subject->setType('type2'); $subject->setValue('value2'); $subject->setLanguage('deu'); @@ -786,20 +797,20 @@ private function addSubjects($doc) } /** - * @param Opus_Document $doc + * @param Document $doc */ private function addLicence($doc) { - $licence = new Opus_Licence(3); + $licence = new Licence(3); $doc->setLicence($licence); } /** - * @param Opus_Document $doc + * @param Document $doc */ private function addFile($doc) { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $path = $config->workspacePath . DIRECTORY_SEPARATOR . uniqid(); mkdir($path, 0777, true); @@ -824,11 +835,11 @@ private function createFile($path, $fileName, $header) } /** - * @param Opus_Document $doc + * @param Document $doc */ private function addThesisPublisher($doc) { - $institute = new Opus_DnbInstitute(3); + $institute = new DnbInstitute(3); $doc->setThesisPublisher($institute); } @@ -836,7 +847,7 @@ public function testGetMetatagsType() { $metaTags = $this->htmlMetaTags; - $document = new Opus_Document(146); + $document = Document::get(146); $book = $this->createBook(); $metaTags->getMetatagsType($document); @@ -861,7 +872,7 @@ public function testGetMappingConfig() public function testGetMappingConfigCustomDocumentType() { - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->htmlMetaTags->setConfig($this->adjustConfiguration([ 'metatags' => ['mapping' => ['book' => ['mybooktype']]] ])); @@ -875,7 +886,7 @@ public function testGetMappingConfigCustomDocumentType() public function testGetMappingConfigDefaultOverride() { - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->htmlMetaTags->setConfig($this->adjustConfiguration([ 'metatags' => ['mapping' => ['book' => ['article']]] ])); diff --git a/tests/modules/home/controllers/IndexControllerTest.php b/tests/modules/home/controllers/IndexControllerTest.php index ce8ba4286e..cf35895d83 100644 --- a/tests/modules/home/controllers/IndexControllerTest.php +++ b/tests/modules/home/controllers/IndexControllerTest.php @@ -82,7 +82,7 @@ public function testHelpActionGerman() public function testHelpActionSeparate() { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $config->help->separate = self::CONFIG_VALUE_TRUE; $this->dispatch('/home/index/help'); $this->assertResponseCode(200); @@ -138,7 +138,7 @@ public function testNoticeAction() private function getDocsInSearchIndex($checkConsistency = true) { - $searcher = new Opus\Search\Util\Searcher(); + $searcher = Application_Search_SearcherFactory::getSearcher(); $query = new Opus\Search\Util\Query(); $query->setCatchAll("*:*"); $query->setRows(Opus\Search\Util\Query::MAX_ROWS); @@ -172,10 +172,10 @@ public function testStartPageContainsTotalNumOfDocs() $element = $document->getElementById('solrsearch-totalnumofdocs'); $numOfDocs = $element->firstChild->textContent; - $docFinder = new Opus_DocumentFinder(); + $docFinder = $this->getDocumentFinder(); $docFinder->setServerState('published'); - $numOfDbDocs = $docFinder->count(); + $numOfDbDocs = $docFinder->getCount(); $this->assertEquals($numOfDbDocs, $numOfDocs); // kurze Erklärung des Vorhabens: die Dokumentanzahl bei der Catch-All-Suche @@ -195,7 +195,7 @@ public function testStartPageContainsTotalNumOfDocs() array_push($idsIndex, $result->getId()); } - $idsDb = $docFinder->ids(); + $idsDb = $docFinder->getIds(); $idsIndexOnly = array_diff($idsIndex, $idsDb); $this->assertEquals(0, count($idsIndexOnly), 'Document IDs in search index, but not in database: ' @@ -251,7 +251,7 @@ public function testShowLanguageSelector() public function testHideLanguageSelector() { - Zend_Registry::get('Zend_Config')->supportedLanguages = 'de'; + $this->getConfig()->supportedLanguages = 'de'; $this->dispatch("/home"); $this->assertNotQuery('//ul#lang-switch'); } diff --git a/tests/modules/home/models/HelpFilesTest.php b/tests/modules/home/models/HelpFilesTest.php index 50fce62cf8..272c6e0ca1 100644 --- a/tests/modules/home/models/HelpFilesTest.php +++ b/tests/modules/home/models/HelpFilesTest.php @@ -62,11 +62,11 @@ public function testGetFiles() public function testGetFileContent() { - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'help' => [ 'useFiles' => true ] - ])); + ]); $content = $this->help->getContent('contact.de.txt'); @@ -90,11 +90,11 @@ public function testGetFileContentNull() public function testGetFileContentForAllFiles() { - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'help' => [ 'useFiles' => true ] - ])); + ]); $helpFiles = $this->help->getFiles(); diff --git a/tests/modules/oai/controllers/ContainerControllerTest.php b/tests/modules/oai/controllers/ContainerControllerTest.php index 9352149558..408fcf4905 100644 --- a/tests/modules/oai/controllers/ContainerControllerTest.php +++ b/tests/modules/oai/controllers/ContainerControllerTest.php @@ -31,6 +31,9 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\File; +use Opus\UserRole; + /** * Class Oai_ContainerControllerTest. * @@ -73,7 +76,7 @@ public function testRequestUnknownDocId() public function testRequestUnpublishedDoc() { - $r = Opus_UserRole::fetchByName('guest'); + $r = UserRole::fetchByName('guest'); $modules = $r->listAccessModules(); $addOaiModuleAccess = ! in_array('oai', $modules); @@ -83,9 +86,8 @@ public function testRequestUnpublishedDoc() } // enable security - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $config->security = self::CONFIG_VALUE_TRUE; - Zend_Registry::set('Zend_Config', $config); $doc = $this->createTestDocument(); $doc->setServerState('unpublished'); @@ -115,7 +117,7 @@ public function testRequestPublishedDocWithoutAssociatedFiles() public function testRequestPublishedDocWithInaccessibleFile() { // create test file test.pdf in file system - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $path = $config->workspacePath . DIRECTORY_SEPARATOR . uniqid(); mkdir($path, 0777, true); $filepath = $path . DIRECTORY_SEPARATOR . 'test.pdf'; @@ -124,7 +126,7 @@ public function testRequestPublishedDocWithInaccessibleFile() $doc = $this->createTestDocument(); $doc->setServerState('published'); - $file = new Opus_File(); + $file = new File(); $file->setVisibleInOai(false); $file->setPathName('test.pdf'); $file->setTempFile($filepath); @@ -135,7 +137,7 @@ public function testRequestPublishedDocWithInaccessibleFile() // cleanup $file->delete(); - Opus_Util_File::deleteDirectory($path); + \Opus\Util\File::deleteDirectory($path); $this->assertResponseCode(500); $this->assertContains( @@ -152,7 +154,7 @@ public function testRequestPublishedDocWithAccessibleFile() ); // create test file test.pdf in file system - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $path = $config->workspacePath . DIRECTORY_SEPARATOR . uniqid(); mkdir($path, 0777, true); $filepath = $path . DIRECTORY_SEPARATOR . 'test.pdf'; @@ -161,7 +163,7 @@ public function testRequestPublishedDocWithAccessibleFile() $doc = $this->createTestDocument(); $doc->setServerState('published'); - $file = new Opus_File(); + $file = new File(); $file->setVisibleInOai(true); $file->setPathName('test.pdf'); $file->setTempFile($filepath); @@ -172,7 +174,7 @@ public function testRequestPublishedDocWithAccessibleFile() // cleanup $file->delete(); - Opus_Util_File::deleteDirectory($path); + \Opus\Util\File::deleteDirectory($path); $this->assertResponseCode(200); } diff --git a/tests/modules/oai/controllers/IndexControllerTest.php b/tests/modules/oai/controllers/IndexControllerTest.php index a43fdab03f..9c8bb6d956 100644 --- a/tests/modules/oai/controllers/IndexControllerTest.php +++ b/tests/modules/oai/controllers/IndexControllerTest.php @@ -31,7 +31,22 @@ * @author Jens Schwidder * @copyright Copyright (c) 2008-2019, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * + */ + +use Opus\Collection; +use Opus\CollectionRole; +use Opus\DnbInstitute; +use Opus\Document; +use Opus\Enrichment; +use Opus\File; +use Opus\Identifier; +use Opus\Licence; +use Opus\Person; +use Opus\Series; +use Opus\TitleAbstract; +use Opus\UserRole; + +/** * TODO split specific protocol tests into separate classes * TODO unit tests transformations directly without "dispatch" * TODO create plugins for formats/protocols/standards @@ -133,9 +148,9 @@ public function testNoVerb() */ public function testIdentify() { - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'oai' => ['repository' => ['name' => 'test-repo-name']] - ])); + ]); $this->dispatch('/oai?verb=Identify'); $this->assertResponseCode(200); @@ -192,9 +207,9 @@ public function testIdentifyDescriptionEprintsConfigured() 'comment' => ['url' => 'test-comment-url', 'text' => 'test-comment-text'] ]; - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'oai' => ['description' => ['eprints' => $values]] - ])); + ]); $this->dispatch('/oai?verb=Identify'); $this->assertResponseCode(200); @@ -218,10 +233,10 @@ public function testIdentifyDescriptionEprintsConfigured() public function testIdentifyDescriptionOaiIdentifier() { - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'oai' => ['repository' => ['identifier' => 'test-repo-identifier'], 'sample' => ['identifier' => 'test-sample-identifier']] - ])); + ]); $this->dispatch('/oai?verb=Identify'); $this->assertResponseCode(200); @@ -358,20 +373,6 @@ public function testGetRecordsFormats() } } - /** - * Test verb=GetRecord, prefix=oai_dc. - * - * @covers ::indexAction - */ - public function testGetRecordOaiDc() - { - $this->dispatch('/oai?verb=GetRecord&metadataPrefix=oai_dc&identifier=oai::35'); - $this->assertResponseCode(200); - - $response = $this->getResponse(); - $this->checkForBadStringsInHtml($response->getBody()); - } - /** * Test verb=GetRecord, prefix=XMetaDissPlus. * @@ -623,7 +624,7 @@ public function testGetRecordXMetaDissPlusDoc91CheckThesisYearAccepted() */ public function testGetRecordXMetaDissPlusDoc146SubjectDDC() { - $doc = new Opus_Document(146); + $doc = Document::get(146); $ddcs = []; foreach ($doc->getCollection() as $c) { if ($c->getRoleName() == 'ddc') { @@ -723,7 +724,7 @@ public function testGetRecordXMetaDissPlusDoc1DdbIdentifier() */ public function testGetRecordXMetaDissPlusDoc132EmptyThesisGrantor() { - $doc = new Opus_Document(132); + $doc = Document::get(132); $this->assertEquals( 'doctoralthesis', $doc->getType(), @@ -758,7 +759,7 @@ public function testGetRecordXMetaDissPlusDoc132EmptyThesisGrantor() */ public function testGetRecordXMetaDissPlusDoc132EmptyThesisPublisher() { - $doc = new Opus_Document(132); + $doc = Document::get(132); $this->assertEquals( 'doctoralthesis', $doc->getType(), @@ -793,7 +794,7 @@ public function testGetRecordXMetaDissPlusDoc132EmptyThesisPublisher() */ public function testGetRecordXMetaDissPlusDoc93() { - $doc = new Opus_Document(93); + $doc = Document::get(93); $this->assertEquals( 'doctoralthesis', $doc->getType(), @@ -834,7 +835,7 @@ public function testGetRecordXMetaDissPlusDoc93() */ public function testGetRecordXMetaDissPlusDoc146ThesisAndDdb() { - $doc = new Opus_Document(146); + $doc = Document::get(146); $this->assertEquals( 'masterthesis', $doc->getType(), @@ -906,228 +907,6 @@ public function testThesisLevelForXMetaDissPlus() } } - /** - * Regression test for OPUSVIER-2379 - * - * @covers ::indexAction - */ - public function testGetRecordOaiDcDoc91DocType() - { - $doc = new Opus_Document(91); - $this->assertEquals("report", $doc->getType(), "testdata changed"); - - $this->dispatch('/oai?verb=GetRecord&metadataPrefix=oai_dc&identifier=oai::91'); - $this->assertResponseCode(200); - - $response = $this->getResponse(); - $badStrings = ["Exception", "Error", "Stacktrace", "badVerb"]; - $this->checkForCustomBadStringsInHtml($response->getBody(), $badStrings); - - $xpath = $this->prepareXpathFromResultString($response->getBody()); - - // Regression test for OPUSVIER-2379 (show doc-type:report) - $elements = $xpath->query('//oai_dc:dc/dc:type[text()="doc-type:report"]'); - $this->assertEquals( - 1, - $elements->length, - "Unexpected count for doc-type:report" - ); - } - - /** - * Regression tests on document 146 - * - * @covers ::indexAction - */ - public function testGetRecordOaiDcDoc146() - { - $this->dispatch('/oai?verb=GetRecord&metadataPrefix=oai_dc&identifier=oai::146'); - $this->assertResponseCode(200); - - $response = $this->getResponse(); - $badStrings = ["Exception", "Error", "Stacktrace", "badVerb"]; - $this->checkForCustomBadStringsInHtml($response->getBody(), $badStrings); - - $xpath = $this->prepareXpathFromResultString($response->getBody()); - - // Regression test for OPUSVIER-2393 (show dc:contributor) - $elements = $xpath->query('//oai_dc:dc/dc:contributor/text()'); - $this->assertGreaterThanOrEqual(2, $elements->length, 'dc:contributor count changed'); - $this->assertEquals('Doe, Jane (PhD)', $elements->item(0)->nodeValue, 'dc:contributor field changed'); - $this->assertEquals('Baz University', $elements->item(1)->nodeValue, 'dc:contributor field changed'); - - // Regression test for OPUSVIER-2393 (show dc:identifier) - $urnResolverUrl = Zend_Registry::get('Zend_Config')->urn->resolverUrl; - $elements = $xpath->query('//oai_dc:dc/dc:identifier[text()="' . $urnResolverUrl . 'urn:nbn:op:123"]'); - $this->assertEquals(1, $elements->length, 'dc:identifier URN count changed'); - - $elements = $xpath->query('//oai_dc:dc/dc:identifier[text()="123"]'); - $this->assertGreaterThanOrEqual(1, $elements->length, 'dc:identifier URN count changed'); - } - - /** - * Regression tests on document 91 - * @covers ::indexAction - */ - public function testGetRecordOaiDcDoc91() - { - $this->dispatch('/oai?verb=GetRecord&metadataPrefix=oai_dc&identifier=oai::91'); - $this->assertResponseCode(200); - - $response = $this->getResponse(); - $badStrings = ["Exception", "Error", "Stacktrace", "badVerb"]; - $this->checkForCustomBadStringsInHtml($response->getBody(), $badStrings); - - $xpath = $this->prepareXpathFromResultString($response->getBody()); - - // Regression test for OPUSVIER-2393 (show dc:identifier) - $elements = $xpath->query('//oai_dc:dc/dc:identifier/text()'); - - $foundIds = []; - foreach ($elements as $element) { - $nodeValue = $element->nodeValue; - if (strstr($nodeValue, '/files/')) { - $foundIds[] = preg_replace("/^.*(\/files\/\d+\/.*)$/", "$1", $element->nodeValue); - } - } - - $this->assertContains("/files/91/test.pdf", $foundIds); - $this->assertContains("/files/91/test.txt", $foundIds); - $this->assertContains("/files/91/frontdoor_invisible.txt", $foundIds); - - // Regression test for OPUSVIER-2393 (show dc:creator) - $elements = $xpath->query('//oai_dc:dc/dc:creator/text()'); - $this->assertEquals(3, $elements->length, 'dc:creator count changed'); - $this->assertEquals('Doe, John', $elements->item(0)->nodeValue, 'dc:creator field changed'); - $this->assertEquals('Zufall, Rainer', $elements->item(1)->nodeValue, 'dc:creator field changed'); - $this->assertEquals('Fall, Klara', $elements->item(2)->nodeValue, 'dc:creator field changed'); - } - - /** - * Regression test for OPUSVIER-2380 and OPUSVIER-2378 - * @covers ::indexAction - */ - public function testGetRecordOaiDcDoc10SubjectDdcAndDate() - { - $doc = new Opus_Document(10); - $ddcs = []; - foreach ($doc->getCollection() as $c) { - if ($c->getRoleName() == 'ddc') { - $ddcs[] = $c->getNumber(); - } - } - $this->assertContains("004", $ddcs, "testdata changed"); - - $this->dispatch('/oai?verb=GetRecord&metadataPrefix=oai_dc&identifier=oai::10'); - $this->assertResponseCode(200); - - $response = $this->getResponse(); - $badStrings = ["Exception", "Error", "Stacktrace", "badVerb"]; - $this->checkForCustomBadStringsInHtml($response->getBody(), $badStrings); - - $xpath = $this->prepareXpathFromResultString($response->getBody()); - - // Regression test for OPUSVIER-2380 (show ddc:) - $elements = $xpath->query('//oai_dc:dc/dc:subject[text()="ddc:004"]'); - $this->assertEquals( - 1, - $elements->length, - "Unexpected count for ddc:004" - ); - - // Regression test for OPUSVIER-2378 (show ) - $elements = $xpath->query('//oai_dc:dc/dc:date'); - $this->assertEquals( - 1, - $elements->length, - "Unexpected count for dc:date" - ); - - // Regression test for OPUSVIER-2378 (show 2003) - $elements = $xpath->query('//oai_dc:dc/dc:date[text()="2003"]'); - $this->assertEquals( - 1, - $elements->length, - "Unexpected count for dc:date" - ); - } - - /** - * Regression test for OPUSVIER-2378 - * @covers ::indexAction - */ - public function testGetRecordOaiDcDoc114DcDate() - { - $doc = new Opus_Document(114); - $completedDate = $doc->getCompletedDate(); - $this->assertEquals("2011-04-19", "$completedDate", "testdata changed"); - - $this->dispatch('/oai?verb=GetRecord&metadataPrefix=oai_dc&identifier=oai::114'); - $this->assertResponseCode(200); - - $response = $this->getResponse(); - $badStrings = ["Exception", "Error", "Stacktrace", "badVerb"]; - $this->checkForCustomBadStringsInHtml($response->getBody(), $badStrings); - - $xpath = $this->prepareXpathFromResultString($response->getBody()); - - // Regression test for OPUSVIER-2378 (show ) - $elements = $xpath->query('//oai_dc:dc/dc:date'); - $this->assertEquals( - 1, - $elements->length, - "Unexpected count for dc:date" - ); - - // Regression test for OPUSVIER-2378 (show 2011-04-19) - $elements = $xpath->query('//oai_dc:dc/dc:date[text()="2011-04-19"]'); - $this->assertEquals( - 1, - $elements->length, - "Unexpected count for dc:date" - ); - } - - /** - * Regression test for OPUSVIER-2454 - * @covers ::indexAction - */ - public function testGetRecordOaiDcDoc1ByIdentifierPrefixOai() - { - $this->dispatch('/oai?verb=GetRecord&metadataPrefix=oai_dc&identifier=oai::1'); - $this->assertResponseCode(200); - - $response = $this->getResponse(); - $badStrings = ["Exception", "Error", "Stacktrace", "badVerb"]; - $this->checkForCustomBadStringsInHtml($response->getBody(), $badStrings); - - $xpath = $this->prepareXpathFromResultString($response->getBody()); - - // Regression test for OPUSVIER-2454 (check returned dc:identifier) - $elements = $xpath->query('//oai_dc:dc/dc:identifier[text()="urn:nbn:de:gbv:830-opus-225"]'); - $this->assertEquals(1, $elements->length, "Expected URN not found"); - } - - /** - * Regression test for OPUSVIER-2454 - * @covers ::indexAction - */ - public function testGetRecordOaiDcDoc1ByIdentifierPrefixUrn() - { - $this->dispatch('/oai?verb=GetRecord&metadataPrefix=oai_dc&identifier=urn:nbn:de:gbv:830-opus-225'); - $this->assertResponseCode(200); - - $response = $this->getResponse(); - $badStrings = ["Exception", "Error", "Stacktrace", "badVerb"]; - $this->checkForCustomBadStringsInHtml($response->getBody(), $badStrings); - - $xpath = $this->prepareXpathFromResultString($response->getBody()); - - // Regression test for OPUSVIER-2454 (check returned dc:identifier) - $elements = $xpath->query('//oai_dc:dc/dc:identifier[text()="urn:nbn:de:gbv:830-opus-225"]'); - $this->assertEquals(1, $elements->length, "Expected URN not found"); - } - /** * Regression test for OPUSVIER-2535 * @covers ::indexAction @@ -1206,16 +985,15 @@ public function testListRecords() */ public function testListRecordsXMetaDissPlusDocumentsWithFilesOnly() { - Zend_Registry::get('Zend_Config')->merge( - new Zend_Config([ - 'oai' => [ - 'max' => [ - 'listrecords' => '100', - 'listidentifiers' => '200', - ] + $this->adjustConfiguration([ + 'oai' => [ + 'max' => [ + 'listrecords' => '100', + 'listidentifiers' => '200', ] - ]) - ); + ] + ]); + $this->dispatch('/oai?verb=ListRecords&metadataPrefix=xMetaDissPlus'); $responseBody = $this->getResponse()->getBody(); @@ -1232,16 +1010,15 @@ public function testListRecordsXMetaDissPlusDocumentsWithFilesOnly() */ public function testListRecordsXMetaDissPlusDocumentsWithoutUrn() { - Zend_Registry::get('Zend_Config')->merge( - new Zend_Config([ - 'oai' => [ - 'max' => [ - 'listrecords' => '100', - 'listidentifiers' => '200', - ] + $this->adjustConfiguration([ + 'oai' => [ + 'max' => [ + 'listrecords' => '100', + 'listidentifiers' => '200', ] - ]) - ); + ] + ]); + $this->dispatch('/oai?verb=ListRecords&metadataPrefix=xMetaDissPlus'); $xpath = $this->prepareXpathFromResultString($this->getResponse()->getBody()); @@ -1330,7 +1107,7 @@ public function testTransferUrlIsPresent() { $doc = $this->createTestDocument(); $doc->setServerState('published'); - $file = new Opus_File(); + $file = new File(); $file->setVisibleInOai(true); $file->setPathName('foobar.pdf'); $doc->addFile($file); @@ -1366,7 +1143,7 @@ public function testGetRecordEpicurUrlEncoding() { $expectedFileNames = ["'many' - spaces and quotes.pdf", 'special-chars-%-"-#-&.pdf']; - $doc = new Opus_Document(147); + $doc = Document::get(147); $fileNames = array_map(function ($f) { return $f->getPathName(); }, $doc->getFile()); @@ -1408,12 +1185,12 @@ public function testDifferentFilesVisibilityOfOneDoc() $d = $this->createTestDocument(); $d->setServerState('published'); - $f1 = new Opus_File(); + $f1 = new File(); $f1->setPathName('foo.pdf'); $f1->setVisibleInOai(false); $d->addFile($f1); - $f2 = new Opus_File(); + $f2 = new File(); $f2->setPathName('bar.pdf'); $f2->setVisibleInOai(false); $d->addFile($f2); @@ -1475,7 +1252,7 @@ public function testRequestForMetadataPrefixCopyxmlAndVerbListIdentifiersIsDenie public function enableSecurity() { - $r = Opus_UserRole::fetchByName('guest'); + $r = UserRole::fetchByName('guest'); $modules = $r->listAccessModules(); $this->_addOaiModuleAccess = ! in_array('oai', $modules); @@ -1485,7 +1262,7 @@ public function enableSecurity() } // enable security - Zend_Registry::get('Zend_Config')->merge(new Zend_Config(['security' => self::CONFIG_VALUE_TRUE])); + $this->adjustConfiguration(['security' => self::CONFIG_VALUE_TRUE]); } /** @@ -1497,7 +1274,7 @@ public function testDdbFileNumberForSingleDocumentAndSingleFile() { $doc = $this->createTestDocument(); $doc->setServerState('published'); - $file = new Opus_File(); + $file = new File(); $file->setVisibleInOai(true); $file->setPathName('foobar.pdf'); $doc->addFile($file); @@ -1522,11 +1299,11 @@ public function testDdbFileNumberForSingleDocumentAndMultipleFiles() { $doc = $this->createTestDocument(); $doc->setServerState('published'); - $file = new Opus_File(); + $file = new File(); $file->setVisibleInOai(true); $file->setPathName('foo.pdf'); $doc->addFile($file); - $file = new Opus_File(); + $file = new File(); $file->setVisibleInOai(true); $file->setPathName('bar.pdf'); $doc->addFile($file); @@ -1549,15 +1326,15 @@ public function testDdbFileNumberForSingleDocumentAndMultipleFiles() */ public function testDdbFileNumberForMultipleDocumentsForXMetaDissPlus() { - $collection = new Opus_Collection(112); + $collection = new Collection(112); $doc1 = $this->createTestDocument(); $doc1->setServerState('published'); - $file = new Opus_File(); + $file = new File(); $file->setVisibleInOai(true); $file->setPathName('foo.pdf'); $doc1->addFile($file); - $file = new Opus_File(); + $file = new File(); $file->setVisibleInOai(true); $file->setPathName('bar.pdf'); $doc1->addFile($file); @@ -1566,7 +1343,7 @@ public function testDdbFileNumberForMultipleDocumentsForXMetaDissPlus() $doc2 = $this->createTestDocument(); $doc2->setServerState('published'); - $file = new Opus_File(); + $file = new File(); $file->setVisibleInOai(true); $file->setPathName('baz.pdf'); $doc2->addFile($file); @@ -1588,15 +1365,15 @@ public function testDdbFileNumberForMultipleDocumentsForXMetaDissPlus() */ public function testTransferUrlIsIOnlyGivenForDocsWithFulltext() { - $collection = new Opus_Collection(112); + $collection = new Collection(112); $doc1 = $this->createTestDocument(); $doc1->setServerState('published'); - $file = new Opus_File(); + $file = new File(); $file->setVisibleInOai(true); $file->setPathName('foo.pdf'); $doc1->addFile($file); - $file = new Opus_File(); + $file = new File(); $file->setVisibleInOai(true); $file->setPathName('bar.pdf'); $doc1->addFile($file); @@ -1605,7 +1382,7 @@ public function testTransferUrlIsIOnlyGivenForDocsWithFulltext() $doc2 = $this->createTestDocument(); $doc2->setServerState('published'); - $file = new Opus_File(); + $file = new File(); $file->setVisibleInOai(true); $file->setPathName('baz.pdf'); $doc2->addFile($file); @@ -1648,14 +1425,14 @@ public function testTransferUrlIsIOnlyGivenForDocsWithFulltext() */ public function testForDDCSubjectTypeForXMetaDissPlus() { - $collection = new Opus_Collection(112); + $collection = new Collection(112); $doc = $this->createTestDocument(); $doc->setServerState('published'); $doc->addCollection($collection); // fixing test for OPUSVIER-3142 - $visibleFile = new Opus_File(); + $visibleFile = new File(); $visibleFile->setPathName('visible_file.txt'); $visibleFile->setVisibleInOai(true); $doc->addFile($visibleFile); @@ -1676,7 +1453,7 @@ public function testForDDCSubjectTypeForXMetaDissPlus() */ public function testForInvalidSetSpecsInListRecords() { - $collectionRole = Opus_CollectionRole::fetchByOaiName('pacs'); + $collectionRole = CollectionRole::fetchByOaiName('pacs'); $this->assertNotNull($collectionRole); $this->assertContains(79, $collectionRole->getDocumentIdsInSet('pacs:07.75.+h')); @@ -1699,7 +1476,7 @@ public function testForInvalidSetSpecsInListRecords() */ public function testForInvalidSetSpecsInListIdentifiers() { - $collectionRole = Opus_CollectionRole::fetchByOaiName('pacs'); + $collectionRole = CollectionRole::fetchByOaiName('pacs'); $this->assertNotNull($collectionRole); $this->assertContains(79, $collectionRole->getDocumentIdsInSet('pacs:07.75.+h')); @@ -1722,7 +1499,7 @@ public function testForInvalidSetSpecsInListIdentifiers() */ public function testForInvalidSetSpecsInGetRecord79() { - $collectionRole = Opus_CollectionRole::fetchByOaiName('pacs'); + $collectionRole = CollectionRole::fetchByOaiName('pacs'); $this->assertNotNull($collectionRole); $this->assertContains(79, $collectionRole->getDocumentIdsInSet('pacs:07.75.+h')); @@ -1774,28 +1551,28 @@ public function testXMetaDissPlusUsePersonEnteredUnderGivenNameIfSurnameIsEmpty( $document = $this->createTestDocument(); $document->setServerState('published'); - $author = new Opus_Person(); + $author = new Person(); $author->setLastName('Foo'); $author->setDateOfBirth('1900-01-01'); $author->setPlaceOfBirth('Berlin'); // $authorId = $author->store(); $document->addPersonAuthor($author); - $advisor = new Opus_Person(); + $advisor = new Person(); $advisor->setLastName('Bar'); $advisor->setDateOfBirth('1900-01-01'); $advisor->setPlaceOfBirth('Berlin'); // $advisorId = $advisor->store(); $document->addPersonAdvisor($advisor); - $referee = new Opus_Person(); + $referee = new Person(); $referee->setLastName('Baz'); $referee->setDateOfBirth('1900-01-01'); $referee->setPlaceOfBirth('Berlin'); // $refereeId = $referee->store(); $document->addPersonReferee($referee); - $editor = new Opus_Person(); + $editor = new Person(); $editor->setLastName('TestEditor'); $document->addPersonEditor($editor); @@ -1916,9 +1693,7 @@ public function testListRecordsWithResumptionToken() { $max_records = '2'; - Zend_Registry::get('Zend_Config')->merge( - new Zend_Config(['oai' => ['max' => ['listrecords' => $max_records]]]) - ); + $this->adjustConfiguration(['oai' => ['max' => ['listrecords' => $max_records]]]); // first request: fetch documents list and expect resumption code $this->dispatch("/oai?verb=ListRecords&metadataPrefix=oai_dc"); @@ -1962,9 +1737,7 @@ public function testListRecordsWithEmptyResumptionTokenForLastBlock() { $max_records = '100'; - Zend_Registry::get('Zend_Config')->merge( - new Zend_Config(['oai' => ['max' => ['listrecords' => $max_records]]]) - ); + $this->adjustConfiguration(['oai' => ['max' => ['listrecords' => $max_records]]]); // first request: fetch documents list and expect resumption code $this->dispatch("/oai?verb=ListRecords&metadataPrefix=oai_dc"); @@ -2112,7 +1885,7 @@ public function testHabilitationIsDcTypeDoctoralthesis() */ public function testXMetaDissPlusDcsourceContainsTitleParent() { - $doc = new Opus_Document(146); + $doc = Document::get(146); $parentTitle = $doc->getTitleParent(); $this->assertFalse(empty($parentTitle), 'Test Data modified: Expected TitleParent'); @@ -2179,7 +1952,7 @@ public function testXMetaDissPlusDcsourceContainsTitleParentPageNumber() */ public function testXMetaDissPlusDctermsispartofContainsSeriesTitleAndNumber() { - $doc = new Opus_Document(146); + $doc = Document::get(146); $series = $doc->getSeries(); $this->dispatch('/oai?verb=GetRecord&metadataPrefix=XMetaDissPlus&identifier=oai::146'); @@ -2287,17 +2060,17 @@ public function testListRecordsForOpenAireRelation() $doc = $this->createTestDocument(); $doc->setServerState('published'); - $relation = new Opus_Enrichment(); + $relation = new Enrichment(); $relation->setKeyName('Relation'); $relation->setValue('test-1234'); $doc->addEnrichment($relation); - $relation = new Opus_Enrichment(); + $relation = new Enrichment(); $relation->setKeyName('Relation'); $relation->setValue('info:eu-repo/grantAgreement/EC/FP7/1234withPrefix'); $doc->addEnrichment($relation); - $role = Opus_CollectionRole::fetchByName('openaire'); + $role = CollectionRole::fetchByName('openaire'); $openaire = $role->getCollectionByOaiSubset('openaire'); $doc->addCollection($openaire); @@ -2373,7 +2146,7 @@ public function testXMetaDissPlusForPeriodicalParts() $doc = $this->createTestDocument(); $doc->setServerState('published'); $doc->setType('periodicalpart'); - $series = new Opus_Series(7); + $series = new Series(7); $doc->addSeries($series)->setNumber('1337'); $docId = $doc->store(); @@ -2573,15 +2346,6 @@ public function testXmlValidOpusvier3846() libxml_clear_errors(); } - public function testGetRecordOaiDcContainsDoi() - { - $this->dispatch('/oai?verb=GetRecord&metadataPrefix=oai_dc&identifier=oai::146'); - - $this->registerXpathNamespaces($this->xpathNamespaces); - - $this->assertXpathContentContains('//oai_dc:dc/dc:identifier', '123'); - } - public function testGetRecordXMetaDissPlusContainsDoi() { $this->dispatch('/oai?verb=GetRecord&metadataPrefix=XMetaDissPlus&identifier=oai::146'); @@ -2603,13 +2367,13 @@ public function testGetRecordXMetaDissPlusDcmiType() public function testGetRecordMarc21OfDocId91() { - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'marc21' => [ 'isil' => 'DE-9999', 'publisherName' => 'publisherNameFromConfig', 'publisherCity' => 'publisherCityFromConfig', ] - ])); + ]); $this->dispatch('/oai?verb=GetRecord&metadataPrefix=marc21&identifier=oai::91'); @@ -2662,65 +2426,65 @@ public function testGetRecordMarc21OfTestDocOfUnknownType() $doc->setPageNumber('10'); $doc->setCreatingCorporation('Foo Creating Corp.'); - $identifierUrn = new Opus_Identifier(); + $identifierUrn = new Identifier(); $identifierUrn->setType('urn'); $identifierUrn->setValue('urn:nbn:de:foo:opus-4711'); - $identifierIssn = new Opus_Identifier(); + $identifierIssn = new Identifier(); $identifierIssn->setType('issn'); $identifierIssn->setValue('0953-4563'); $doc->setIdentifier([$identifierUrn, $identifierIssn]); - $ddc33x = new Opus_Collection(45); // sichtbar - $ddc334 = new Opus_Collection(402); // unsichtbar - $ddc34x = new Opus_Collection(46); // sichtbar + $ddc33x = new Collection(45); // sichtbar + $ddc334 = new Collection(402); // unsichtbar + $ddc34x = new Collection(46); // sichtbar $doc->setCollection([$ddc33x, $ddc334, $ddc34x]); - $titleMainDeu = new Opus_TitleAbstract(); + $titleMainDeu = new TitleAbstract(); $titleMainDeu->setLanguage('deu'); $titleMainDeu->setType('main'); $titleMainDeu->setValue('TitleMainInDocumentLanguage'); - $titleMainEng = new Opus_TitleAbstract(); + $titleMainEng = new TitleAbstract(); $titleMainEng->setLanguage('eng'); $titleMainEng->setType('main'); $titleMainEng->setValue('TitleMainInOtherLanguage'); $doc->setTitleMain([$titleMainDeu, $titleMainEng]); - $titleSubDeu = new Opus_TitleAbstract(); + $titleSubDeu = new TitleAbstract(); $titleSubDeu->setLanguage('deu'); $titleSubDeu->setType('sub'); $titleSubDeu->setValue('TitleSubInDocumentLanguage'); - $titleSubEng = new Opus_TitleAbstract(); + $titleSubEng = new TitleAbstract(); $titleSubEng->setLanguage('eng'); $titleSubEng->setType('sub'); $titleSubEng->setValue('TitleSubInOtherLanguage'); $doc->setTitleSub([$titleSubDeu, $titleSubEng]); - $titleParent = new Opus_TitleAbstract(); + $titleParent = new TitleAbstract(); $titleParent->setLanguage('deu'); $titleParent->setType('parent'); $titleParent->setValue('TitleParentInDocumentLanguage'); $doc->setTitleParent([$titleParent]); - $abstractDeu = new Opus_TitleAbstract(); + $abstractDeu = new TitleAbstract(); $abstractDeu->setLanguage('deu'); $abstractDeu->setType('abstract'); $abstractDeu->setValue('TitleAbstractInDocumentLanguage'); - $abstractEng = new Opus_TitleAbstract(); + $abstractEng = new TitleAbstract(); $abstractEng->setLanguage('eng'); $abstractEng->setType('abstract'); $abstractEng->setValue('TitleAbstractInOtherLanguage'); $doc->setTitleAbstract([$abstractEng, $abstractDeu]); - $doc->setThesisPublisher([new Opus_DnbInstitute(2), new Opus_DnbInstitute(4)]); + $doc->setThesisPublisher([new DnbInstitute(2), new DnbInstitute(4)]); - $editor = new Opus_Person(); + $editor = new Person(); $editor->setFirstName('John'); $editor->setLastName('Doe'); $doc->addPersonEditor($editor); - $doc->addSeries(new Opus_Series(1))->setNumber(1); - $doc->addSeries(new Opus_Series(2))->setNumber(2); - $doc->addSeries(new Opus_Series(3))->setNumber(3); + $doc->addSeries(new Series(1))->setNumber(1); + $doc->addSeries(new Series(2))->setNumber(2); + $doc->addSeries(new Series(3))->setNumber(3); $docId = $doc->store(); @@ -2831,15 +2595,15 @@ public function testGenerationOfField856WithInvisibleInOaiFile() $doc->setServerState('published'); $doc->setPublisherPlace('publisherPlace'); - $f1 = new Opus_File(); + $f1 = new File(); $f1->setPathName('invisible-in-oai.pdf'); $f1->setVisibleInOai(false); $doc->addFile($f1); - $licencePresent = new Opus_Licence(1); + $licencePresent = new Licence(1); $doc->addLicence($licencePresent); - $licenceMissing = new Opus_Licence(2); + $licenceMissing = new Licence(2); $doc->addLicence($licenceMissing); $docId = $doc->store(); @@ -2865,20 +2629,20 @@ public function testGenerationOfField856With2VisibleInOaiFiles() $doc->setServerState('published'); $doc->setPublisherPlace('publisherPlace'); - $f1 = new Opus_File(); + $f1 = new File(); $f1->setPathName('visible-in-oai.pdf'); $f1->setVisibleInOai(true); $doc->addFile($f1); - $f2 = new Opus_File(); + $f2 = new File(); $f2->setPathName('visible-in-oai.txt'); $f2->setVisibleInOai(true); $doc->addFile($f2); - $licencePresent = new Opus_Licence(1); + $licencePresent = new Licence(1); $doc->addLicence($licencePresent); - $licenceMissing = new Opus_Licence(2); + $licenceMissing = new Licence(2); $doc->addLicence($licenceMissing); $docId = $doc->store(); @@ -3576,13 +3340,13 @@ public function testGenerationOfField773WithVolumeAndIsbn() /** * Helper function for adding title parent to given document. * - * @param $doc Opus_Document + * @param $doc Document * @param $language string * @param $value string */ private function addTitleParent($doc, $language, $value) { - $titleParent = new Opus_TitleAbstract(); + $titleParent = new TitleAbstract(); $titleParent->setType('parent'); $titleParent->setLanguage($language); $titleParent->setValue($value); @@ -3593,16 +3357,57 @@ private function addTitleParent($doc, $language, $value) /** * Helper function for adding identifier of given type to given document. * - * @param $doc Opus_Document + * @param $doc Document * @param $value string * @param $type string */ private function addIdentifier($doc, $value, $type) { - $identifier = new Opus_Identifier(); + $identifier = new Identifier(); $identifier->setType($type); $identifier->setValue($value); $doc->addIdentifier($identifier); } + + public function metadataPrefixProvider() + { + return [ + ['MARC21'], + ['marc21'], + ['mArC21'] + ]; + } + + /** + * @param $metadataPrefix + * @dataProvider metadataPrefixProvider + */ + public function testMetadataPrefixCaseInsensitive($metadataPrefix) + { + $this->dispatch("/oai?verb=ListRecords&metadataPrefix=$metadataPrefix"); + $this->assertResponseCode(200); + + $body = $this->getResponse()->getBody(); + + $this->checkForCustomBadStringsInHtml($body, ["Exception", "Stacktrace", "badVerb"]); + + $this->assertContains( + '', + $body, + "Response must contain ''" + ); + $this->assertContains( + '', + $body, + "Response must contain ''" + ); + + // TODO check that metadata is generated + $this->assertNotContains( + '', + $body, + 'Response must not contains empty \'\' elements.' + ); + } } diff --git a/tests/modules/oai/format/DcTest.php b/tests/modules/oai/format/DcTest.php index eadeb853c0..6396fba64c 100644 --- a/tests/modules/oai/format/DcTest.php +++ b/tests/modules/oai/format/DcTest.php @@ -31,26 +31,13 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ -use Opus\Collection; -use Opus\CollectionRole; -use Opus\DnbInstitute; use Opus\Document; -use Opus\Enrichment; -use Opus\File; -use Opus\Identifier; -use Opus\Licence; -use Opus\Person; -use Opus\Series; -use Opus\TitleAbstract; -use Opus\UserRole; /** * TODO unit tests transformations directly without "dispatch" * TODO create plugins for formats/protocols/standards * TODO test dc:type value for different formats * TODO test ListSets values for document type sets - * - * @covers Oai_IndexController */ class Oai_Format_DcTest extends ControllerTestCase { @@ -66,13 +53,10 @@ class Oai_Format_DcTest extends ControllerTestCase 'dc' => "http://purl.org/dc/elements/1.1/", 'ddb' => "http://www.d-nb.de/standards/ddb/", 'pc' => "http://www.d-nb.de/standards/pc/", - 'xMetaDiss' => "http://www.d-nb.de/standards/xmetadissplus/", - 'epicur' => "urn:nbn:de:1111-2004033116", 'dcterms' => "http://purl.org/dc/terms/", 'thesis' => "http://www.ndltd.org/standards/metadata/etdms/1.0/", - 'eprints' => 'http://www.openarchives.org/OAI/1.1/eprints', 'oaiid' => 'http://www.openarchives.org/OAI/2.0/oai-identifier', - 'marc' => 'http://www.loc.gov/MARC21/slim' + 'xmlns' => 'http://www.openarchives.org/OAI/2.0/' ]; /** @@ -106,6 +90,240 @@ protected function prepareXpathFromResultString($resultString) return $xpath; } + /** + * Test verb=GetRecord, prefix=oai_dc. + */ + public function testGetRecordOaiDc() + { + $this->dispatch('/oai?verb=GetRecord&metadataPrefix=oai_dc&identifier=oai::35'); + $this->assertResponseCode(200); + + $response = $this->getResponse(); + $this->checkForBadStringsInHtml($response->getBody()); + } + + /** + * Regression test for OPUSVIER-2379 + */ + public function testGetRecordOaiDcDoc91DocType() + { + $doc = Document::get(91); + $this->assertEquals("report", $doc->getType(), "testdata changed"); + + $this->dispatch('/oai?verb=GetRecord&metadataPrefix=oai_dc&identifier=oai::91'); + $this->assertResponseCode(200); + + $response = $this->getResponse(); + $badStrings = ["Exception", "Error", "Stacktrace", "badVerb"]; + $this->checkForCustomBadStringsInHtml($response->getBody(), $badStrings); + + $xpath = $this->prepareXpathFromResultString($response->getBody()); + + // Regression test for OPUSVIER-2379 (show doc-type:report) + $elements = $xpath->query('//oai_dc:dc/dc:type[text()="doc-type:report"]'); + $this->assertEquals( + 1, + $elements->length, + "Unexpected count for doc-type:report" + ); + } + + /** + * Regression tests on document 146 + */ + public function testGetRecordOaiDcDoc146() + { + $this->dispatch('/oai?verb=GetRecord&metadataPrefix=oai_dc&identifier=oai::146'); + $this->assertResponseCode(200); + + $response = $this->getResponse(); + $badStrings = ["Exception", "Error", "Stacktrace", "badVerb"]; + $this->checkForCustomBadStringsInHtml($response->getBody(), $badStrings); + + $xpath = $this->prepareXpathFromResultString($response->getBody()); + + // Regression test for OPUSVIER-2393 (show dc:contributor) + $elements = $xpath->query('//oai_dc:dc/dc:contributor/text()'); + $this->assertGreaterThanOrEqual(2, $elements->length, 'dc:contributor count changed'); + $this->assertEquals('Doe, Jane (PhD)', $elements->item(0)->nodeValue, 'dc:contributor field changed'); + $this->assertEquals('Baz University', $elements->item(1)->nodeValue, 'dc:contributor field changed'); + + // Regression test for OPUSVIER-2393 (show dc:identifier) + $urnResolverUrl = $this->getConfig()->urn->resolverUrl; + $elements = $xpath->query('//oai_dc:dc/dc:identifier[text()="' . $urnResolverUrl . 'urn:nbn:op:123"]'); + $this->assertEquals(1, $elements->length, 'dc:identifier URN count changed'); + + $elements = $xpath->query('//oai_dc:dc/dc:identifier[text()="123"]'); + $this->assertGreaterThanOrEqual(1, $elements->length, 'dc:identifier URN count changed'); + } + + /** + * Regression tests on document 91 + */ + public function testGetRecordOaiDcDoc91() + { + $this->dispatch('/oai?verb=GetRecord&metadataPrefix=oai_dc&identifier=oai::91'); + $this->assertResponseCode(200); + + $response = $this->getResponse(); + $badStrings = ["Exception", "Error", "Stacktrace", "badVerb"]; + $this->checkForCustomBadStringsInHtml($response->getBody(), $badStrings); + + $xpath = $this->prepareXpathFromResultString($response->getBody()); + + // Regression test for OPUSVIER-2393 (show dc:identifier) + $elements = $xpath->query('//oai_dc:dc/dc:identifier/text()'); + + $foundIds = []; + foreach ($elements as $element) { + $nodeValue = $element->nodeValue; + if (strstr($nodeValue, '/files/')) { + $foundIds[] = preg_replace("/^.*(\/files\/\d+\/.*)$/", "$1", $element->nodeValue); + } + } + + $this->assertContains("/files/91/test.pdf", $foundIds); + $this->assertContains("/files/91/test.txt", $foundIds); + $this->assertContains("/files/91/frontdoor_invisible.txt", $foundIds); + + // Regression test for OPUSVIER-2393 (show dc:creator) + $elements = $xpath->query('//oai_dc:dc/dc:creator/text()'); + $this->assertEquals(3, $elements->length, 'dc:creator count changed'); + $this->assertEquals('Doe, John', $elements->item(0)->nodeValue, 'dc:creator field changed'); + $this->assertEquals('Zufall, Rainer', $elements->item(1)->nodeValue, 'dc:creator field changed'); + $this->assertEquals('Fall, Klara', $elements->item(2)->nodeValue, 'dc:creator field changed'); + } + + /** + * Regression test for OPUSVIER-2380 and OPUSVIER-2378 + */ + public function testGetRecordOaiDcDoc10SubjectDdcAndDate() + { + $doc = Document::get(10); + $ddcs = []; + foreach ($doc->getCollection() as $c) { + if ($c->getRoleName() == 'ddc') { + $ddcs[] = $c->getNumber(); + } + } + $this->assertContains("004", $ddcs, "testdata changed"); + + $this->dispatch('/oai?verb=GetRecord&metadataPrefix=oai_dc&identifier=oai::10'); + $this->assertResponseCode(200); + + $response = $this->getResponse(); + $badStrings = ["Exception", "Error", "Stacktrace", "badVerb"]; + $this->checkForCustomBadStringsInHtml($response->getBody(), $badStrings); + + $xpath = $this->prepareXpathFromResultString($response->getBody()); + + // Regression test for OPUSVIER-2380 (show ddc:) + $elements = $xpath->query('//oai_dc:dc/dc:subject[text()="ddc:004"]'); + $this->assertEquals( + 1, + $elements->length, + "Unexpected count for ddc:004" + ); + + // Regression test for OPUSVIER-2378 (show ) + $elements = $xpath->query('//oai_dc:dc/dc:date'); + $this->assertEquals( + 1, + $elements->length, + "Unexpected count for dc:date" + ); + + // Regression test for OPUSVIER-2378 (show 2003) + $elements = $xpath->query('//oai_dc:dc/dc:date[text()="2003"]'); + $this->assertEquals( + 1, + $elements->length, + "Unexpected count for dc:date" + ); + } + + /** + * Regression test for OPUSVIER-2378 + */ + public function testGetRecordOaiDcDoc114DcDate() + { + $doc = Document::get(114); + $completedDate = $doc->getCompletedDate(); + $this->assertEquals("2011-04-19", "$completedDate", "testdata changed"); + + $this->dispatch('/oai?verb=GetRecord&metadataPrefix=oai_dc&identifier=oai::114'); + $this->assertResponseCode(200); + + $response = $this->getResponse(); + $badStrings = ["Exception", "Error", "Stacktrace", "badVerb"]; + $this->checkForCustomBadStringsInHtml($response->getBody(), $badStrings); + + $xpath = $this->prepareXpathFromResultString($response->getBody()); + + // Regression test for OPUSVIER-2378 (show ) + $elements = $xpath->query('//oai_dc:dc/dc:date'); + $this->assertEquals( + 1, + $elements->length, + "Unexpected count for dc:date" + ); + + // Regression test for OPUSVIER-2378 (show 2011-04-19) + $elements = $xpath->query('//oai_dc:dc/dc:date[text()="2011-04-19"]'); + $this->assertEquals( + 1, + $elements->length, + "Unexpected count for dc:date" + ); + } + + /** + * Regression test for OPUSVIER-2454 + */ + public function testGetRecordOaiDcDoc1ByIdentifierPrefixOai() + { + $this->dispatch('/oai?verb=GetRecord&metadataPrefix=oai_dc&identifier=oai::1'); + $this->assertResponseCode(200); + + $response = $this->getResponse(); + $badStrings = ["Exception", "Error", "Stacktrace", "badVerb"]; + $this->checkForCustomBadStringsInHtml($response->getBody(), $badStrings); + + $xpath = $this->prepareXpathFromResultString($response->getBody()); + + // Regression test for OPUSVIER-2454 (check returned dc:identifier) + $elements = $xpath->query('//oai_dc:dc/dc:identifier[text()="urn:nbn:de:gbv:830-opus-225"]'); + $this->assertEquals(1, $elements->length, "Expected URN not found"); + } + + /** + * Regression test for OPUSVIER-2454 + */ + public function testGetRecordOaiDcDoc1ByIdentifierPrefixUrn() + { + $this->dispatch('/oai?verb=GetRecord&metadataPrefix=oai_dc&identifier=urn:nbn:de:gbv:830-opus-225'); + $this->assertResponseCode(200); + + $response = $this->getResponse(); + $badStrings = ["Exception", "Error", "Stacktrace", "badVerb"]; + $this->checkForCustomBadStringsInHtml($response->getBody(), $badStrings); + + $xpath = $this->prepareXpathFromResultString($response->getBody()); + + // Regression test for OPUSVIER-2454 (check returned dc:identifier) + $elements = $xpath->query('//oai_dc:dc/dc:identifier[text()="urn:nbn:de:gbv:830-opus-225"]'); + $this->assertEquals(1, $elements->length, "Expected URN not found"); + } + + public function testGetRecordOaiDcContainsDoi() + { + $this->dispatch('/oai?verb=GetRecord&metadataPrefix=oai_dc&identifier=oai::146'); + + $this->registerXpathNamespaces($this->xpathNamespaces); + + $this->assertXpathContentContains('//oai_dc:dc/dc:identifier', '123'); + } + public function testXmlXsiSchemaDeclarationPresentForDcMetadata() { $this->dispatch('/oai?verb=GetRecord&metadataPrefix=oai_dc&identifier=oai::146'); @@ -128,9 +346,7 @@ public function testListRecordsMetadataSchemaWithResumptionToken() { $max_records = '2'; - Zend_Registry::get('Zend_Config')->merge( - new Zend_Config(['oai' => ['max' => ['listrecords' => $max_records]]]) - ); + $this->adjustConfiguration(['oai' => ['max' => ['listrecords' => $max_records]]]); // first request: fetch documents list and expect resumption code $this->dispatch("/oai?verb=ListRecords&metadataPrefix=oai_dc"); diff --git a/tests/modules/oai/models/ContainerTest.php b/tests/modules/oai/models/ContainerTest.php index 4c09d5fe03..56f54c6fa6 100644 --- a/tests/modules/oai/models/ContainerTest.php +++ b/tests/modules/oai/models/ContainerTest.php @@ -1,4 +1,11 @@ getConfig(); if (! isset($config->workspacePath)) { throw new Exception("config key 'workspacePath' not defined in config file"); } @@ -55,11 +62,11 @@ public function setUp() public function tearDown() { if (! is_null($this->roleId)) { - $testRole = new Opus_UserRole($this->roleId); + $testRole = new UserRole($this->roleId); $testRole->delete(); } if (! is_null($this->userId)) { - $userAccount = new Opus_Account($this->userId); + $userAccount = new Account($this->userId); $userAccount->delete(); } parent::tearDown(); @@ -100,7 +107,7 @@ public function testConstructorWithUnknownDocId() public function testConstructorWithUnpublishedDocument() { - $r = Opus_UserRole::fetchByName('guest'); + $r = UserRole::fetchByName('guest'); $modules = $r->listAccessModules(); $addOaiModuleAccess = ! in_array('oai', $modules); @@ -110,9 +117,8 @@ public function testConstructorWithUnpublishedDocument() } // enable security - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $config->security = self::CONFIG_VALUE_TRUE; - Zend_Registry::set('Zend_Config', $config); $doc = $this->createTestDocument(); $doc->setServerState('unpublished'); @@ -153,7 +159,7 @@ public function testGetName() { $doc = $this->createTestDocument(); $doc->setServerState('published'); - $file = new Opus_File(); + $file = new File(); $file->setPathName('foo.pdf'); $file->setVisibleInOai(false); $doc->addFile($file); @@ -190,7 +196,7 @@ public function testDocumentWithNonExistentFile() { $doc = $this->createTestDocument(); $doc->setServerState('published'); - $file = new Opus_File(); + $file = new File(); $file->setPathName('test.pdf'); $file->setVisibleInOai(true); $doc->addFile($file); @@ -333,7 +339,7 @@ public function testAdminAccessToFileRegression3281() $docId = $doc->store(); $this->tryAccessForDocument($docId, true); - $doc = new Opus_Document($docId); + $doc = Document::get($docId); $doc->setServerState('unpublished'); $docId = $doc->store(); $this->tryAccessForDocument($docId, true); @@ -352,13 +358,13 @@ public function testAccessUserToFileRegression3281() $doc->setServerState('unpublished'); $unpublishedDocId = $doc->store(); - $testRole = new Opus_UserRole(); + $testRole = new UserRole(); $testRole->setName('test_access'); $testRole->appendAccessDocument($unpublishedDocId); $testRole->appendAccessDocument($publishedDocId); $this->roleId = $testRole->store(); - $userAccount = new Opus_Account(); + $userAccount = new Account(); $userAccount->setLogin('test_account')->setPassword('role_tester_user2'); $userAccount->setRole($testRole); $this->userId = $userAccount->store(); @@ -379,7 +385,7 @@ public function testGuestAccessToFileRegression3281() $docId = $doc->store(); $this->tryAccessForDocument($docId, true); - $doc = new Opus_Document($docId); + $doc = Document::get($docId); $doc->setServerState('unpublished'); $docId = $doc->store(); $this->tryAccessForDocument($docId, false); @@ -414,7 +420,7 @@ public function testGetAccessibleFilesForEmbargoedDocument() $doc->setServerState('published'); // set embargo date to tomorrow - $date = new Opus_Date(); + $date = new Date(); $date->setDateTime(new DateTime('tomorrow')); $doc->setEmbargoDate($date); diff --git a/tests/modules/oai/models/DocumentListTest.php b/tests/modules/oai/models/DocumentListTest.php index 70b98c7291..cae073de0d 100644 --- a/tests/modules/oai/models/DocumentListTest.php +++ b/tests/modules/oai/models/DocumentListTest.php @@ -1,5 +1,4 @@ createTestDocument(); $docWithUrn->setServerState('published'); - $identifier = new Opus_Identifier(); + $identifier = new Identifier(); $identifier->setValue('urn_value1'); $identifier->setType('urn'); $docWithUrn->addIdentifier($identifier); @@ -77,7 +80,7 @@ public function testIntervalOAIPMHQueries() $doc->addFile($file); $this->docId = $doc->store(); - $doc = new Opus_Document($this->docId); + $doc = Document::get($this->docId); $serverDateModified = $doc->getServerDateModified(); $today = new DateTime(); @@ -135,7 +138,7 @@ public function testIntervalOAIPMHQueryWithoutTestDoc() $doc->setServerState('published'); $this->docId = $doc->store(); - $doc = new Opus_Document($this->docId); + $doc = Document::get($this->docId); $serverDateModified = $doc->getServerDateModified(); $today = new DateTime(); diff --git a/tests/modules/oai/models/XmlFactoryTest.php b/tests/modules/oai/models/XmlFactoryTest.php index 425a254244..5cc3f93dd0 100644 --- a/tests/modules/oai/models/XmlFactoryTest.php +++ b/tests/modules/oai/models/XmlFactoryTest.php @@ -31,6 +31,8 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Document; + class Oai_Model_XmlFactoryTest extends ControllerTestCase { @@ -56,7 +58,7 @@ public function testGetAccessRights() $file->setVisibleInOai(1); $file->setVisibleInFrontdoor(1); $doc->addFile($file); - $doc = new Opus_Document($doc->store()); // store and get fresh object + $doc = Document::get($doc->store()); // store and get fresh object // document with file accessible in OAI and frontdoor $this->assertEquals('info:eu-repo/semantics/openAccess', $this->_xmlFactory->getAccessRights($doc)); @@ -78,7 +80,7 @@ public function testGetAccessRights() $file2->setVisibleInOai(1); $file2->setVisibleInFrontdoor(1); $doc->addFile($file2); - $doc = new Opus_Document($doc->store()); + $doc = Document::get($doc->store()); $this->assertCount(2, $doc->getFile()); diff --git a/tests/modules/publish/View/Helper/JavascriptMessagesTest.php b/tests/modules/publish/View/Helper/JavascriptMessagesTest.php index 46b9583715..e69de29bb2 100644 --- a/tests/modules/publish/View/Helper/JavascriptMessagesTest.php +++ b/tests/modules/publish/View/Helper/JavascriptMessagesTest.php @@ -1,70 +0,0 @@ - - * @copyright Copyright (c) 2019, OPUS 4 development team - * @license http://www.gnu.org/licenses/gpl.html General Public License - */ - -class Publish_View_Helper_JavascriptMessagesTest extends ControllerTestCase -{ - - protected $additionalResources = ['view', 'translation']; - - private $helper; - - public function setUp() - { - parent::setUp(); - - $this->useEnglish(); - - $this->helper = new Publish_View_Helper_JavascriptMessages(); - - $this->helper->setView(Zend_Registry::get('Opus_View')); - } - - /** - * Tests if default translations for javascript in the publish module are set correctly. - */ - public function testGetDefaultMessageSet() - { - $this->helper->getDefaultMessageSet(); - - $expectation = ' ' . "\n"; - - $this->assertEquals($expectation, $this->helper->javascriptMessages()); - } -} diff --git a/tests/modules/publish/controllers/DepositControllerTest.php b/tests/modules/publish/controllers/DepositControllerTest.php index 00aa12b66e..9bd4ea0c0e 100644 --- a/tests/modules/publish/controllers/DepositControllerTest.php +++ b/tests/modules/publish/controllers/DepositControllerTest.php @@ -27,10 +27,13 @@ * @category Tests * @package Publish * @author Susanne Gottwald - * @copyright Copyright (c) 2008-2019, OPUS 4 development team + * @copyright Copyright (c) 2008-2021, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Document; +use Opus\Log; + /** * Class Publish_DepositControllerTest. * @@ -58,7 +61,7 @@ public function testdepositActionWithoutPost() */ public function testDepositActionWithValidPostAndBackButton() { - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $elemente = [ 1 => ['name' => 'PersonSubmitterFirstName_1', 'value' => 'Hans'], 2 => ['name' => 'PersonSubmitterLastName_1', 'value' => 'Hansmann'], @@ -90,7 +93,7 @@ public function testDepositActionWithValidPostAndBackButton() */ public function testDepositActionWithValidPostAndSendButton() { - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $elemente = [ 1 => ['name' => 'PersonSubmitterFirstName_1', 'value' => 'Hans', 'datatype' => 'Person', 'subfield' => '0'], 2 => ['name' => 'PersonSubmitterLastName_1', 'value' => 'Hansmann', 'datatype' => 'Person', 'subfield' => '1'], @@ -157,14 +160,14 @@ public function testDepositActionWithValidPostAndSendButton() $this->assertController('deposit'); $this->assertAction('deposit'); - $doc = new Opus_Document($session->documentId); + $doc = Document::get($session->documentId); $this->assertEquals('unpublished', $doc->getServerState()); $this->assertEquals('publish', $doc->getEnrichmentValue('opus.source')); } public function testConfirmAction() { - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $session->depositConfirmDocumentId = '712'; $this->dispatch('/publish/deposit/confirm'); $this->assertController('deposit'); @@ -188,7 +191,7 @@ public function testGetConfirmActionResultsInRedirect() */ public function testDepositActionWithAbortInPost() { - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $elemente = [ 1 => ['name' => 'PersonSubmitterFirstName_1', 'value' => 'Hans'], 2 => ['name' => 'PersonSubmitterLastName_1', 'value' => 'Hansmann'], @@ -227,7 +230,7 @@ public function testStoreExistingDocument() $doc->setServerState('published'); $doc->setType('preprint'); - $log = Zend_Registry::get('Zend_Log'); + $log = Log::get(); $deposit = new Publish_Model_Deposit($log); $deposit->storeDocument($doc->store()); } diff --git a/tests/modules/publish/controllers/FormControllerTest.php b/tests/modules/publish/controllers/FormControllerTest.php index 3694015ab4..8400127ff1 100644 --- a/tests/modules/publish/controllers/FormControllerTest.php +++ b/tests/modules/publish/controllers/FormControllerTest.php @@ -33,6 +33,8 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Document; + /** * Class Publish_FormControllerTest. * @@ -117,7 +119,7 @@ public function testCheckActionWithValidPostAndAddButton() { $doc = $this->createTemporaryDoc(); - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $session->documentType = 'preprint'; $session->documentId = $doc->getId(); $session->fulltext = '0'; @@ -177,7 +179,7 @@ public function testCheckActionWithValidPostAndSendButton() { $doc = $this->createTemporaryDoc(); - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $session->documentType = 'preprint'; $session->documentId = $doc->getId(); $session->fulltext = '0'; @@ -209,7 +211,7 @@ public function testCheckActionWithValidPostAndSendButtonAndAllRequiredFields() { $doc = $this->createTemporaryDoc(); - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $session->documentType = 'preprint'; $session->documentId = $doc->getId(); $session->fulltext = '0'; @@ -263,12 +265,12 @@ public function testCheckActionWithValidPostAndSendButtonAndAllRequiredFields() */ public function testOPUSVIER1886WithBibliography() { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $config->form->first->bibliographie = self::CONFIG_VALUE_TRUE; $doc = $this->createTemporaryDoc(); - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $session->documentType = 'demo'; $session->documentId = $doc->getId(); $session->fulltext = '0'; @@ -292,14 +294,14 @@ public function testOPUSVIER1886WithBibliography() public function testOPUSVIER1886WithBibliographyUnselected() { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $config->form->first->bibliographie = self::CONFIG_VALUE_TRUE; $doc = $this->createTemporaryDoc(); $doc->setBelongsToBibliography(0); $doc->store(); - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $session->documentType = 'demo'; $session->documentId = $doc->getId(); $session->fulltext = '0'; @@ -323,14 +325,14 @@ public function testOPUSVIER1886WithBibliographyUnselected() public function testOPUSVIER1886WithBibliographySelected() { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $config->form->first->bibliographie = self::CONFIG_VALUE_TRUE; $doc = $this->createTemporaryDoc(); $doc->setBelongsToBibliography(1); $doc->store(); - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $session->documentType = 'demo'; $session->documentId = $doc->getId(); $session->fulltext = '0'; @@ -357,12 +359,12 @@ public function testOPUSVIER1886WithBibliographySelected() */ public function testOPUSVIER1886WithoutBibliography() { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $config->form->first->bibliographie = self::CONFIG_VALUE_FALSE; $doc = $this->createTemporaryDoc(); - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $session->documentType = 'demo'; $session->documentId = $doc->getId(); $session->fulltext = '0'; @@ -390,7 +392,7 @@ public function testOPUSVIER1886WithoutBibliography() public function testFormManipulationForBibliography() { $this->markTestIncomplete('testing multipart formdata not yet solved'); - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $config->form->first->bibliographie = self::CONFIG_VALUE_FALSE; $this->request @@ -405,11 +407,11 @@ public function testFormManipulationForBibliography() 'send' => 'Weiter zum nächsten Schritt', ]); $this->dispatch('/publish/form/upload'); - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); - $doc = new Opus_Document($session->documentId); + $doc = Document::get($session->documentId); $belongsToBibliography = $doc->getBelongsToBibliography(); - $doc->deletePermanent(); + $doc->delete(); $this->assertResponseCode(200); $this->assertNotContains("Es sind Fehler aufgetreten.", $this->response->getBody()); @@ -417,7 +419,7 @@ public function testFormManipulationForBibliography() } /** - * @return Opus_Document + * @return Document */ private function createTemporaryDoc() { @@ -450,29 +452,33 @@ public function testShowFileNoticeOnSecondFormPageIfFileUploadIsEnabled() { $this->fileNoticeOnSecondFormPage(self::CONFIG_VALUE_TRUE); - $this->assertContains('

      Alle Felder (Testdokumenttyp)

      ', $this->getResponse()->getBody()); - $this->assertContains('Sie haben folgende Datei(en) hochgeladen:', $this->getResponse()->getBody()); - $this->assertContains('Es wurden keine Dateien hochgeladen.', $this->getResponse()->getBody()); + $output = $this->getResponse()->getBody(); + + $this->assertContains('

      Alle Felder (Testdokumenttyp)

      ', $output); + $this->assertContains('Sie haben folgende Datei(en) hochgeladen:', $output); + $this->assertContains('Es wurden keine Dateien hochgeladen.', $output); } public function testShowFileNoticeOnThirdFormPageIfFileUploadIsEnabled() { $this->fileNoticeOnThirdFormPage(self::CONFIG_VALUE_TRUE); + $output = $this->getResponse()->getBody(); + $this->assertResponseCode(200); - $this->assertContains('Bitte überprüfen Sie Ihre Eingaben', $this->getResponse()->getBody()); - $this->assertContains('Sie haben folgende Datei(en) hochgeladen:', $this->getResponse()->getBody()); - $this->assertContains('Es wurden keine Dateien hochgeladen.', $this->getResponse()->getBody()); + $this->assertContains('Bitte überprüfen Sie Ihre Eingaben', $output); + $this->assertContains('Sie haben folgende Datei(en) hochgeladen:', $output); + $this->assertContains('Es wurden keine Dateien hochgeladen.', $output); } private function fileNoticeOnThirdFormPage($value) { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $config->form->first->enable_upload = $value; $doc = $this->createTemporaryDoc(); - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $session->documentType = 'demo'; $session->documentId = $doc->getId(); $session->fulltext = '0'; @@ -491,12 +497,12 @@ private function fileNoticeOnThirdFormPage($value) private function fileNoticeOnSecondFormPage($value) { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $config->form->first->enable_upload = $value; $doc = $this->createTemporaryDoc(); - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $session->documentType = 'all'; $session->documentId = $doc->getId(); $session->fulltext = '0'; @@ -525,7 +531,7 @@ private function addTemporaryTestDocument($session, $documentType) */ public function testCheckActionWithAddButton() { - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $this->addTemporaryTestDocument($session, 'preprint'); $data = [ 'PersonSubmitterFirstName_1' => '', @@ -576,7 +582,7 @@ public function testCheckActionWithAddButton() */ public function testCheckActionWithDeleteButton() { - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $this->addTemporaryTestDocument($session, 'preprint'); $session->additionalFields['TitleMain'] = '2'; @@ -631,7 +637,7 @@ public function testCheckActionWithDeleteButton() */ public function testCheckActionWithBrowseDownButton() { - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $this->addTemporaryTestDocument($session, 'preprint'); $session->additionalFields['Institute'] = '1'; $session->additionalFields['collId0Institute_1'] = '1'; @@ -687,7 +693,7 @@ public function testCheckActionWithBrowseDownButton() */ public function testCheckActionWithBrowseUpButton() { - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $this->addTemporaryTestDocument($session, 'preprint'); $session->additionalFields['Institute'] = '1'; $session->additionalFields['collId0Institute_1'] = '1'; @@ -744,7 +750,7 @@ public function testCheckActionWithBrowseUpButton() */ public function testCheckActionWithMissingButton() { - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $this->addTemporaryTestDocument($session, 'preprint'); $session->additionalFields['PersonSubmitter'] = '1'; $session->additionalFields['TitleMain'] = '1'; @@ -812,7 +818,7 @@ public function testManipulatePostMissingTitleMainLanguage() { $doc = $this->createTemporaryDoc(); - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $session->documentType = 'preprint'; $session->documentId = $doc->getId(); $session->fulltext = '0'; @@ -845,7 +851,7 @@ public function testManipulatePostMissingTitleAbstractLanguage() { $doc = $this->createTemporaryDoc(); - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $session->documentType = 'preprint'; $session->documentId = $doc->getId(); $session->fulltext = '0'; @@ -879,7 +885,7 @@ public function testManipulatePostMissingTitleParentLanguage() { $doc = $this->createTemporaryDoc(); - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $session->documentType = 'all'; $session->documentId = $doc->getId(); $session->fulltext = '0'; @@ -909,7 +915,7 @@ public function testManipulatePostMissingTitleSubLanguage() { $doc = $this->createTemporaryDoc(); - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $session->documentType = 'all'; $session->documentId = $doc->getId(); $session->fulltext = '0'; @@ -939,7 +945,7 @@ public function testManipulatePostMissingTitleAdditionalLanguage() { $doc = $this->createTemporaryDoc(); - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $session->documentType = 'all'; $session->documentId = $doc->getId(); $session->fulltext = '0'; @@ -967,7 +973,7 @@ public function testManipulatePostMissingTitleAdditionalLanguage() public function testBarfooTemplateIsRenderedForDoctypeFoobar() { - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $session->documentType = 'foobar'; $doc = $this->createTemporaryDoc(); $session->documentId = $doc->getId(); @@ -986,7 +992,7 @@ public function testBarfooTemplateIsRenderedForDoctypeFoobar() public function testApplicationErrorForDoctypeBarbaz() { - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $session->documentType = 'barbaz'; $doc = $this->createTemporaryDoc(); $session->documentId = $doc->getId(); @@ -1004,7 +1010,7 @@ public function testApplicationErrorForDoctypeBarbaz() public function testApplicationErrorForDoctypeBazbar() { - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $session->documentType = 'bazbar'; $doc = $this->createTemporaryDoc(); $session->documentId = $doc->getId(); diff --git a/tests/modules/publish/controllers/IndexControllerTest.php b/tests/modules/publish/controllers/IndexControllerTest.php index 0b93441551..9c1062a633 100644 --- a/tests/modules/publish/controllers/IndexControllerTest.php +++ b/tests/modules/publish/controllers/IndexControllerTest.php @@ -58,7 +58,7 @@ public function testIndexAction() public function testShowFileUpload() { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $config->form->first->enable_upload = self::CONFIG_VALUE_TRUE; $this->dispatch('/publish'); @@ -78,7 +78,7 @@ public function testShowFileUpload() public function testDoNotShowFileUpload() { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $config->form->first->enable_upload = self::CONFIG_VALUE_FALSE; $this->dispatch('/publish'); @@ -99,7 +99,7 @@ public function testDoNotShowFileUpload() public function testShowBibliographyCheckbox() { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $config->form->first->bibliographie = self::CONFIG_VALUE_TRUE; $this->dispatch('/publish'); @@ -117,7 +117,7 @@ public function testShowBibliographyCheckbox() public function testDoNotShowBibliographyCheckbox() { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $config->form->first->bibliographie = self::CONFIG_VALUE_FALSE; $this->dispatch('/publish'); @@ -139,7 +139,7 @@ public function testDoNotShowBibliographyCheckbox() public function testDocumentTypeSelectBoxIsSortedAlphabetically() { // manipulate list of available document types in application configuration - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $include = $config->documentTypes->include; $exclude = $config->documentTypes->exclude; $config->documentTypes->include = 'all, article, workingpaper, demodemo'; diff --git a/tests/modules/publish/forms/PublishingFirstTest.php b/tests/modules/publish/forms/PublishingFirstTest.php index f337468eae..48026dc5da 100644 --- a/tests/modules/publish/forms/PublishingFirstTest.php +++ b/tests/modules/publish/forms/PublishingFirstTest.php @@ -44,12 +44,12 @@ public function testConstructorWithEmptyView() public function testIsValidMethodWithMissingDocumentType() { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $config->form->first->require_upload = self::CONFIG_VALUE_FALSE; $config->form->first->show_rights_checkbox = self::CONFIG_VALUE_FALSE; $config->form->first->bibliographie = self::CONFIG_VALUE_FALSE; - $form = new Publish_Form_PublishingFirst(new Zend_View()); + $form = new Publish_Form_PublishingFirst(new \Zend_View()); $data = [ 'documentType' => '' ]; @@ -60,12 +60,12 @@ public function testIsValidMethodWithMissingDocumentType() public function testIsValidMethodWithMissingRightsCheckbox() { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $config->form->first->require_upload = self::CONFIG_VALUE_FALSE; $config->form->first->show_rights_checkbox = self::CONFIG_VALUE_TRUE; $config->form->first->bibliographie = self::CONFIG_VALUE_FALSE; - $form = new Publish_Form_PublishingFirst(new Zend_View()); + $form = new Publish_Form_PublishingFirst(new \Zend_View()); $data = [ 'documentType' => 'preprint', 'rights' => '0' diff --git a/tests/modules/publish/forms/PublishingSecondTest.php b/tests/modules/publish/forms/PublishingSecondTest.php index a954c3f3b3..1d0a2cd16f 100644 --- a/tests/modules/publish/forms/PublishingSecondTest.php +++ b/tests/modules/publish/forms/PublishingSecondTest.php @@ -40,8 +40,8 @@ class Publish_Form_PublishingSecondTest extends ControllerTestCase public function setUp() { - $writer = new Zend_Log_Writer_Null; - $this->_logger = new Zend_Log($writer); + $writer = new \Zend_Log_Writer_Null; + $this->_logger = new \Zend_Log($writer); parent::setUp(); } @@ -59,7 +59,7 @@ public function testConstructorWithoutDocTypeInSession() */ public function testConstructorWithDocTypeInSession() { - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $session->documentType = 'preprint'; $form = new Publish_Form_PublishingSecond($this->_logger); $this->assertNotNull($form->getElement('back')); @@ -71,9 +71,9 @@ public function testConstructorWithDocTypeInSession() */ public function testIsValidWithInvalidData() { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $config->documentTypes->include = 'all,preprint,article,demo,workingpaper'; - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $session->documentType = 'workingpaper'; $form = new Publish_Form_PublishingSecond($this->_logger); $data = [ @@ -90,9 +90,9 @@ public function testIsValidWithInvalidData() */ public function testIsValidWithValidData() { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $config->documentTypes->include = 'all,preprint,article,demo,workingpaper'; - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $session->documentType = 'demo'; $form = new Publish_Form_PublishingSecond($this->_logger); $data = [ @@ -109,9 +109,9 @@ public function testIsValidWithValidData() */ public function testPrepareCheckMethodWithDemoType() { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $config->documentTypes->include = 'all,preprint,article,demo,workingpaper'; - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $session->documentType = 'demo'; $form = new Publish_Form_PublishingSecond($this->_logger); @@ -128,7 +128,7 @@ public function testPrepareCheckMethodWithDemoType() public function testExternalElementLegalNotices() { - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $session->documentType = 'all'; $session->additionalFields = []; diff --git a/tests/modules/publish/models/DepositTest.php b/tests/modules/publish/models/DepositTest.php index 7e64f01a83..d5c81f44bb 100644 --- a/tests/modules/publish/models/DepositTest.php +++ b/tests/modules/publish/models/DepositTest.php @@ -1,5 +1,4 @@ - * @copyright Copyright (c) 2008-2019, OPUS 4 development team + * @copyright Copyright (c) 2008-2021, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ + +use Opus\EnrichmentKey; +use Opus\Log; + class Publish_Model_DepositTest extends ControllerTestCase { @@ -61,7 +64,7 @@ public function testInvalidDocumentState() $document->setServerState('published'); $documentId = $document->store(); - $log = Zend_Registry::get('Zend_Log'); + $log = Log::get(); $deposit = new Publish_Model_Deposit($log); $deposit->storeDocument($documentId); } @@ -74,7 +77,7 @@ public function testValidDocumentData() $document->setServerState('temporary'); $docId = $document->store(); - $this->enrichmentKey = new Opus_EnrichmentKey(); + $this->enrichmentKey = new EnrichmentKey(); $this->enrichmentKey->setName('Foo2Title'); $this->enrichmentKey->store(); @@ -137,7 +140,7 @@ public function testValidDocumentData() 'Foo2Title' => ['value' => 'title as enrichment', 'datatype' => 'Enrichment', 'subfield' => '0'], ]; - $log = Zend_Registry::get('Zend_Log'); + $log = Log::get(); $dep = new Publish_Model_Deposit($log); $dep->storeDocument($docId, null, $data); @@ -226,7 +229,7 @@ public function testCastStringToDate() $date = $deposit->castStringToOpusDate('2017/03/12'); - $this->assertInstanceOf('Opus_Date', $date); + $this->assertInstanceOf('Opus\Date', $date); $this->assertEquals('2017', $date->getYear()); @@ -245,7 +248,7 @@ public function testCastStringToDateGerman() $date = $deposit->castStringToOpusDate('12.03.2017'); - $this->assertInstanceOf('Opus_Date', $date); + $this->assertInstanceOf('Opus\Date', $date); $this->assertEquals('2017', $date->getYear()); diff --git a/tests/modules/publish/models/DocumenttypeParserTest.php b/tests/modules/publish/models/DocumenttypeParserTest.php index 87e7e8fe04..d8a9327cd1 100644 --- a/tests/modules/publish/models/DocumenttypeParserTest.php +++ b/tests/modules/publish/models/DocumenttypeParserTest.php @@ -1,5 +1,4 @@ _logger = new Zend_Log($writer); + $writer = new \Zend_Log_Writer_Null; + $this->_logger = new \Zend_Log($writer); parent::setUp(); } @@ -50,14 +50,14 @@ public function setUp() */ public function testConstructorWithWrongDom() { - $dom = Zend_Controller_Action_HelperBroker::getStaticHelper('DocumentTypes')->getDocument('irgendwas'); + $dom = \Zend_Controller_Action_HelperBroker::getStaticHelper('DocumentTypes')->getDocument('irgendwas'); $model = new Publish_Model_DocumenttypeParser($dom, null); $this->assertNull($model->dom); } public function testConstructorWithCorrectDom() { - $dom = Zend_Controller_Action_HelperBroker::getStaticHelper('DocumentTypes')->getDocument('preprint'); + $dom = \Zend_Controller_Action_HelperBroker::getStaticHelper('DocumentTypes')->getDocument('preprint'); $model = new Publish_Model_DocumenttypeParser($dom, null); $this->assertInstanceOf('DOMDocument', $model->dom); } @@ -67,9 +67,9 @@ public function testConstructorWithCorrectDom() */ public function testConstructorWithCorrectDomAndWrongForm() { - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $session->documentType = 'irgendwas'; - $dom = Zend_Controller_Action_HelperBroker::getStaticHelper('DocumentTypes')->getDocument('preprint'); + $dom = \Zend_Controller_Action_HelperBroker::getStaticHelper('DocumentTypes')->getDocument('preprint'); $form = new Publish_Form_PublishingSecond($this->_logger); $model = new Publish_Model_DocumenttypeParser($dom, $form); $this->assertInstanceOf('DOMDocument', $model->dom); @@ -77,9 +77,9 @@ public function testConstructorWithCorrectDomAndWrongForm() public function testConstructorWithCorrectDomAndCorrectForm() { - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $session->documentType = 'preprint'; - $dom = Zend_Controller_Action_HelperBroker::getStaticHelper('DocumentTypes')->getDocument('preprint'); + $dom = \Zend_Controller_Action_HelperBroker::getStaticHelper('DocumentTypes')->getDocument('preprint'); $form = new Publish_Form_PublishingSecond($this->_logger); $model = new Publish_Model_DocumenttypeParser($dom, $form); $this->assertInstanceOf('DOMDocument', $model->dom); @@ -92,11 +92,11 @@ public function testConstructorWithCorrectDomAndCorrectForm() public function testInccorectFieldName() { - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $session->documentType = 'all'; /* @var $dom DomDocument */ - $dom = Zend_Controller_Action_HelperBroker::getStaticHelper('DocumentTypes')->getDocument('all'); + $dom = \Zend_Controller_Action_HelperBroker::getStaticHelper('DocumentTypes')->getDocument('all'); $this->assertInstanceOf('DOMDocument', $dom); foreach ($dom->getElementsByTagname('documenttype') as $rootNode) { @@ -124,11 +124,11 @@ public function testInccorectFieldName() public function testIncorrectEnrichmentKey() { - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $session->documentType = 'all'; /* @var $dom DomDocument */ - $dom = Zend_Controller_Action_HelperBroker::getStaticHelper('DocumentTypes')->getDocument('all'); + $dom = \Zend_Controller_Action_HelperBroker::getStaticHelper('DocumentTypes')->getDocument('all'); $this->assertInstanceOf('DOMDocument', $dom); foreach ($dom->getElementsByTagname('documenttype') as $rootNode) { diff --git a/tests/modules/publish/models/ExtendedValidationTest.php b/tests/modules/publish/models/ExtendedValidationTest.php index 5e4cd4b656..3e80998039 100644 --- a/tests/modules/publish/models/ExtendedValidationTest.php +++ b/tests/modules/publish/models/ExtendedValidationTest.php @@ -40,14 +40,14 @@ class Publish_Model_ExtendedValidationTest extends ControllerTestCase public function setUp() { - $writer = new Zend_Log_Writer_Null; - $this->_logger = new Zend_Log($writer); + $writer = new \Zend_Log_Writer_Null; + $this->_logger = new \Zend_Log($writer); parent::setUp(); } public function testPersonsFirstNamesWithInvalidData() { - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $session->documentType = 'all'; $form = new Publish_Form_PublishingSecond($this->_logger); $data = [ @@ -71,7 +71,7 @@ public function testPersonsFirstNamesWithInvalidData() public function testPersonsEmailWithInvalidData() { - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $session->documentType = 'all'; $form = new Publish_Form_PublishingSecond($this->_logger); $data = [ @@ -95,9 +95,9 @@ public function testPersonsEmailWithInvalidData() public function testPersonsEmailNotificationWithValidData() { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $config->documentTypes->include = 'all,preprint,article,demo,workingpaper'; - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $session->documentType = 'workingpaper'; $form = new Publish_Form_PublishingSecond($this->_logger); $data = [ @@ -121,9 +121,9 @@ public function testPersonsEmailNotificationWithValidData() public function testPersonsEmailNotificationWithInvalidData() { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $config->documentTypes->include = 'all,preprint,article,demo,workingpaper'; - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $session->documentType = 'workingpaper'; $form = new Publish_Form_PublishingSecond($this->_logger); $data = [ @@ -150,9 +150,9 @@ public function testPersonsEmailNotificationWithInvalidData() */ public function testMainTitleWithWrongDocLanguage() { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $config->documentTypes->include = 'all,preprint,article,demo,workingpaper'; - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $session->documentType = 'workingpaper'; $form = new Publish_Form_PublishingSecond($this->_logger); $data = [ @@ -179,9 +179,9 @@ public function testMainTitleWithWrongDocLanguage() */ public function testEmptyMainTitleLanguage() { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $config->documentTypes->include = 'all,preprint,article,demo,workingpaper'; - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $session->documentType = 'workingpaper'; $form = new Publish_Form_PublishingSecond($this->_logger); $data = [ @@ -211,9 +211,9 @@ public function testSeveralMainTitleLanguages() { $this->markTestSkipped('Method getExtendedForm removed from Form class: moved to FormController class as manipulateSession'); - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $config->documentTypes->include = 'all,preprint,article,demo,workingpaper'; - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $session->documentType = 'workingpaper'; $session->additionalFields = []; $session->additionalFields['TitleMain'] = '4'; @@ -250,9 +250,9 @@ public function testSeveralMainTitleLanguages() */ public function testSeveralTitleTypeLanguages() { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $config->documentTypes->include = 'all,preprint,article,demo,workingpaper'; - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $session->documentType = 'workingpaper'; $form = new Publish_Form_PublishingSecond($this->_logger); $data = [ @@ -285,9 +285,9 @@ public function testSeveralTitleTypeLanguages() */ public function testSeriesNumberValidationWithUnknownSeries() { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $config->documentTypes->include = 'all'; - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $session->documentType = 'all'; $form = new Publish_Form_PublishingSecond($this->_logger); $data = [ @@ -311,9 +311,9 @@ public function testSeriesNumberValidationWithUnknownSeries() */ public function testSeriesNumberValidationWithMissingSeriesField() { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $config->documentTypes->include = 'all'; - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $session->documentType = 'all'; $form = new Publish_Form_PublishingSecond($this->_logger); $data = [ diff --git a/tests/modules/publish/models/FormElementTest.php b/tests/modules/publish/models/FormElementTest.php index 6be0d8f6bb..bd091a5d67 100644 --- a/tests/modules/publish/models/FormElementTest.php +++ b/tests/modules/publish/models/FormElementTest.php @@ -40,14 +40,14 @@ class Publish_Model_FormElementTest extends ControllerTestCase public function setUp() { - $writer = new Zend_Log_Writer_Null; - $this->_logger = new Zend_Log($writer); + $writer = new \Zend_Log_Writer_Null; + $this->_logger = new \Zend_Log($writer); parent::setUp(); } public function testUnrequiredFirstNames() { - $session = new Zend_Session_Namespace('Publish'); + $session = new \Zend_Session_Namespace('Publish'); $session->documentType = 'all'; $form = new Publish_Form_PublishingSecond($this->_logger); diff --git a/tests/modules/publish/models/LoggedUserTest.php b/tests/modules/publish/models/LoggedUserTest.php index d4cc9e4482..57de31bded 100644 --- a/tests/modules/publish/models/LoggedUserTest.php +++ b/tests/modules/publish/models/LoggedUserTest.php @@ -29,6 +29,9 @@ * @copyright Copyright (c) 2008-2019, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ + +use Opus\Account; + class Publish_Model_LoggedUserTest extends ControllerTestCase { @@ -73,7 +76,7 @@ public function testCreatePersonValidUser() $this->setZendAuthIdentity($accountName); - $account = new Opus_Account(); + $account = new Account(); $account->setLogin($accountName) ->setPassword($accountPassword) ->store(); @@ -92,9 +95,9 @@ public function testCreatePersonValidUser() */ private function setZendAuthIdentity($identity) { - $namespace = Zend_Auth_Storage_Session::NAMESPACE_DEFAULT; - $member = Zend_Auth_Storage_Session::MEMBER_DEFAULT; - $session = new Zend_Session_Namespace($namespace); + $namespace = \Zend_Auth_Storage_Session::NAMESPACE_DEFAULT; + $member = \Zend_Auth_Storage_Session::MEMBER_DEFAULT; + $session = new \Zend_Session_Namespace($namespace); $session->{$member} = $identity; } } diff --git a/tests/modules/publish/models/ValidationTest.php b/tests/modules/publish/models/ValidationTest.php index 48bafb50e7..f5c388a245 100644 --- a/tests/modules/publish/models/ValidationTest.php +++ b/tests/modules/publish/models/ValidationTest.php @@ -31,6 +31,11 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Collection; +use Opus\CollectionRole; +use Opus\Licence; +use Opus\Series; + class Publish_Model_ValidationTest extends ControllerTestCase { @@ -41,7 +46,7 @@ class Publish_Model_ValidationTest extends ControllerTestCase public function setUp() { parent::setUp(); - $this->session = new Zend_Session_Namespace(); + $this->session = new \Zend_Session_Namespace(); } public function testValidationWithInvalidDatatype() @@ -212,7 +217,7 @@ public function testSelectOptionsForLicence() */ public function testSortOrderOfSelectOptionForLicence() { - $licences = Opus_Licence::getAll(); + $licences = Licence::getAll(); $activeLicences = []; @@ -267,7 +272,7 @@ public function testInvisibleCollectionRoleDDC() { $val = new Publish_Model_Validation('Collection', $this->session, 'ddc'); - $collectionRole = Opus_CollectionRole::fetchByName($val->collectionRole); + $collectionRole = CollectionRole::fetchByName($val->collectionRole); $visibleFlag = $collectionRole->getVisible(); $collectionRole->setVisible(0); $collectionRole->store(); @@ -283,7 +288,7 @@ public function testVisibleCollectionRoleDDC() { $val = new Publish_Model_Validation('Collection', $this->session, 'ddc'); - $collectionRole = Opus_CollectionRole::fetchByName($val->collectionRole); + $collectionRole = CollectionRole::fetchByName($val->collectionRole); $visibleFlag = $collectionRole->getVisible(); $collectionRole->setVisible(1); $collectionRole->store(); @@ -332,7 +337,7 @@ public function testSortOrderOfSeries() $val = new Publish_Model_Validation('Series', $this->session); $values = $val->selectOptions(); - $series = Opus_Series::getAllSortedBySortKey(); + $series = Series::getAllSortedBySortKey(); $visibleSeries = []; @@ -356,7 +361,7 @@ public function testSortOrderOfSeries() */ public function testCollectionFieldVisiblePublish() { - $collectionRole = new Opus_CollectionRole(); + $collectionRole = new CollectionRole(); $collectionRole->setName("test"); $collectionRole->setOaiName("test"); $collectionRole->setDisplayBrowsing("Name"); @@ -368,7 +373,7 @@ public function testCollectionFieldVisiblePublish() $rootCollection = $collectionRole->addRootCollection(); $rootCollection->store(); - $invisibleCollection = new Opus_Collection(); + $invisibleCollection = new Collection(); $invisibleCollection->setName("invisible collection"); $invisibleCollection->setNumber("123"); $invisibleCollection->setVisible(true); @@ -376,7 +381,7 @@ public function testCollectionFieldVisiblePublish() $rootCollection->addFirstChild($invisibleCollection); $invisibleCollection->store(); - $visibleCollection = new Opus_Collection(); + $visibleCollection = new Collection(); $visibleCollection->setName("visible collection"); $visibleCollection->setNumber("987"); $visibleCollection->setVisiblePublish(true); @@ -384,7 +389,7 @@ public function testCollectionFieldVisiblePublish() $rootCollection->addLastChild($visibleCollection); $visibleId = $visibleCollection->store(); - $mixedVisibilityCollection = new Opus_Collection(); + $mixedVisibilityCollection = new Collection(); $mixedVisibilityCollection->setName("mixed visibility"); $mixedVisibilityCollection->setNumber("456"); $mixedVisibilityCollection->setVisiblePublish(true); @@ -408,7 +413,7 @@ public function testCollectionFieldVisiblePublish() */ public function testRootCollectionFieldVisiblePublish() { - $collectionRole = new Opus_CollectionRole(); + $collectionRole = new CollectionRole(); $collectionRole->setName("test"); $collectionRole->setOaiName("test"); $collectionRole->setDisplayBrowsing("Name"); @@ -423,7 +428,7 @@ public function testRootCollectionFieldVisiblePublish() $rootCollection->setVisiblePublish(false); $rootCollection->store(); - $visibleCollection = new Opus_Collection(); + $visibleCollection = new Collection(); $visibleCollection->setName("visible collection"); $visibleCollection->setNumber("123"); $visibleCollection->setVisible(true); @@ -431,7 +436,7 @@ public function testRootCollectionFieldVisiblePublish() $rootCollection->addFirstChild($visibleCollection); $visibleCollection->store(); - $invisibleCollection = new Opus_Collection(); + $invisibleCollection = new Collection(); $invisibleCollection->setName("collection to invisible root collection"); $invisibleCollection->setNumber("123"); $invisibleCollection->setVisible(true); @@ -439,7 +444,7 @@ public function testRootCollectionFieldVisiblePublish() $rootCollection->addFirstChild($invisibleCollection); $invisibleCollection->store(); - $childCollection = new Opus_Collection(); + $childCollection = new Collection(); $childCollection->setName("collection child"); $childCollection->setNumber("123"); $childCollection->setVisible(true); diff --git a/tests/modules/review/controllers/IndexControllerTest.php b/tests/modules/review/controllers/IndexControllerTest.php index 493dbd925e..8dcec8b54c 100644 --- a/tests/modules/review/controllers/IndexControllerTest.php +++ b/tests/modules/review/controllers/IndexControllerTest.php @@ -30,6 +30,8 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Document; + /** * Basic unit tests for class Review_IndexController. * @@ -52,7 +54,7 @@ public function setUp() $document->setEnrichment([]); $this->documentId = $document->store(); - $document = new Opus_Document($this->documentId); + $document = Document::get($this->documentId); $this->assertEquals(0, count($document->getPersonReferee())); $this->assertEquals(0, count($document->getEnrichment())); } @@ -107,7 +109,7 @@ public function testIndexActionClearButtonWithOneDocumentGoesToClear() $this->assertContains('sureyes', $response->getBody()); $this->assertContains('sureno', $response->getBody()); - $document = new Opus_Document($this->documentId); + $document = Document::get($this->documentId); $this->assertEquals('unpublished', $document->getServerState()); } @@ -129,7 +131,7 @@ public function testClearActionWithOneDocumentUnconfirmed() $this->assertContains('sureyes', $response->getBody()); $this->assertContains('sureno', $response->getBody()); - $document = new Opus_Document($this->documentId); + $document = Document::get($this->documentId); $this->assertEquals('unpublished', $document->getServerState()); } @@ -152,7 +154,7 @@ public function testClearActionWithOneDocumentCanceled() $this->assertNotContains('sureyes', $response->getBody()); $this->assertNotContains('sureno', $response->getBody()); - $document = new Opus_Document($this->documentId); + $document = Document::get($this->documentId); $this->assertEquals('unpublished', $document->getServerState()); } @@ -175,7 +177,7 @@ public function testClearActionWithOneDocumentConfirmed() $this->assertNotContains('sureyes', $response->getBody()); $this->assertNotContains('sureno', $response->getBody()); - $document = new Opus_Document($this->documentId); + $document = Document::get($this->documentId); $this->assertEquals('published', $document->getServerState()); } @@ -197,7 +199,7 @@ public function testRejectActionWithOneDocumentUnconfirmed() $this->assertContains('sureyes', $response->getBody()); $this->assertContains('sureno', $response->getBody()); - $document = new Opus_Document($this->documentId); + $document = Document::get($this->documentId); $this->assertEquals('unpublished', $document->getServerState()); } @@ -220,7 +222,7 @@ public function testRejectActionWithOneDocumentCanceled() $this->assertNotContains('sureyes', $response->getBody()); $this->assertNotContains('sureno', $response->getBody()); - $document = new Opus_Document($this->documentId); + $document = Document::get($this->documentId); $this->assertEquals('unpublished', $document->getServerState()); } @@ -243,7 +245,7 @@ public function testRejectActionWithOneDocumentConfirmed() $this->assertNotContains('sureyes', $response->getBody()); $this->assertNotContains('sureno', $response->getBody()); - $document = new Opus_Document($this->documentId); + $document = Document::get($this->documentId); $this->assertEquals('deleted', $document->getServerState()); } } diff --git a/tests/modules/review/models/ClearDocumentsHelperTest.php b/tests/modules/review/models/ClearDocumentsHelperTest.php index e671b92038..48a315ca09 100644 --- a/tests/modules/review/models/ClearDocumentsHelperTest.php +++ b/tests/modules/review/models/ClearDocumentsHelperTest.php @@ -30,6 +30,10 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Document; +use Opus\Person; +use Opus\Date; + class Review_Model_ClearDocumentsHelperTest extends ControllerTestCase { @@ -48,11 +52,11 @@ public function setUp() $document->setEnrichment([]); $this->documentId = $document->store(); - $document = new Opus_Document($this->documentId); + $document = Document::get($this->documentId); $this->assertEquals(0, count($document->getPersonReferee())); $this->assertEquals(0, count($document->getEnrichment())); - $person = new Opus_Person(); + $person = new Person(); $person->setFirstName('John'); $person->setLastName('Doe'); $this->person = $person; @@ -63,7 +67,7 @@ public function testClearDocument() $helper = new Review_Model_ClearDocumentsHelper(); $helper->clear([$this->documentId], 23, $this->person); - $document = new Opus_Document($this->documentId); + $document = Document::get($this->documentId); $this->assertEquals('published', $document->getServerState()); $this->assertEquals(1, count($document->getPersonReferee())); @@ -80,7 +84,7 @@ public function testClearDocumentWithFile() $filepath = $path . DIRECTORY_SEPARATOR . "foobar.pdf"; touch($filepath); - $document = new Opus_Document($this->documentId); + $document = Document::get($this->documentId); $document->addFile() ->setTempFile($filepath) ->setPathName('foobar.pdf') @@ -90,7 +94,7 @@ public function testClearDocumentWithFile() $helper = new Review_Model_ClearDocumentsHelper(); $helper->clear([$this->documentId], 23, $this->person); - $document = new Opus_Document($this->documentId); + $document = Document::get($this->documentId); $this->assertEquals('published', $document->getServerState()); $this->assertEquals(1, count($document->getPersonReferee())); @@ -104,7 +108,7 @@ public function testRejectDocument() $helper = new Review_Model_ClearDocumentsHelper(); $helper->reject([$this->documentId], 23, $this->person); - $document = new Opus_Document($this->documentId); + $document = Document::get($this->documentId); $this->assertNotEquals('published', $document->getServerState()); $this->assertEquals(1, count($document->getPersonReferee())); @@ -117,7 +121,7 @@ public function testClearInvalidDocument() { $helper = new Review_Model_ClearDocumentsHelper(); - $this->setExpectedException('Opus_Model_NotFoundException'); + $this->setExpectedException('Opus\Model\NotFoundException'); $helper->clear([$this->documentId + 100000], 23); } @@ -125,7 +129,7 @@ public function testRejectInvalidDocument() { $helper = new Review_Model_ClearDocumentsHelper(); - $this->setExpectedException('Opus_Model_NotFoundException'); + $this->setExpectedException('Opus\Model\NotFoundException'); $helper->reject([$this->documentId + 100000], 23); } @@ -134,7 +138,7 @@ public function testClearDocumentWoPerson() $helper = new Review_Model_ClearDocumentsHelper(); $helper->clear([$this->documentId], 23); - $document = new Opus_Document($this->documentId); + $document = Document::get($this->documentId); $this->assertEquals('published', $document->getServerState()); $this->assertEquals(0, count($document->getPersonReferee())); @@ -148,7 +152,7 @@ public function testRejectDocumentWoPerson() $helper = new Review_Model_ClearDocumentsHelper(); $helper->reject([$this->documentId], 23); - $document = new Opus_Document($this->documentId); + $document = Document::get($this->documentId); $this->assertNotEquals('published', $document->getServerState()); $this->assertEquals(0, count($document->getPersonReferee())); @@ -159,13 +163,13 @@ public function testRejectDocumentWoPerson() public function testPublishedDateIsSetIfEmpty() { - $document = new Opus_Document($this->documentId); + $document = Document::get($this->documentId); $this->assertNull($document->getPublishedDate()); $helper = new Review_Model_ClearDocumentsHelper(); $helper->clear([$this->documentId], 23, $this->person); - $document = new Opus_Document($this->documentId); + $document = Document::get($this->documentId); $this->assertEquals('published', $document->getServerState()); $this->assertEquals(1, count($document->getPersonReferee())); @@ -183,16 +187,16 @@ public function testPublishedDateIsSetIfEmpty() public function testPublishedDateIsNotOverwritten() { // set PublishedDate to yesterday - $document = new Opus_Document($this->documentId); + $document = Document::get($this->documentId); $yesterday = new DateTime('yesterday'); - $expectedDate = new Opus_Date($yesterday); + $expectedDate = new Date($yesterday); $document->setPublishedDate($expectedDate); $document->store(); $helper = new Review_Model_ClearDocumentsHelper(); $helper->clear([$this->documentId], 23, $this->person); - $document = new Opus_Document($this->documentId); + $document = Document::get($this->documentId); $this->assertEquals('published', $document->getServerState()); $this->assertEquals(1, count($document->getPersonReferee())); diff --git a/tests/modules/rss/controllers/IndexControllerTest.php b/tests/modules/rss/controllers/IndexControllerTest.php index 578eba2096..080d909ba2 100644 --- a/tests/modules/rss/controllers/IndexControllerTest.php +++ b/tests/modules/rss/controllers/IndexControllerTest.php @@ -31,6 +31,8 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Title; + /** * Class Rss_IndexControllerTest * @@ -62,11 +64,10 @@ public function testUnavailableSolrServerReturns503() $this->requireSolrConfig(); // manipulate solr configuration - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $host = $config->searchengine->index->host; $port = $config->searchengine->index->port; $config->searchengine->index->app = 'solr/corethatdoesnotexist'; - Zend_Registry::set('Zend_Config', $config); $this->dispatch('/rss/index/index/searchtype/all'); $body = $this->getResponse()->getBody(); @@ -91,7 +92,7 @@ public function testSolrIndexIsNotUpToDate() $doc1 = $this->createTestDocument(); $doc1->setServerState('published'); $doc1->setLanguage('eng'); - $title = new Opus_Title(); + $title = new Title(); $title->setValue('test document for OPUSVIER-1726'); $title->setLanguage('eng'); $doc1->setTitleMain($title); @@ -100,37 +101,37 @@ public function testSolrIndexIsNotUpToDate() $doc1->store(); $docId1 = $doc1->getId(); - $date = new Zend_Date($doc1->getServerDatePublished()); - $dateValue1 = $date->get(Zend_Date::RFC_2822); + $date = new \Zend_Date($doc1->getServerDatePublished()); + $dateValue1 = $date->get(\Zend_Date::RFC_2822); $indexer = Opus\Search\Service::selectIndexingService(null, 'solr'); $indexer->addDocumentsToIndex($doc1); // delete document from database - $doc1->deletePermanent(); + $doc1->delete(); sleep(2); // make sure $doc2 do not get the same value for server_date_published $doc2 = $this->createTestDocument(); $doc2->setServerState('published'); $doc2->setLanguage('eng'); - $title = new Opus_Title(); + $title = new Title(); $title->setValue('another test document for OPUSVIER-1726'); $title->setLanguage('eng'); $doc2->setTitleMain($title); $doc2->store(); $docId2 = $doc2->getId(); - $date = new Zend_Date($doc2->getServerDatePublished()); - $dateValue2 = $date->get(Zend_Date::RFC_2822); + $date = new \Zend_Date($doc2->getServerDatePublished()); + $dateValue2 = $date->get(\Zend_Date::RFC_2822); $this->dispatch('/rss/index/index/searchtype/all'); // make search index up to date $indexer->removeDocumentsFromIndexById($docId1); - $doc2->deletePermanent(); + $doc2->delete(); $body = $this->getResponse()->getBody(); $this->assertNotContains("No Opus_Db_Documents with id $docId1 in database.", $body); @@ -183,7 +184,7 @@ public function testOutputWithEmptySearchResult() */ public function testRssLink() { - Zend_Controller_Front::getInstance()->setBaseUrl('opus4dev'); + \Zend_Controller_Front::getInstance()->setBaseUrl('opus4dev'); $this->dispatch('/rss/index/index'); $this->assertXpathContentContains('//link', 'http://opus4dev/frontdoor/index/index/docId/147'); $this->assertXpathContentContains('//link', 'http://opus4dev/frontdoor/index/index/docId/150'); diff --git a/tests/modules/rss/models/FeedTest.php b/tests/modules/rss/models/FeedTest.php index f35308cd0d..f9c8dde181 100644 --- a/tests/modules/rss/models/FeedTest.php +++ b/tests/modules/rss/models/FeedTest.php @@ -44,69 +44,70 @@ public function setUp() { parent::setUp(); - $view = Zend_Registry::get('Opus_View'); + $view = $this->getView(); $this->_model = new Rss_Model_Feed($view); } public function testGetTitle() { - $view = Zend_Registry::get('Opus_View'); - Zend_Controller_Front::getInstance()->setBaseUrl('/opus4test'); + $view = $this->getView(); + \Zend_Controller_Front::getInstance()->setBaseUrl('/opus4test'); $model = new Rss_Model_Feed($view); $this->assertEquals('http:///opus4test', $model->getTitle()); - $config = Zend_Registry::get('Zend_Config'); - - $config->merge(new Zend_Config([ + $this->adjustConfiguration([ 'rss' => ['default' => ['feedTitle' => 'OPUS 4 Test']] - ])); + ]); + + $model->setConfig(null); // reset local reference to configuration + $this->assertEquals('OPUS 4 Test', $model->getTitle()); } public function testGetTitleWithName() { - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'rss' => ['default' => ['feedTitle' => '%1$s']] - ])); + ]); $this->assertEquals('OPUS 4', $this->_model->getTitle()); } public function testGetTitleWithFullUrl() { - $view = Zend_Registry::get('Opus_View'); - Zend_Controller_Front::getInstance()->setBaseUrl('/opus4test'); + $view = $this->getView(); + \Zend_Controller_Front::getInstance()->setBaseUrl('/opus4test'); $model = new Rss_Model_Feed($view); - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'rss' => ['default' => ['feedTitle' => '%4$s']] - ])); + ]); $this->assertEquals('http:///opus4test', $this->_model->getTitle()); } public function testGetTitleWithBaseUrl() { - $view = Zend_Registry::get('Opus_View'); - Zend_Controller_Front::getInstance()->setBaseUrl('/opus4test'); + $view = $this->getView(); + \Zend_Controller_Front::getInstance()->setBaseUrl('/opus4test'); $model = new Rss_Model_Feed($view); - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'rss' => ['default' => ['feedTitle' => '%3$s']] - ])); + ]); $this->assertEquals('opus4test', $model->getTitle()); } public function testGetTitleWithHost() { - $view = Zend_Registry::get('Opus_View'); - Zend_Controller_Front::getInstance()->setBaseUrl('/opus4test'); + $view = $this->getView(); + \Zend_Controller_Front::getInstance()->setBaseUrl('/opus4test'); $view->getHelper('ServerUrl')->setHost('testhost'); $model = new Rss_Model_Feed($view); - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'rss' => ['default' => ['feedTitle' => '%2$s']] - ])); + ]); $this->assertEquals('testhost', $model->getTitle()); } @@ -114,9 +115,11 @@ public function testGetDescription() { $this->assertEquals('OPUS documents', $this->_model->getDescription()); - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'rss' => ['default' => ['feedDescription' => 'Test description.']] - ])); + ]); + + $this->_model->setConfig(null); // reset local reference to configuration $this->assertEquals('Test description.', $this->_model->getDescription()); } diff --git a/tests/modules/setup/controllers/LanguageControllerTest.php b/tests/modules/setup/controllers/LanguageControllerTest.php index 991c8b85d8..91ccce8eb6 100644 --- a/tests/modules/setup/controllers/LanguageControllerTest.php +++ b/tests/modules/setup/controllers/LanguageControllerTest.php @@ -44,7 +44,7 @@ class Setup_LanguageControllerTest extends ControllerTestCase public function tearDown() { - $database = new Opus_Translate_Dao(); + $database = $this->getTranslationManager(); $database->removeAll(); parent::tearDown(); } @@ -55,8 +55,8 @@ public function tearDown() public function testMissingConfigMessageIsDisplayedRed() { $this->markTestSkipped('Needs to be updated for no modules allowed.'); - $config = Zend_Registry::get('Zend_Config'); - $config->merge(new Zend_Config(['setup' => ['translation' => ['modules' => ['allowed' => null]]]])); + + $this->adjustConfiguration(['setup' => ['translation' => ['modules' => ['allowed' => null]]]]); $this->getRequest()->setPost(['Anzeigen' => 'Anzeigen', 'search' => 'test', 'sort' => 'unit']); $this->dispatch('/setup/language/show'); @@ -94,7 +94,7 @@ public function testStoringUpdatedTranslationForKeyWithDashes() $this->dispatch("/setup/language/edit/key/$key"); - $database = new Opus_Translate_Dao(); + $database = $this->getTranslationManager(); $storedTranslations = $database->getTranslation($key); @@ -202,7 +202,7 @@ public function testIndexActionStateAdded() public function testIndexActionScopeKey() { - $dao = new Opus_Translate_Dao(); + $dao = $this->getTranslationManager(); $key1 = 'testentry'; $key2 = 'customkey2'; @@ -226,7 +226,7 @@ public function testIndexActionScopeKey() public function testIndexActionScopeTranslation() { - $dao = new Opus_Translate_Dao(); + $dao = $this->getTranslationManager(); $key1 = 'testentry'; $key2 = 'customkey2'; @@ -363,7 +363,7 @@ public function testAddTranslationCancel() try { $manager->getTranslation('customkey'); - } catch (\Opus\Translate\UnknownTranslationKey $ex) { + } catch (\Opus\Translate\UnknownTranslationKeyException $ex) { $keyFound = false; } @@ -372,7 +372,7 @@ public function testAddTranslationCancel() public function testResetTranslationShowForm() { - $database = new Opus_Translate_Dao(); + $database = $this->getTranslationManager(); $database->setTranslation('default_add', [ 'en' => 'AddEdited', @@ -394,7 +394,7 @@ public function testResetTranslationShowForm() public function testResetTranslationConfirmNo() { - $database = new Opus_Translate_Dao(); + $database = $this->getTranslationManager(); $database->setTranslation('default_add', [ 'en' => 'AddTest', @@ -423,7 +423,7 @@ public function testResetTranslationConfirmNo() public function testResetTranslationConfirmYes() { - $database = new Opus_Translate_Dao(); + $database = $this->getTranslationManager(); $database->setTranslation('default_add', [ 'en' => 'AddTest', @@ -473,7 +473,7 @@ public function testDeleteTranslationShowForm() public function testDeleteTranslationConfirmYes() { - $dao = new Opus_Translate_Dao(); + $dao = $this->getTranslationManager(); $key = 'customtestkey'; @@ -499,7 +499,7 @@ public function testDeleteTranslationConfirmYes() public function testDeleteTranslationConfirmNo() { - $dao = new Opus_Translate_Dao(); + $dao = $this->getTranslationManager(); $key = 'customtestkey'; @@ -540,7 +540,7 @@ public function testDeleteAllShowForm() public function testDeleteAllConfirmYes() { - $database = new Opus_Translate_Dao(); + $database = $this->getTranslationManager(); $database->setTranslation('default_add', [ 'en' => 'CreateTest', @@ -572,7 +572,7 @@ public function testDeleteAllConfirmYes() public function testDeleteAllConfirmYesMatchingEntriesOnly() { - $database = new Opus_Translate_Dao(); + $database = $this->getTranslationManager(); $database->setTranslation('default_add', [ 'en' => 'CreateTest', @@ -603,7 +603,7 @@ public function testDeleteAllConfirmYesMatchingEntriesOnly() public function testDeleteAllConfirmNo() { - $dao = new Opus_Translate_Dao(); + $dao = $this->getTranslationManager(); $key = 'customtestkey'; @@ -691,7 +691,7 @@ public function testEditInvalidExistingKey() public function testChangeNameOfAddedKey() { - $database = new Opus_Translate_Dao(); + $database = $this->getTranslationManager(); $oldKey = 'customkey'; $newKey = 'renamedkey'; @@ -727,7 +727,7 @@ public function testChangeNameOfAddedKey() public function testChangeModuleOfAddedKey() { - $dao = new Opus_Translate_Dao(); + $dao = $this->getTranslationManager(); $key = 'customtestkey'; @@ -790,7 +790,7 @@ public function testExportShowPage() public function testExportFiltered() { - $dao = new Opus_Translate_Dao(); + $dao = $this->getTranslationManager(); $dao->setTranslation('customtestkey', [ 'en' => 'English', @@ -822,7 +822,7 @@ public function testExportFilteredWithUnmodified() public function testExportAll() { - $dao = new Opus_Translate_Dao(); + $dao = $this->getTranslationManager(); $dao->setTranslation('testkey1', [ 'en' => 'Test key 1', @@ -849,7 +849,7 @@ public function testExportAll() public function testExportAllWithUnmodified() { - $dao = new Opus_Translate_Dao(); + $dao = $this->getTranslationManager(); $dao->setTranslation('testkey1', [ 'en' => 'Test key 1', @@ -885,11 +885,11 @@ public function testImportFile() } /** - * @return Opus_Database_Dao + * @return \Opus\Translate\Dao * TODO really use translation manager (be independent of database) */ protected function getTranslationManager() { - return new Opus_Translate_Dao(); + return new \Opus\Translate\Dao(); } } diff --git a/tests/modules/setup/forms/FaqItemTest.php b/tests/modules/setup/forms/FaqItemTest.php index 209494a9b7..5bdef3d801 100644 --- a/tests/modules/setup/forms/FaqItemTest.php +++ b/tests/modules/setup/forms/FaqItemTest.php @@ -31,6 +31,8 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Translate\Dao; + class Setup_Form_FaqItemTest extends ControllerTestCase { @@ -40,13 +42,13 @@ public function setUp() { parent::setUp(); - $translations = new Opus_Translate_Dao(); + $translations = new Dao(); $translations->removeAll(); } public function tearDown() { - $translations = new Opus_Translate_Dao(); + $translations = new Dao(); $translations->removeAll(); parent::tearDown(); @@ -73,7 +75,7 @@ public function testUpdatingContact() $form->updateEntry(); - $translations = new Opus_Translate_Dao(); + $translations = new Dao(); $this->assertEquals( $content, @@ -97,7 +99,7 @@ public function testUpdatingImprint() $form->updateEntry(); - $translations = new Opus_Translate_Dao(); + $translations = new Dao(); $this->assertEquals( $content, diff --git a/tests/modules/setup/forms/HomePageTest.php b/tests/modules/setup/forms/HomePageTest.php new file mode 100644 index 0000000000..960d27165f --- /dev/null +++ b/tests/modules/setup/forms/HomePageTest.php @@ -0,0 +1,107 @@ + + * @copyright Copyright (c) 2021, OPUS 4 development team + * @license http://www.gnu.org/licenses/gpl.html General Public License + */ + +class Setup_Form_HomePageTest extends ControllerTestCase +{ + + protected $additionalResources = 'Translation'; + + private $database; + + public function setUp() + { + parent::setUp(); + + $this->database = new \Opus\Translate\Dao(); + $this->database->removeAll(); + } + + public function tearDown() + { + $this->database->removeAll(); + $translate = Application_Translate::getInstance(); + $translate->clearCache(); + \Zend_Translate::clearCache(); + + parent::tearDown(); + } + + public function testInit() + { + $form = new Setup_Form_HomePage(); + + $element = $form->getElement('home_index_index_pagetitle'); + $this->assertNotNull($element); + $this->assertEquals([ + 'en' => 'Home', + 'de' => 'Einstieg' + ], $element->getValue()); + } + + public function testUpdatingTranslations() + { + $key = 'home_index_index_pagetitle'; + + $this->database->setTranslation($key, [ + 'en' => 'TestHome', + 'de' => 'TestEinstieg' + ], null); + + $translations = $this->database->getTranslationsWithModules(); + + $this->assertCount(1, $translations); + $this->assertArrayHasKey($key, $translations); + $this->assertEmpty($translations[$key]['module']); + + $form = new Setup_Form_HomePage(); + + $element = $form->getElement($key); + + $change = [ + 'en' => 'Homepage', + 'de' => 'Startseite' + ]; + + $element->setValue($change); + + $form->updateTranslations(); + + $database = $this->database; + + $translations = $database->getTranslationsWithModules(); + + $this->assertCount(1, $translations); + $this->assertArrayHasKey($key, $translations); + $this->assertEquals('home', $translations[$key]['module']); + } +} diff --git a/tests/modules/setup/forms/ImprintPageTest.php b/tests/modules/setup/forms/ImprintPageTest.php index aab2238e89..954019ac3b 100644 --- a/tests/modules/setup/forms/ImprintPageTest.php +++ b/tests/modules/setup/forms/ImprintPageTest.php @@ -40,6 +40,9 @@ class Setup_Form_ImprintPageTest extends ControllerTestCase public function testInit() { + $database = new \Opus\Translate\Dao(); + $database->removeAll(); + $form = new Setup_Form_ImprintPage(); $element = $form->getElement('home_index_imprint_pagetitle'); diff --git a/tests/modules/setup/forms/TranslationTest.php b/tests/modules/setup/forms/TranslationTest.php index 95dd1f0728..9be5049cb9 100644 --- a/tests/modules/setup/forms/TranslationTest.php +++ b/tests/modules/setup/forms/TranslationTest.php @@ -40,7 +40,7 @@ class Setup_Form_TranslationTest extends ControllerTestCase public function tearDown() { - $database = new Opus_Translate_Dao(); + $database = new \Opus\Translate\Dao(); $database->removeAll(); parent::tearDown(); // TODO: Change the autogenerated stub @@ -198,13 +198,13 @@ public function testIsValidDuplicateKey() $key = 'testkey835'; - $database = new Opus_Translate_Dao(); + $database = new \Opus\Translate\Dao(); $database->setTranslation($key, [ 'en' => 'English', 'de' => 'Deutsch' ], 'admin'); - $translate = Zend_Registry::get('Zend_Translate'); + $translate = Application_Translate::getInstance(); $translate->loadDatabase(true); $this->assertFalse($form->isValid([ @@ -242,7 +242,7 @@ public function testPopulateFromKeyAddedKey() $key = 'testkey123'; - $database = new Opus_Translate_Dao(); + $database = new \Opus\Translate\Dao(); $database->setTranslation($key, [ 'en' => 'English', 'de' => 'Deutsch' @@ -261,7 +261,7 @@ public function testPopulateFromKeyAddedKey() } /** - * @expectedException \Opus\Translate\UnknownTranslationKey + * @expectedException \Opus\Translate\UnknownTranslationKeyException * @expectedExceptionMessage unknownKey789 */ public function testPopulateFromKeyUnknownKey() @@ -337,7 +337,7 @@ public function testUpdateModuleOfAddedKey() { $form = $this->getForm(); - $dao = new Opus_Translate_Dao(); + $dao = new \Opus\Translate\Dao(); $key = 'newkey1'; @@ -365,7 +365,7 @@ public function testUpdateNameOfAddedKey() { $form = $this->getForm(); - $dao = new Opus_Translate_Dao(); + $dao = new \Opus\Translate\Dao(); $oldKey = 'oldkey1'; $newKey = 'newkey2'; @@ -388,7 +388,7 @@ public function testUpdateNameOfAddedKey() $failed = true; try { $translation = $manager->getTranslation($oldKey); - } catch (\Opus\Translate\UnknownTranslationKey $ex) { + } catch (\Opus\Translate\UnknownTranslationKeyException $ex) { $failed = false; } if ($failed) { @@ -411,7 +411,7 @@ public function testUpdateNameOfAddedKey() public function testUpdateManuallyToOriginal() { $manager = new Application_Translate_TranslationManager(); - $dao = new Opus_Translate_Dao(); + $dao = new \Opus\Translate\Dao(); $key = 'default_add'; diff --git a/tests/modules/setup/forms/TranslationValuesTest.php b/tests/modules/setup/forms/TranslationValuesTest.php index cee4b77b82..2b52670a6d 100644 --- a/tests/modules/setup/forms/TranslationValuesTest.php +++ b/tests/modules/setup/forms/TranslationValuesTest.php @@ -47,7 +47,7 @@ public function testInit() $elements = $form->getElements(); - $this->assertEquals(count($languages), count($elements)); + $this->assertSameSize($languages, $elements); } public function testPopulate() diff --git a/tests/modules/setup/forms/Validate/TranslationKeyFormatTest.php b/tests/modules/setup/forms/Validate/TranslationKeyFormatTest.php index 7f48294ff6..5835b17dbb 100644 --- a/tests/modules/setup/forms/Validate/TranslationKeyFormatTest.php +++ b/tests/modules/setup/forms/Validate/TranslationKeyFormatTest.php @@ -64,7 +64,7 @@ public function testIsValid($value, $result) public function testMessagesTranslated() { $validator = new Setup_Form_Validate_TranslationKeyFormat(); - $translate = Zend_Registry::get('Zend_Translate'); + $translate = Application_Translate::getInstance(); $messageTemplates = $validator->getMessageTemplates(); $key = $messageTemplates[$validator::NOT_MATCH]; $this->assertTrue($translate->isTranslated($key)); diff --git a/tests/modules/solrsearch/controllers/BrowseControllerTest.php b/tests/modules/solrsearch/controllers/BrowseControllerTest.php index 72153ac7c2..6b3e6d33c3 100644 --- a/tests/modules/solrsearch/controllers/BrowseControllerTest.php +++ b/tests/modules/solrsearch/controllers/BrowseControllerTest.php @@ -33,6 +33,8 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Series; + /** * Class Solrsearch_BrowseControllerTest. * @@ -95,7 +97,7 @@ public function testSeriesActionWithOneVisibleSeriesWithoutAnyPublishedDocument( $d->setServerState('unpublished'); $d->store(); - $s = new Opus_Series(7); + $s = new Series(7); $s->setVisible('1'); $s->store(); @@ -118,7 +120,7 @@ public function testSeriesActionWithOneVisibleSeriesWithOnePublishedDocument() $d->setServerState('published'); $d->store(); - $s = new Opus_Series(7); + $s = new Series(7); $s->setVisible('1'); $s->store(); @@ -130,7 +132,7 @@ public function testSeriesActionWithOneVisibleSeriesWithOnePublishedDocument() $this->restoreSeriesVisibility($visibilities); $this->assertContains('/solrsearch/index/search/searchtype/series/id/7', $this->getResponse()->getBody()); - foreach (Opus_Series::getAll() as $series) { + foreach (Series::getAll() as $series) { if ($series->getId() != 7) { $this->assertNotContains('/solrsearch/index/search/searchtype/series/id/' . $series->getId(), $this->getResponse()->getBody()); } @@ -141,7 +143,7 @@ public function testSeriesActionWithOneVisibleSeriesWithOnePublishedDocument() private function setAllSeriesToUnvisible() { $visibilities = []; - foreach (Opus_Series::getAll() as $seriesItem) { + foreach (Series::getAll() as $seriesItem) { $visibilities[$seriesItem->getId()] = $seriesItem->getVisible(); $seriesItem->setVisible(0); $seriesItem->store(); @@ -151,7 +153,7 @@ private function setAllSeriesToUnvisible() private function restoreSeriesVisibility($visibilities) { - foreach (Opus_Series::getAll() as $seriesItem) { + foreach (Series::getAll() as $seriesItem) { $seriesItem->setVisible($visibilities[$seriesItem->getId()]); $seriesItem->store(); } @@ -175,7 +177,7 @@ public function testSeriesActionRespectsSeriesSortOrderAfterManipulation() $sortOrders = $this->getSortOrders(); // reverse ordering of series - foreach (Opus_Series::getAll() as $seriesItem) { + foreach (Series::getAll() as $seriesItem) { $seriesItem->setSortOrder(10 - intval($sortOrders[$seriesItem->getId()])); $seriesItem->store(); } @@ -197,11 +199,11 @@ public function testSeriesActionRespectsSeriesSortOrderIfItCoincidesBetweenTwoSe { $sortOrders = $this->getSortOrders(); - $s = new Opus_Series(2); + $s = new Series(2); $s->setSortOrder(6); $s->store(); - $s = new Opus_Series(6); + $s = new Series(6); $s->setSortOrder(0); $s->store(); @@ -221,7 +223,7 @@ public function testSeriesActionRespectsSeriesSortOrderIfItCoincidesBetweenTwoSe private function getSortOrders() { $sortOrders = []; - foreach (Opus_Series::getAll() as $seriesItem) { + foreach (Series::getAll() as $seriesItem) { $sortOrders[$seriesItem->getId()] = $seriesItem->getSortOrder(); } return $sortOrders; @@ -229,7 +231,7 @@ private function getSortOrders() private function setSortOrders($sortOrders) { - foreach (Opus_Series::getAll() as $seriesItem) { + foreach (Series::getAll() as $seriesItem) { $seriesItem->setSortOrder($sortOrders[$seriesItem->getId()]); $seriesItem->store(); } diff --git a/tests/modules/solrsearch/controllers/IndexControllerTest.php b/tests/modules/solrsearch/controllers/IndexControllerTest.php index 03f933fb50..51080017ca 100644 --- a/tests/modules/solrsearch/controllers/IndexControllerTest.php +++ b/tests/modules/solrsearch/controllers/IndexControllerTest.php @@ -34,6 +34,14 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\CollectionRole; +use Opus\Date; +use Opus\Identifier; +use Opus\Person; +use Opus\Security\Realm; +use Opus\Subject; +use Opus\Title; + /** * Class Solrsearch_IndexControllerTest. * @@ -326,11 +334,11 @@ public function testPaginationBarContainsOverallNumberOfHitsInDoctypeBrowsing() */ public function testLastPageUrlEqualsNextPageUrlDocTypeArticle() { - $docFinder = new Opus_DocumentFinder(); - $docFinder->setType('article')->setServerState('published'); + $docFinder = $this->getDocumentFinder(); + $docFinder->setDocumentType('article')->setServerState('published'); // check if test requirements are met - $docCount = $docFinder->count(); + $docCount = $docFinder->getCount(); $this->assertGreaterThan(10, $docCount, "Test requires at least 11 documents."); @@ -652,12 +660,11 @@ public function testUnavailableSolrServerReturns503() $this->requireSolrConfig(); // manipulate solr configuration - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $host = $config->searchengine->solr->default->service->default->endpoint->localhost->host; $port = $config->searchengine->solr->default->service->default->endpoint->localhost->port; $config->searchengine->solr->default->service->default->endpoint->localhost->path = '/solr/corethatdoesnotexist'; - Zend_Registry::set('Zend_Config', $config); $this->dispatch('/solrsearch/browse/doctypes'); @@ -678,12 +685,12 @@ public function testCatchAllSearchConsidersIdentifiers() $doc = $this->createTestDocument(); $doc->setServerState('published'); $doc->setLanguage('eng'); - $title = new Opus_Title(); + $title = new Title(); $title->setValue('test document for OPUSVIER-2475'); $title->setLanguage('eng'); $doc->setTitleMain($title); - $id = new Opus_Identifier(); + $id = new Identifier(); $field = $id->getField('Type'); $identifierTypes = array_keys($field->getDefault()); @@ -733,12 +740,12 @@ public function testCatchAllSearchConsidersAllPersons($lastName, $role, $contain $doc = $this->createTestDocument(); $doc->setServerState('published'); $doc->setLanguage('eng'); - $title = new Opus_Title(); + $title = new Title(); $title->setValue('test document for OPUSVIER-2484'); $title->setLanguage('eng'); $doc->setTitleMain($title); - $person = new Opus_Person(); + $person = new Person(); $person->setLastName($lastName); $personLink = $doc->addPerson($person); $personLink->setRole($role); @@ -759,7 +766,7 @@ public function testCatchAllSearchConsidersAllPersons($lastName, $role, $contain public function testFacetLimitWithDefaultSetting() { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $numOfSubjects = 20; $this->addSampleDocWithMultipleSubjects($numOfSubjects); @@ -784,7 +791,7 @@ public function testFacetLimitWithDefaultSetting() public function testFacetLimitWithGlobalSetting() { // manipulate application configuration - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $config->search->facet->default->limit = '5'; $numOfSubjects = 10; @@ -802,38 +809,21 @@ public function testFacetLimitWithGlobalSetting() public function testFacetLimitWithLocalSettingForSubjectFacet() { - // manipulate application configuration - $config = Zend_Registry::get('Zend_Config'); - $limit = null; - $oldConfig = null; - if (isset($config->searchengine->solr->facetlimit->subject)) { - $limit = $config->searchengine->solr->facetlimit->subject; - } else { - $config = new Zend_Config([ - 'searchengine' => [ - 'solr' => [ - 'facetlimit' => [ - 'subject' => '5']]]], true); - $oldConfig = Zend_Registry::get('Zend_Config'); - // Include the above made configuration changes in the application configuration. - $config->merge(Zend_Registry::get('Zend_Config')); - } - Zend_Registry::set('Zend_Config', $config); + $this->adjustConfiguration([ + 'searchengine' => [ + 'solr' => [ + 'facetlimit' => [ + 'subject' => '5' + ] + ] + ] + ]); $numOfSubjects = 10; $this->addSampleDocWithMultipleSubjects($numOfSubjects); $this->dispatch('/solrsearch/index/search/searchtype/simple/query/facetlimittestwithsubjects-opusvier2610'); - // undo configuration manipulation - $config = Zend_Registry::get('Zend_Config'); - if (! is_null($oldConfig)) { - $config = $oldConfig; - } else { - $config->searchengine->solr->facetlimit->subject = $limit; - } - Zend_Registry::set('Zend_Config', $config); - for ($index = 0; $index < 5; $index++) { $this->assertContains('/solrsearch/index/search/searchtype/simple/query/facetlimittestwithsubjects-opusvier2610/start/0/rows/10/subjectfq/subject0' . $index, $this->getResponse()->getBody()); } @@ -858,13 +848,13 @@ private function addSampleDocWithMultipleSubjects($numOfSubjects = 0) $doc = $this->createTestDocument(); $doc->setServerState('published'); $doc->setLanguage('eng'); - $title = new Opus_Title(); + $title = new Title(); $title->setValue('facetlimittestwithsubjects-opusvier2610'); $title->setLanguage('eng'); $doc->addTitleMain($title); for ($index = 0; $index < $numOfSubjects; $index++) { - $subject = new Opus_Subject(); + $subject = new Subject(); if ($index < 10) { $subject->setValue('subject' . '0' . $index); } else { @@ -881,28 +871,19 @@ private function addSampleDocWithMultipleSubjects($numOfSubjects = 0) public function testFacetSortLexicographicallyForInstituteFacet() { - // manipulate application configuration - $oldConfig = Zend_Registry::get('Zend_Config'); - - $config = Zend_Registry::get('Zend_Config'); - if (isset($config->searchengine->solr->sortcrit->institute)) { - $config->searchengine->solr->sortcrit->institute = 'lexi'; - } else { - $config = new Zend_Config([ - 'searchengine' => [ - 'solr' => [ - 'sortcrit' => [ - 'institute' => 'lexi']]]], true); - $oldConfig = Zend_Registry::get('Zend_Config'); - // Include the above made configuration changes in the application configuration. - $config->merge(Zend_Registry::get('Zend_Config')); - } - Zend_Registry::set('Zend_Config', $config); + $this->adjustConfiguration([ + 'searchengine' => [ + 'solr' => [ + 'sortcrit' => [ + 'institute' => 'lexi' + ] + ] + ] + ]); $this->dispatch('/solrsearch/index/search/searchtype/all'); - // undo configuration manipulation - Zend_Registry::set('Zend_Config', $oldConfig); + $this->resetConfiguration(); $searchStrings = [ 'Abwasserwirtschaft und Gewässerschutz B-2', @@ -936,13 +917,13 @@ public function testFacetSortLexicographicallyForInstituteFacet() public function testFacetSortForYearInverted() { - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'search' => ['facet' => ['year' => [ 'sort' => 'lexi', 'indexField' => 'published_year_inverted' ]]], 'searchengine' => ['solr' => ['facets' => 'year,doctype,author_facet,language,has_fulltext,belongs_to_bibliography,subject,institute']] - ])); + ]); $this->dispatch('/solrsearch/index/search/searchtype/all'); @@ -1027,7 +1008,7 @@ public function testSortOrderOfDocumentsInBrowsing() { $olderDoc = $this->createTestDocument(); $olderDoc->setServerState('published'); - $date = new Opus_Date(); + $date = new Date(); $date->setNow(); $date->setDay($date->getDay() - 1); $olderDoc->setServerDatePublished($date); @@ -1063,13 +1044,13 @@ public function testSortOrderOfDocumentsInBrowsingWithSortfield() $olderDoc = $this->createTestDocument(); $olderDoc->setServerState('published'); $olderDoc->setLanguage('eng'); - $date = new Opus_Date(); + $date = new Date(); $date->setNow(); $date->setDay($date->getDay() - 1); $olderDoc->setServerDatePublished($date); $olderDoc->setType('article'); - $title = new Opus_Title(); + $title = new Title(); $title->setValue('zzzOlderDoc'); // 'zzz' to show the document at the first page $title->setLanguage('eng'); $olderDoc->addTitleMain($title); @@ -1079,7 +1060,7 @@ public function testSortOrderOfDocumentsInBrowsingWithSortfield() $newerDoc->setServerState('published'); $newerDoc->setLanguage('eng'); $newerDoc->setType('article'); - $title = new Opus_Title(); + $title = new Title(); $title->setValue('zzzNewerDoc'); $title->setLanguage('eng'); $newerDoc->addTitleMain($title); @@ -1142,12 +1123,12 @@ public function testAuthorFacetClosed() public function testFacetExtenderWithVariousConfigFacetLimits() { $this->useEnglish(); - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'search' => ['facet' => [ 'author_facet' => ['limit' => '3'], 'year' => ['limit' => '15'] ]] - ])); + ]); $this->dispatch('/solrsearch/index/search/searchtype/all/'); $this->assertQueryContentContains("//div[@id='author_facet_facet']/div/a", ' + more'); $this->assertQueryContentContains("//div[@id='year_facet']/div/a", ' + more'); @@ -1248,10 +1229,10 @@ public function testXmlExportButtonPresentForAdminInLatestSearch() $this->enableSecurity(); $this->loginUser('admin', 'adminadmin'); - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'export' => ['stylesheet' => ['search' => 'example']], 'searchengine' => ['solr' => ['numberOfDefaultSearchResults' => '10']] - ])); + ]); $this->dispatch('/solrsearch/index/search/searchtype/latest'); $this->assertQuery('//a[@href="/solrsearch/index/search/searchtype/latest/rows/10/export/xml/stylesheet/example"]'); @@ -1263,18 +1244,15 @@ public function testXmlExportButtonPresentForAdminInLatestSearch() public function testXmlExportButtonNotPresentForGuest() { $this->enableSecurity(); - $config = Zend_Registry::get('Zend_Config'); - $config->merge(new Zend_Config(['export' => ['stylesheet' => ['search' => 'example']]])); + $this->adjustConfiguration(['export' => ['stylesheet' => ['search' => 'example']]]); $this->dispatch('/solrsearch/index/search/searchtype/all'); - $this->assertFalse(Opus_Security_Realm::getInstance()->checkModule('export')); + $this->assertFalse(Realm::getInstance()->checkModule('export')); $this->assertNotQuery('//a[@href="/solrsearch/index/search/searchtype/all/export/xml/stylesheet/example"]'); } public function testDisableEmptyCollectionsTrue() { - Zend_Registry::get('Zend_Config')->merge( - new Zend_Config(['browsing' => ['disableEmptyCollections' => self::CONFIG_VALUE_TRUE]]) - ); + $this->adjustConfiguration(['browsing' => ['disableEmptyCollections' => self::CONFIG_VALUE_TRUE]]); $this->dispatch('/solrsearch/index/search/searchtype/collection/id/2'); @@ -1287,9 +1265,7 @@ public function testDisableEmptyCollectionsTrue() public function testDisableEmptyCollectionsFalse() { - Zend_Registry::get('Zend_Config')->merge( - new Zend_Config(['browsing' => ['disableEmptyCollections' => self::CONFIG_VALUE_FALSE]]) - ); + $this->adjustConfiguration(['browsing' => ['disableEmptyCollections' => self::CONFIG_VALUE_FALSE]]); $this->dispatch('/solrsearch/index/search/searchtype/collection/id/2'); @@ -1306,7 +1282,7 @@ public function testDisableEmptyCollectionsFalse() public function testEnableHideEmptyCollectionsForCollectionRoleMSC() { - $collRole = Opus_CollectionRole::fetchByName('msc'); + $collRole = CollectionRole::fetchByName('msc'); $hideEmptyCollections = $collRole->getHideEmptyCollections(); $collRole->setHideEmptyCollections(1); $collRole->store(); @@ -1322,7 +1298,7 @@ public function testEnableHideEmptyCollectionsForCollectionRoleMSC() public function testDisableHideEmptyCollectionsForCollectionRoleMSC() { - $collRole = Opus_CollectionRole::fetchByName('msc'); + $collRole = CollectionRole::fetchByName('msc'); $hideEmptyCollections = $collRole->getHideEmptyCollections(); $collRole->setHideEmptyCollections(0); $collRole->store(); @@ -1436,4 +1412,17 @@ public function testAuthorSearchLinks() '//div[@class = "results_author"]/a[contains(@href, "solrsearch/index/search/searchtype/authorsearch/author/Doe%2C+John")]' ); } + + public function testServerStateFacetForAdmins() + { + $this->enableSecurity(); + $this->loginUser('admin', 'adminadmin'); + + $this->dispatch('/solrsearch/index/search/searchtype/all'); + + $this->assertXpath('//div[@id = "server_state_facet"]'); + $this->assertXpath('//div[@id = "server_state_facet"]//a[contains(@href, "server_statefq/published")]'); + $this->assertXpath('//div[@id = "server_state_facet"]//a[contains(@href, "server_statefq/unpublished")]'); + $this->assertXpath('//div[@id = "server_state_facet"]//a[contains(@href, "server_statefq/deleted")]'); + } } diff --git a/tests/modules/solrsearch/models/CollectionListTest.php b/tests/modules/solrsearch/models/CollectionListTest.php index f52d70e858..d662e5c4e2 100644 --- a/tests/modules/solrsearch/models/CollectionListTest.php +++ b/tests/modules/solrsearch/models/CollectionListTest.php @@ -31,6 +31,9 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\CollectionRole; +use Opus\Model\ModelException; + class Solrsearch_Model_CollectionListTest extends ControllerTestCase { @@ -225,12 +228,12 @@ public function testCollectionRoleTitle() /** * Teste das Ausblenden von leeren Sammlungen am Beispiel der MSC. * - * @throws Opus_Model_Exception + * @throws ModelException * @throws Solrsearch_Model_Exception */ public function testGetChildrenWithoutEmptyCollections() { - $collRole = Opus_CollectionRole::fetchByName('msc'); + $collRole = CollectionRole::fetchByName('msc'); $hideEmptyCollections = $collRole->getHideEmptyCollections(); $collRole->setHideEmptyCollections(1); $collRole->store(); @@ -251,7 +254,7 @@ public function testGetChildrenWithoutEmptyCollections() private function getCollectionRole($collectionRoleId) { - $collectionRole = new Opus_CollectionRole($collectionRoleId); + $collectionRole = new CollectionRole($collectionRoleId); $this->assertNotNull($collectionRole); $this->assertEquals('1', $collectionRole->getVisible()); $this->assertEquals('1', $collectionRole->getVisibleBrowsingStart()); diff --git a/tests/modules/solrsearch/models/CollectionRolesTest.php b/tests/modules/solrsearch/models/CollectionRolesTest.php index 63ae989e0a..4e4c9d12a4 100644 --- a/tests/modules/solrsearch/models/CollectionRolesTest.php +++ b/tests/modules/solrsearch/models/CollectionRolesTest.php @@ -31,6 +31,8 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\CollectionRole; + class Solrsearch_Model_CollectionRolesTest extends ControllerTestCase { @@ -50,7 +52,7 @@ public function testHasVisibleChildrenForEmptyCollectionRole() $class = new ReflectionClass('Solrsearch_Model_CollectionRoles'); $method = $class->getMethod('hasVisibleChildren'); $method->setAccessible(true); - $hasChildren = $method->invokeArgs($collectionRoles, [new Opus_CollectionRole(17)]); + $hasChildren = $method->invokeArgs($collectionRoles, [new CollectionRole(17)]); $this->assertFalse($hasChildren); } @@ -62,7 +64,7 @@ public function testHasVisibleChildrenForNonEmptyCollectionRole() $class = new ReflectionClass('Solrsearch_Model_CollectionRoles'); $method = $class->getMethod('hasVisibleChildren'); $method->setAccessible(true); - $hasChildren = $method->invokeArgs($collectionRoles, [new Opus_CollectionRole(7)]); + $hasChildren = $method->invokeArgs($collectionRoles, [new CollectionRole(7)]); $this->assertTrue($hasChildren); } @@ -74,7 +76,7 @@ public function testHasPublishedDocsForEmptyCollectionRole() $class = new ReflectionClass('Solrsearch_Model_CollectionRoles'); $method = $class->getMethod('hasPublishedDocs'); $method->setAccessible(true); - $hasChildren = $method->invokeArgs($collectionRoles, [new Opus_CollectionRole(17)]); + $hasChildren = $method->invokeArgs($collectionRoles, [new CollectionRole(17)]); $this->assertFalse($hasChildren); } @@ -86,7 +88,7 @@ public function testHasPublishedDocsForNonEmptyCollectionRoleWithoutPublishedDoc $class = new ReflectionClass('Solrsearch_Model_CollectionRoles'); $method = $class->getMethod('hasPublishedDocs'); $method->setAccessible(true); - $hasChildren = $method->invokeArgs($collectionRoles, [new Opus_CollectionRole(7)]); + $hasChildren = $method->invokeArgs($collectionRoles, [new CollectionRole(7)]); $this->assertFalse($hasChildren); } @@ -98,7 +100,7 @@ public function testHasPublishedDocsForNonEmptyCollectionRoleWithPublishedDocs() $class = new ReflectionClass('Solrsearch_Model_CollectionRoles'); $method = $class->getMethod('hasPublishedDocs'); $method->setAccessible(true); - $hasChildren = $method->invokeArgs($collectionRoles, [new Opus_CollectionRole(5)]); + $hasChildren = $method->invokeArgs($collectionRoles, [new CollectionRole(5)]); $this->assertTrue($hasChildren); } diff --git a/tests/modules/solrsearch/models/ExceptionTest.php b/tests/modules/solrsearch/models/ExceptionTest.php index 59895d3de5..2fb19a6573 100644 --- a/tests/modules/solrsearch/models/ExceptionTest.php +++ b/tests/modules/solrsearch/models/ExceptionTest.php @@ -29,7 +29,6 @@ * @author Sascha Szott * @copyright Copyright (c) 2008-2010, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id$ */ class Solrsearch_Model_ExceptionTest extends ControllerTestCase diff --git a/tests/modules/solrsearch/models/FacetMenuTest.php b/tests/modules/solrsearch/models/FacetMenuTest.php index e8b39c4ae7..a33ad0a931 100644 --- a/tests/modules/solrsearch/models/FacetMenuTest.php +++ b/tests/modules/solrsearch/models/FacetMenuTest.php @@ -44,17 +44,17 @@ class Solrsearch_Model_FacetMenuTest extends ControllerTestCase */ public function testGetFacetLimitsFromConfig() { - $config = Zend_Registry::get('Zend_Config'); - $config->merge(new Zend_Config(['searchengine' => - ['solr' => - ['facetlimit' => - [ + + $this->adjustConfiguration([ + 'searchengine' => [ + 'solr' => [ + 'facetlimit' => [ 'author_facet' => '3', 'year' => '15' ] ] ] - ])); + ]); $facetLimits = Opus\Search\Config::getFacetLimits(); @@ -72,27 +72,28 @@ public function testGetFacetLimitsFromConfig() */ public function testGetFacetLimitsFromConfigWithYearInverted() { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); if (isset($config->searchengine->solr->facets)) { $config->searchengine->solr->facets = 'year,doctype,author_facet,language,has_fulltext,belongs_to_bibliography,subject,institute'; } else { - $testConfig = new Zend_Config([ + $this->adjustConfiguration([ 'searchengine' => [ 'solr' => [ - 'facets' => 'year,doctype,author_facet,language,has_fulltext,belongs_to_bibliography,subject,institute']]], true); - // Include the above made configuration changes in the application configuration. - $testConfig->merge($config); + 'facets' => 'year,doctype,author_facet,language,has_fulltext,belongs_to_bibliography,subject,institute' + ] + ] + ]); } - $config->merge(new Zend_Config(['searchengine' => - ['solr' => - ['facetlimit' => - [ + $this->adjustConfiguration([ + 'searchengine' => [ + 'solr' => [ + 'facetlimit' => [ 'author_facet' => '3', 'year' => '15' ] ] ] - ])); + ]); $facetLimits = Opus\Search\Config::getFacetLimits(); @@ -130,17 +131,21 @@ public function testBuildFacetArray() public function testBuildFacetArrayWithYearInverted() { $model = new Solrsearch_Model_FacetMenu(); - $config = Zend_Registry::get('Zend_Config'); + + $config = $this->getConfig(); + if (isset($config->searchengine->solr->facets)) { $config->searchengine->solr->facets = 'year_inverted,doctype,author_facet,language,has_fulltext,belongs_to_bibliography,subject,institute'; } else { - $testConfig = new Zend_Config([ + $this->adjustConfiguration([ 'searchengine' => [ 'solr' => [ - 'facets' => 'year_inverted,doctype,author_facet,language,has_fulltext,belongs_to_bibliography,subject,institute']]], true); - // Include the above made configuration changes in the application configuration. - $testConfig->merge($config); + 'facets' => 'year_inverted,doctype,author_facet,language,has_fulltext,belongs_to_bibliography,subject,institute' + ] + ] + ]); } + $paramSet = ['facetNumber_year' => 'all']; $facetArray = $model->buildFacetArray($paramSet); $this->assertEquals(10000, $facetArray['year']); diff --git a/tests/modules/solrsearch/models/PaginationUtilTest.php b/tests/modules/solrsearch/models/PaginationUtilTest.php index d9fb56bcea..e7af6a9aba 100644 --- a/tests/modules/solrsearch/models/PaginationUtilTest.php +++ b/tests/modules/solrsearch/models/PaginationUtilTest.php @@ -29,7 +29,6 @@ * @author Julian Heise * @copyright Copyright (c) 2008-2010, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id$ */ class Solrsearch_Model_PaginationUtilTest extends ControllerTestCase diff --git a/tests/modules/solrsearch/models/SearchTest.php b/tests/modules/solrsearch/models/SearchTest.php index 5a9dc7cac2..21b9223b4f 100644 --- a/tests/modules/solrsearch/models/SearchTest.php +++ b/tests/modules/solrsearch/models/SearchTest.php @@ -124,9 +124,9 @@ public function testCreateSimpleSearchUrlParamsWithCustomRows() { $request = $this->getRequest(); - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'searchengine' => ['solr' => ['numberOfDefaultSearchResults' => '25']] - ])); + ]); $model = new Solrsearch_Model_Search(); diff --git a/tests/modules/solrsearch/models/SeriesTest.php b/tests/modules/solrsearch/models/SeriesTest.php index 9062b5c996..f56c0f3254 100644 --- a/tests/modules/solrsearch/models/SeriesTest.php +++ b/tests/modules/solrsearch/models/SeriesTest.php @@ -32,6 +32,8 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Series; + class Solrsearch_Model_SeriesTest extends ControllerTestCase { @@ -65,7 +67,7 @@ public function testConstructWithNonEmptyVisibleSeries() { $series = new Solrsearch_Model_Series(1); $this->assertNotNull($series); - $seriesFramework = new Opus_Series(1); + $seriesFramework = new Series(1); $this->assertEquals($seriesFramework->getId(), $series->getId()); $this->assertEquals($seriesFramework->getTitle(), $series->getTitle()); $this->assertEquals($seriesFramework->getInfobox(), $series->getInfobox()); diff --git a/tests/modules/solrsearch/models/SeriesUtilTest.php b/tests/modules/solrsearch/models/SeriesUtilTest.php index 50d9b01ea4..f00ea66ede 100644 --- a/tests/modules/solrsearch/models/SeriesUtilTest.php +++ b/tests/modules/solrsearch/models/SeriesUtilTest.php @@ -31,6 +31,8 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Series; + class Solrsearch_Model_SeriesUtilTest extends ControllerTestCase { @@ -44,7 +46,7 @@ public function setUp() { parent::setUp(); - foreach (Opus_Series::getAll() as $seriesItem) { + foreach (Series::getAll() as $seriesItem) { $this->visibilities[$seriesItem->getId()] = $seriesItem->getVisible(); } @@ -95,13 +97,13 @@ public function testGetVisibleSeriesSortedBySortKey() public function testGetVisibleSeriesSortedAlphabetically() { - Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + $this->adjustConfiguration([ 'browsing' => [ 'series' => [ 'sortByTitle' => self::CONFIG_VALUE_TRUE ] ] - ])); + ]); $series = $this->model->getVisibleSeries(); @@ -116,7 +118,7 @@ public function testGetVisibleSeriesSortedAlphabetically() private function setAllSeriesToUnvisible() { - foreach (Opus_Series::getAll() as $seriesItem) { + foreach (Series::getAll() as $seriesItem) { $seriesItem->setVisible(0); $seriesItem->store(); } @@ -124,7 +126,7 @@ private function setAllSeriesToUnvisible() private function restoreVisiblitySettings() { - foreach (Opus_Series::getAll() as $seriesItem) { + foreach (Series::getAll() as $seriesItem) { $seriesItem->setVisible($this->visibilities[$seriesItem->getId()]); $seriesItem->store(); } diff --git a/tests/modules/solrsearch/models/search/BasicTest.php b/tests/modules/solrsearch/models/search/BasicTest.php index eb8ada45bf..5fa6599bae 100644 --- a/tests/modules/solrsearch/models/search/BasicTest.php +++ b/tests/modules/solrsearch/models/search/BasicTest.php @@ -58,8 +58,7 @@ public function testCreateQueryBuilderInputFromRequest() */ public function testGetRowsFromConfig() { - $config = Zend_Registry::get('Zend_Config'); - $oldParamRows = $config->searchengine->solr->numberOfDefaultSearchResults; + $config = $this->getConfig(); $config->searchengine->solr->numberOfDefaultSearchResults = '1337'; $request = $this->getRequest(); @@ -68,9 +67,6 @@ public function testGetRowsFromConfig() $queryBuilder = new Solrsearch_Model_Search_Basic(); $result = $queryBuilder->createQueryBuilderInputFromRequest($request); - //clean-up - $config->searchengine->solr->numberOfDefaultSearchResults = $oldParamRows; - $this->assertEquals($result['rows'], 1337); } diff --git a/tests/modules/sword/controllers/DepositControllerErrorCasesTest.php b/tests/modules/sword/controllers/DepositControllerErrorCasesTest.php index 461020cf94..ba415da35d 100644 --- a/tests/modules/sword/controllers/DepositControllerErrorCasesTest.php +++ b/tests/modules/sword/controllers/DepositControllerErrorCasesTest.php @@ -1,5 +1,4 @@ getRequest()->setRawBody('some content'); // remove enrichment key opus.import.user - $enrichmentKey = new Opus_EnrichmentKey(Application_Import_AdditionalEnrichments::OPUS_IMPORT_USER); + $enrichmentKey = new EnrichmentKey(Application_Import_AdditionalEnrichments::OPUS_IMPORT_USER); $enrichmentKey->delete(); $this->dispatch('/sword/deposit'); - $enrichmentKey = new Opus_EnrichmentKey(); + $enrichmentKey = new EnrichmentKey(); $enrichmentKey->setName(Application_Import_AdditionalEnrichments::OPUS_IMPORT_USER); $enrichmentKey->store(); @@ -187,19 +191,19 @@ public function testZipArchiveProvokeUrnCollision() { $doc = $this->addDocWithUrn(); $this->depositError('one-doc-with-urn.zip', DepositTestHelper::CONTENT_TYPE_ZIP, 400, 'http://www.opus-repository.org/sword/error/InternalFrameworkError'); - $doc->deletePermanent(); + $doc->delete(); } public function testTarArchiveProvokeUrnCollision() { $doc = $this->addDocWithUrn(); $this->depositError('one-doc-with-urn.tar', DepositTestHelper::CONTENT_TYPE_TAR, 400, 'http://www.opus-repository.org/sword/error/InternalFrameworkError'); - $doc->deletePermanent(); + $doc->delete(); } private function addDocWithUrn() { - $doc = new Opus_Document(); + $doc = Document::new(); $doc->addIdentifier()->setType('urn')->setValue('colliding-urn'); $doc->store(); return $doc; diff --git a/tests/modules/sword/controllers/DepositControllerMultipleDocsTest.php b/tests/modules/sword/controllers/DepositControllerMultipleDocsTest.php index 780a83bb8f..36e487da21 100644 --- a/tests/modules/sword/controllers/DepositControllerMultipleDocsTest.php +++ b/tests/modules/sword/controllers/DepositControllerMultipleDocsTest.php @@ -1,5 +1,4 @@ testHelper->checkAtomEntryDocument($child, $fileName, $checksum); $this->checkMetadata($docCount, $doc); - $doc->deletePermanent(); + $doc->delete(); $docCount++; } } diff --git a/tests/modules/sword/controllers/DepositControllerTest.php b/tests/modules/sword/controllers/DepositControllerTest.php index 5bf890f762..081e67973e 100644 --- a/tests/modules/sword/controllers/DepositControllerTest.php +++ b/tests/modules/sword/controllers/DepositControllerTest.php @@ -1,5 +1,4 @@ * @copyright Copyright (c) 2016-2019 * @license http://www.gnu.org/licenses/gpl.html General Public License - * + */ + +use Opus\Document; + +/** * @covers Sword_DepositController */ class Sword_DepositControllerTest extends ControllerTestCase @@ -62,7 +65,7 @@ public function testZipArchiveAllFieldDocumentDeposit() { $doc = $this->depositSuccessful('allfields-document.zip', DepositTestHelper::CONTENT_TYPE_ZIP, true, false, false, 7, 3, 'published'); $this->checkAllFieldsImport($doc); - $doc->deletePermanent(); + $doc->delete(); $this->testHelper->removeImportCollection(); } @@ -70,7 +73,7 @@ public function testTarArchiveAllFieldDocumentDeposit() { $doc = $this->depositSuccessful('allfields-document.tar', DepositTestHelper::CONTENT_TYPE_TAR, true, false, false, 7, 3, 'published'); $this->checkAllFieldsImport($doc); - $doc->deletePermanent(); + $doc->delete(); $this->testHelper->removeImportCollection(); } @@ -78,7 +81,7 @@ public function testZipArchiveDanglingIds() { $doc = $this->depositSuccessful('dangling-ids.zip', DepositTestHelper::CONTENT_TYPE_ZIP, false, false); $this->checkMinimalDoc($doc); - $doc->deletePermanent(); + $doc->delete(); $this->testHelper->removeImportCollection(); } @@ -86,7 +89,7 @@ public function testTarArchiveDanglingIds() { $doc = $this->depositSuccessful('dangling-ids.tar', DepositTestHelper::CONTENT_TYPE_TAR, false, false); $this->checkMinimalDoc($doc); - $doc->deletePermanent(); + $doc->delete(); $this->testHelper->removeImportCollection(); } @@ -94,7 +97,7 @@ public function testZipArchiveWithUrnCollision() { $doc = $this->depositSuccessful('urn-collision.zip', DepositTestHelper::CONTENT_TYPE_ZIP, false, false); $this->checkOnlyOneDocIsImported($doc); - $doc->deletePermanent(); + $doc->delete(); $this->testHelper->removeImportCollection(); } @@ -102,7 +105,7 @@ public function testTarArchiveWithUrnCollision() { $doc = $this->depositSuccessful('urn-collision.tar', DepositTestHelper::CONTENT_TYPE_TAR, false, false); $this->checkOnlyOneDocIsImported($doc); - $doc->deletePermanent(); + $doc->delete(); $this->testHelper->removeImportCollection(); } @@ -110,7 +113,7 @@ public function testZipArchiveWithEmptyElementsDocumentDeposit() { $doc = $this->depositSuccessful('empty-elements.zip', DepositTestHelper::CONTENT_TYPE_ZIP, false, false); $this->checkMinimalDoc($doc, 'eng', 'book', 'titlemain'); - $doc->deletePermanent(); + $doc->delete(); $this->testHelper->removeImportCollection(); } @@ -118,7 +121,7 @@ public function testTarArchiveWithEmptyElementsDocumentDeposit() { $doc = $this->depositSuccessful('empty-elements.tar', DepositTestHelper::CONTENT_TYPE_TAR, false, false); $this->checkMinimalDoc($doc, 'eng', 'book', 'titlemain'); - $doc->deletePermanent(); + $doc->delete(); $this->testHelper->removeImportCollection(); } @@ -126,7 +129,7 @@ public function testZipArchiveWithEmptyElementsDocumentDepositAlternative() { $doc = $this->depositSuccessful('empty-elements-alternative.zip', DepositTestHelper::CONTENT_TYPE_ZIP, false, false); $this->checkMinimalDoc($doc, 'eng', 'book', 'titlemain'); - $doc->deletePermanent(); + $doc->delete(); $this->testHelper->removeImportCollection(); } @@ -134,7 +137,7 @@ public function testTarArchiveWithEmptyElementsDocumentDepositAlternative() { $doc = $this->depositSuccessful('empty-elements-alternative.tar', DepositTestHelper::CONTENT_TYPE_TAR, false, false); $this->checkMinimalDoc($doc, 'eng', 'book', 'titlemain'); - $doc->deletePermanent(); + $doc->delete(); $this->testHelper->removeImportCollection(); } @@ -147,7 +150,7 @@ public function testZipSingleDocWithMultipleFilesImplicit() $this->checkFile($files[0], 'doc1.pdf', $language, null, 1, 1); $this->checkFile($files[1], 'doc1.txt', $language, null, 1, 1); $this->checkFile($files[2], 'foo.txt', $language, null, 1, 1); - $doc->deletePermanent(); + $doc->delete(); $this->testHelper->removeImportCollection(); } @@ -160,10 +163,56 @@ public function testTarSingleDocWithMultipleFilesImplicit() $this->checkFile($files[0], 'doc1.pdf', $language, null, 1, 1); $this->checkFile($files[1], 'doc1.txt', $language, null, 1, 1); $this->checkFile($files[2], 'foo.txt', $language, null, 1, 1); - $doc->deletePermanent(); + $doc->delete(); $this->testHelper->removeImportCollection(); } + public function testFileIsRemovedFromImportFolderAfterSuccess() + { + $doc = $this->depositSuccessful( + 'minimal-record.zip', + DepositTestHelper::CONTENT_TYPE_ZIP, + true, + false + ); + + $config = Application_Configuration::getInstance(); + $importDir = $config->getWorkspacePath() . 'import/'; + $enrichments = $doc->getEnrichmentValues(); + $filename = $enrichments['opus.import.file']; + $filePath = $importDir . $filename; + + $this->addFileToCleanup($filePath); + + $this->assertFileNotExists($filePath); + } + + public function testFileIsKeptInImportFolderAfterError() + { + $doc = $this->depositWithError( + 'invalid-xml.zip', + DepositTestHelper::CONTENT_TYPE_ZIP, + true, + false + ); + + $this->assertNull($doc); + + $config = Application_Configuration::getInstance(); + $importDir = $config->getWorkspacePath() . 'import/'; + + $payload = file_get_contents(APPLICATION_PATH . '/tests/resources/sword-packages/invalid-xml.zip'); + $checksum = md5($payload); + + $filename = "$checksum-invalid-xml.zip"; + $filePath = $importDir . $filename; + + $this->addFileToCleanup($filePath); + + $this->assertFileExists($filePath); + } + + private function checkOnlyOneDocIsImported($doc) { $this->assertEquals('eng', $doc->getLanguage()); @@ -181,7 +230,7 @@ private function checkMinimalDoc($doc, $language = 'deu', $docType = 'book', $ti } /** - * @param Opus_Document $doc + * @param Document $doc * @throws Exception */ private function checkAllFieldsImport($doc) @@ -400,15 +449,15 @@ private function checkTitleFields($titles, $titleType) /** * - * @param type $fileName - * @param type $contentType - * @param type $abstractExist - * @param type $deleteDoc - * @param type $deleteCollection - * @param type $numOfEnrichments - * @param type $numOfCollections - * @param type $serverState - * @return Opus_Document + * @param string $fileName + * @param string $contentType + * @param bool $abstractExist + * @param bool $deleteDoc + * @param bool $deleteCollection + * @param int $numOfEnrichments + * @param int $numOfCollections + * @param string $serverState + * @return Document */ private function depositSuccessful( $fileName, @@ -441,6 +490,38 @@ private function depositSuccessful( return $doc; } + /** + * TODO addapt function to run deposit requests producing various errors + */ + private function depositWithError( + $fileName, + $contentType, + $abstractExist = true, + $deleteDoc = true, + $deleteCollection = true, + $numOfEnrichments = 5, + $numOfCollections = 1, + $serverState = 'unpublished' + ) { + + $this->testHelper->assertEmptyTmpDir(); + $this->testHelper->disableExceptionConversion(); + $this->getRequest()->setMethod('POST'); + $this->getRequest()->setHeader('Content-Type', $contentType); + $this->testHelper->setValidAuthorizationHeader($this->getRequest(), DepositTestHelper::USER_AGENT); + $checksum = $this->testHelper->uploadFile($this->getRequest(), $fileName); + $this->getRequest()->setHeader('Content-Disposition', $fileName); + $this->testHelper->addImportCollection(); + + $this->dispatch('/sword/deposit'); + $this->testHelper->assertEmptyTmpDir(); + + $doc = $this->checkErrorDocument($checksum, $fileName, $abstractExist, $numOfEnrichments, $numOfCollections, $serverState, $deleteDoc); + if ($deleteCollection) { + $this->testHelper->removeImportCollection(); + } + } + private function checkAtomEntryDocument($checksum, $fileName, $abstractExist, $numOfEnrichments, $numOfCollections, $serverState, $deleteDoc) { $this->assertEquals(201, $this->getResponse()->getHttpResponseCode()); @@ -460,7 +541,34 @@ private function checkAtomEntryDocument($checksum, $fileName, $abstractExist, $n return $doc; } + $doc->delete(); + } + + /** + * TODO adapt function for checking error document OPUSVIER-4500 + */ + private function checkErrorDocument($checksum, $fileName, $abstractExist, $numOfEnrichments, $numOfCollections, $serverState, $deleteDoc) + { + $this->assertNotEquals(201, $this->getResponse()->getHttpResponseCode()); + + /** + $doc = new DOMDocument(); + $doc->loadXML($this->getResponse()->getBody()); + + $roots = $doc->childNodes; + $this->assertEquals(1, $roots->length); + $root = $roots->item(0); + + $doc = $this->testHelper->checkAtomEntryDocument($root, $fileName, $checksum, $abstractExist, $numOfEnrichments, $numOfCollections); + $this->assertEquals($serverState, $doc->getServerState()); + $this->checkHttpResponseHeaders($this->testHelper->getFrontdoorUrl()); + + if (! $deleteDoc) { + return $doc; + } + $doc->deletePermanent(); + */ } private function checkHttpResponseHeaders($frontdoorUrl) diff --git a/tests/modules/sword/controllers/ServicedocumentControllerTest.php b/tests/modules/sword/controllers/ServicedocumentControllerTest.php index 7097081037..619c5f5bd2 100644 --- a/tests/modules/sword/controllers/ServicedocumentControllerTest.php +++ b/tests/modules/sword/controllers/ServicedocumentControllerTest.php @@ -1,5 +1,4 @@ assertEquals(2, $root->length); - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $this->testHelper->assertNodeProperties(0, $root, 'atom:title', $config->name); $collectionNode = $root->item(1); diff --git a/tests/rebuild-database.php b/tests/rebuild-database.php index 7330cfef22..a7e9b8f141 100644 --- a/tests/rebuild-database.php +++ b/tests/rebuild-database.php @@ -54,8 +54,11 @@ require_once 'autoload.php'; +// TODO OPUSVIER-4420 remove after switching to Laminas/ZF3 +require_once APPLICATION_PATH . '/vendor/opus4-repo/framework/library/OpusDb/Mysqlutf8.php'; + // environment initializiation -$application = new Zend_Application( +$application = new \Zend_Application( APPLICATION_ENV, [ "config" => [ @@ -68,7 +71,9 @@ ] ); -Zend_Registry::set('opus.disableDatabaseVersionCheck', true); +$options = $application->getOptions(); +$options['opus']['disableDatabaseVersionCheck'] = true; +$application->setOptions($options); // Bootstrapping application $application->bootstrap('Backend'); @@ -77,7 +82,7 @@ * Prepare database. */ -$database = new Opus_Database(); +$database = new \Opus\Database(); $dbName = $database->getName(); diff --git a/tests/rebuilding_database.sh b/tests/rebuilding_database.sh index 7abb493336..2aae2ee93a 100755 --- a/tests/rebuilding_database.sh +++ b/tests/rebuilding_database.sh @@ -113,7 +113,10 @@ function cleanupFolders() { fi if [ -d ${workspace_log_dir} ] ; then - rm -rf $workspace_log_dir + rm -f $workspace_log_dir/opus.log + rm -f $workspace_log_dir/opus-console.log + rm -f $workspace_log_dir/index.log + # do not remove error.log (Apache2 is using it) fi if [ -d ${series_logos_dir} ] ; then @@ -131,14 +134,16 @@ mkdir -p $workspace_files_dir mkdir -p $workspace_log_dir mkdir -p $workspace_dir/cache mkdir -p $workspace_dir/export +mkdir -p $workspace_dir/import mkdir -p $workspace_dir/incoming mkdir -p $workspace_dir/tmp mkdir -p $workspace_dir/tmp/resumption mkdir -p $series_logos_dir -rm -rf $workspace_test_dir/* +rm -rf "${workspace_test_dir:?}"/* mkdir -p $workspace_test_dir/cache mkdir -p $workspace_test_dir/export +mkdir -p $workspace_test_dir/import mkdir -p $workspace_test_dir/incoming mkdir -p $workspace_test_dir/tmp mkdir -p $workspace_test_dir/tmp/resumption diff --git a/tests/resources/import/embargo-date.xml b/tests/resources/import/embargo-date.xml new file mode 100644 index 0000000000..299d0c691b --- /dev/null +++ b/tests/resources/import/embargo-date.xml @@ -0,0 +1,17 @@ + + + + + + + + valid embargoed document + + + + + + + diff --git a/tests/resources/import/incomplete-embargo-date.xml b/tests/resources/import/incomplete-embargo-date.xml new file mode 100644 index 0000000000..105a9e749a --- /dev/null +++ b/tests/resources/import/incomplete-embargo-date.xml @@ -0,0 +1,18 @@ + + + + + + + + invalid embargoed document + + + + + + + + diff --git a/tests/resources/import/incomplete-embargo-year.xml b/tests/resources/import/incomplete-embargo-year.xml new file mode 100644 index 0000000000..184c576229 --- /dev/null +++ b/tests/resources/import/incomplete-embargo-year.xml @@ -0,0 +1,18 @@ + + + + + + + + invalid embargoed document + + + + + + + + diff --git a/tests/scripts/cron/ConsistencyCheckTest.php b/tests/scripts/cron/ConsistencyCheckTest.php index 07ca6db663..620869186d 100644 --- a/tests/scripts/cron/ConsistencyCheckTest.php +++ b/tests/scripts/cron/ConsistencyCheckTest.php @@ -33,6 +33,8 @@ require_once('CronTestCase.php'); +use Opus\Job; + class ConsistencyCheckTest extends CronTestCase { @@ -40,9 +42,9 @@ class ConsistencyCheckTest extends CronTestCase private function getPublishedDocumentCount() { - $finder = new Opus_DocumentFinder(); + $finder = $this->getDocumentFinder(); $finder->setServerState('published'); - return count($finder->ids()); + return $finder->getCount(); } /** @@ -53,10 +55,10 @@ public function testJobSuccess() $this->createJob(Opus\Search\Task\ConsistencyCheck::LABEL); $this->executeScript('cron-check-consistency.php'); - $allJobs = Opus_Job::getByLabels([Opus\Search\Task\ConsistencyCheck::LABEL], null, Opus_Job::STATE_UNDEFINED); + $allJobs = Job::getByLabels([Opus\Search\Task\ConsistencyCheck::LABEL], null, Job::STATE_UNDEFINED); $this->assertTrue(empty($allJobs), 'Expected no more jobs in queue: found ' . count($allJobs) . ' jobs'); - $failedJobs = Opus_Job::getByLabels([Opus\Search\Task\ConsistencyCheck::LABEL], null, Opus_Job::STATE_FAILED); + $failedJobs = Job::getByLabels([Opus\Search\Task\ConsistencyCheck::LABEL], null, Job::STATE_FAILED); $this->assertTrue(empty($failedJobs), 'Expected no failed jobs in queue: found ' . count($failedJobs) . ' jobs'); $logPath = parent::$scriptPath . '/../../workspace/log/'; @@ -95,10 +97,10 @@ public function testJobSuccessWithInconsistency() $this->createJob(Opus\Search\Task\ConsistencyCheck::LABEL); $this->executeScript('cron-check-consistency.php'); - $allJobs = Opus_Job::getByLabels([Opus\Search\Task\ConsistencyCheck::LABEL], null, Opus_Job::STATE_UNDEFINED); + $allJobs = Job::getByLabels([Opus\Search\Task\ConsistencyCheck::LABEL], null, Job::STATE_UNDEFINED); $this->assertTrue(empty($allJobs), 'Expected no more jobs in queue: found ' . count($allJobs) . ' jobs'); - $failedJobs = Opus_Job::getByLabels([Opus\Search\Task\ConsistencyCheck::LABEL], null, Opus_Job::STATE_FAILED); + $failedJobs = Job::getByLabels([Opus\Search\Task\ConsistencyCheck::LABEL], null, Job::STATE_FAILED); $this->assertTrue(empty($failedJobs), 'Expected no failed jobs in queue: found ' . count($failedJobs) . ' jobs'); $logPath = parent::$scriptPath . '/../../workspace/log/'; diff --git a/tests/scripts/cron/CronTestCase.php b/tests/scripts/cron/CronTestCase.php index ddf3647218..cf9c505d88 100644 --- a/tests/scripts/cron/CronTestCase.php +++ b/tests/scripts/cron/CronTestCase.php @@ -31,6 +31,9 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Job; +use Opus\Model\NotFoundException; + /** * */ @@ -53,9 +56,9 @@ public function tearDown() if (! empty($this->jobIds)) { foreach ($this->jobIds as $jobId) { try { - $job = new Opus_Job($jobId); + $job = new Job($jobId); $job->delete(); - } catch (Opus_Model_NotFoundException $e) { + } catch (NotFoundException $e) { } } } @@ -76,7 +79,7 @@ protected function executeScript($fileName) protected function createJob($label, $data = []) { - $job = new Opus_Job(); + $job = new Job(); $job->setLabel($label); $job->setData($data); $this->jobIds[] = $job->store(); diff --git a/tests/scripts/cron/DbCleanTemporaryTest.php b/tests/scripts/cron/DbCleanTemporaryTest.php index 5281c6cb15..a94497369b 100644 --- a/tests/scripts/cron/DbCleanTemporaryTest.php +++ b/tests/scripts/cron/DbCleanTemporaryTest.php @@ -1,5 +1,4 @@ changeDocumentDateModified(3); $this->executeScript('cron-db-clean-temporary.php'); try { - $doc = new Opus_Document($this->doc->getId()); - $doc->deletePermanent(); - $this->fail("expected Opus_Model_NotFoundException"); - } catch (Opus_Model_NotFoundException $e) { + $doc = Document::get($this->doc->getId()); + $doc->delete(); + $this->fail("expected Opus\Model\NotFoundException"); + } catch (NotFoundException $e) { } } @@ -70,9 +73,9 @@ public function testKeepDocumentNewerThan3Days() $this->changeDocumentDateModified(2); $this->executeScript('cron-db-clean-temporary.php'); try { - $doc = new Opus_Document($this->doc->getId()); - $doc->deletePermanent(); - } catch (Opus_Model_NotFoundException $e) { + $doc = Document::get($this->doc->getId()); + $doc->delete(); + } catch (NotFoundException $e) { $this->fail("expected existing document."); } } @@ -81,6 +84,6 @@ private function changeDocumentDateModified($numDaysBeforeNow) { $date = new DateTime(); $date->sub(new DateInterval("P{$numDaysBeforeNow}D")); - $this->doc->changeServerDateModified(new Opus_Date($date)); + $this->doc->changeServerDateModified(new Date($date)); } } diff --git a/tests/scripts/cron/EmbargoUpdateTest.php b/tests/scripts/cron/EmbargoUpdateTest.php index 5a55e4089c..00d46eae4f 100644 --- a/tests/scripts/cron/EmbargoUpdateTest.php +++ b/tests/scripts/cron/EmbargoUpdateTest.php @@ -34,6 +34,9 @@ require_once('CronTestCase.php'); +use Opus\Date; +use Opus\Document; + /** * */ @@ -44,38 +47,38 @@ class EmbargoUpdateTest extends CronTestCase public function testEmbargoUpdate() { - $twoDaysAgo = new Opus_Date(); + $twoDaysAgo = new Date(); $twoDaysAgo->setDateTime(new DateTime(date('Y-m-d H:i:s', strtotime('-2 day')))); $yesterday = date('Y-m-d', strtotime('-1 day')); $today = date('Y-m-d', time()); - $doc = new Opus_Document(); + $doc = Document::new(); $doc->setEmbargoDate($yesterday); $expiredId = $doc->store(); - $doc = new Opus_Document(); + $doc = Document::new(); $noEmbargoId = $doc->store(); - $doc = new Opus_Document(); + $doc = Document::new(); $doc->setEmbargoDate($today); $notExpiredId = $doc->store(); - Opus_Document::setServerDateModifiedByIds($twoDaysAgo, [$expiredId, $noEmbargoId, $notExpiredId]); + Document::setServerDateModifiedByIds($twoDaysAgo, [$expiredId, $noEmbargoId, $notExpiredId]); $this->executeScript('cron-embargo-update.php'); // document embargo until yesterday -> therefore ServerDateModified got updated - $doc = new Opus_Document($expiredId); + $doc = Document::get($expiredId); $this->assertTrue($this->sameDay(new DateTime($today), $doc->getServerDateModified()->getDateTime())); // document embargo until today -> therefore ServerDateModified not yet updated - $doc = new Opus_Document($notExpiredId); + $doc = Document::get($notExpiredId); $this->assertTrue($this->sameDay($twoDaysAgo->getDateTime(), $doc->getServerDateModified()->getDateTime())); // no document embargo -> therefore ServerDateModified unchanged - $doc = new Opus_Document($noEmbargoId); + $doc = Document::get($noEmbargoId); $this->assertTrue($this->sameDay($twoDaysAgo->getDateTime(), $doc->getServerDateModified()->getDateTime())); } diff --git a/tests/scripts/cron/MetadataImportTest.php b/tests/scripts/cron/MetadataImportTest.php index 782d4f6add..24be140301 100644 --- a/tests/scripts/cron/MetadataImportTest.php +++ b/tests/scripts/cron/MetadataImportTest.php @@ -34,6 +34,9 @@ require_once('CronTestCase.php'); +use Opus\Document; +use Opus\Job; +use Opus\Job\Worker\MetadataImport; class MetadataImportTest extends CronTestCase { @@ -55,10 +58,10 @@ public function setUp() public function tearDown() { if ($this->documentImported) { - $ids = Opus_Document::getAllIds(); + $ids = Document::getAllIds(); $last_id = array_pop($ids); - $doc = new Opus_Document($last_id); - $doc->deletePermanent(); + $doc = Document::get($last_id); + $doc->delete(); } parent::tearDown(); } @@ -66,14 +69,16 @@ public function tearDown() public function testJobFailedWithoutXml() { $xml = null; - $this->createJob(Opus_Job_Worker_MetadataImport::LABEL, ['xml' => $xml]); + $this->createJob(MetadataImport::LABEL, ['xml' => $xml]); $this->executeScript('cron-import-metadata.php'); - $allJobs = Opus_Job::getByLabels([Opus_Job_Worker_MetadataImport::LABEL], null, Opus_Job::STATE_UNDEFINED); + $allJobs = Job::getByLabels([MetadataImport::LABEL], null, Job::STATE_UNDEFINED); $this->assertTrue(empty($allJobs), 'Expected no more jobs in queue'); - $failedJobs = Opus_Job::getByLabels([Opus_Job_Worker_MetadataImport::LABEL], null, Opus_Job::STATE_FAILED); + $failedJobs = Job::getByLabels([MetadataImport::LABEL], null, Job::STATE_FAILED); $this->assertEquals(1, count($failedJobs), 'Expected one failed job in queue'); - $this->assertJobException(array_pop($failedJobs), 'Opus_Job_Worker_InvalidJobException'); + + // TODO Opus\\\\Job... is necessary to match Opus\\Job... in the actual error message - Fix! + $this->assertJobException(array_pop($failedJobs), 'Opus\\\\Job\\\\Worker\\\\InvalidJobException'); } public function testJobFailedWithSkippedDocumentsException() @@ -82,14 +87,14 @@ public function testJobFailedWithSkippedDocumentsException() $xml = new DOMDocument(); $this->assertTrue($xml->load($this->xmlDir . $filename), 'Could not load xml as DomDocument'); - $this->createJob(Opus_Job_Worker_MetadataImport::LABEL, ['xml' => $xml->saveXML()]); + $this->createJob(MetadataImport::LABEL, ['xml' => $xml->saveXML()]); $this->executeScript('cron-import-metadata.php'); - $allJobs = Opus_Job::getByLabels([Opus_Job_Worker_MetadataImport::LABEL], null, Opus_Job::STATE_UNDEFINED); + $allJobs = Job::getByLabels([MetadataImport::LABEL], null, Job::STATE_UNDEFINED); $this->assertTrue(empty($allJobs), 'Expected no more jobs in queue'); - $failedJobs = Opus_Job::getByLabels([Opus_Job_Worker_MetadataImport::LABEL], null, Opus_Job::STATE_FAILED); + $failedJobs = Job::getByLabels([MetadataImport::LABEL], null, Job::STATE_FAILED); $this->assertEquals(1, count($failedJobs), 'Expected one failed job in queue'); - $this->assertJobException(array_pop($failedJobs), 'Opus_Util_MetadataImportSkippedDocumentsException'); + $this->assertJobException(array_pop($failedJobs), 'Opus\\\\Util\\\\MetadataImportSkippedDocumentsException'); } public function testJobFailedWithInvalidXmlException() @@ -98,14 +103,14 @@ public function testJobFailedWithInvalidXmlException() $xml = new DOMDocument(); $this->assertTrue($xml->load($this->xmlDir . $filename), 'Could not load xml as DomDocument'); - $this->createJob(Opus_Job_Worker_MetadataImport::LABEL, ['xml' => $xml->saveXML()]); + $this->createJob(MetadataImport::LABEL, ['xml' => $xml->saveXML()]); $this->executeScript('cron-import-metadata.php'); - $allJobs = Opus_Job::getByLabels([Opus_Job_Worker_MetadataImport::LABEL], null, Opus_Job::STATE_UNDEFINED); + $allJobs = Job::getByLabels([MetadataImport::LABEL], null, Job::STATE_UNDEFINED); $this->assertTrue(empty($allJobs), 'Expected no more jobs in queue'); - $failedJobs = Opus_Job::getByLabels([Opus_Job_Worker_MetadataImport::LABEL], null, Opus_Job::STATE_FAILED); + $failedJobs = Job::getByLabels([MetadataImport::LABEL], null, Job::STATE_FAILED); $this->assertEquals(1, count($failedJobs), 'Expected one failed job in queue'); - $this->assertJobException(array_pop($failedJobs), 'Opus_Util_MetadataImportInvalidXmlException'); + $this->assertJobException(array_pop($failedJobs), 'Opus\\\\Util\\\\MetadataImportInvalidXmlException'); } @@ -115,12 +120,12 @@ public function testJobSuccess() $xml = new DOMDocument(); $this->assertTrue($xml->load($this->xmlDir . $filename), 'Could not load xml as DomDocument'); - $this->createJob(Opus_Job_Worker_MetadataImport::LABEL, ['xml' => $xml->saveXML()]); + $this->createJob(MetadataImport::LABEL, ['xml' => $xml->saveXML()]); $this->executeScript('cron-import-metadata.php'); - $allJobs = Opus_Job::getByLabels([Opus_Job_Worker_MetadataImport::LABEL], null, Opus_Job::STATE_UNDEFINED); + $allJobs = Job::getByLabels([MetadataImport::LABEL], null, Job::STATE_UNDEFINED); $this->assertTrue(empty($allJobs), 'Expected no more jobs in queue'); - $failedJobs = Opus_Job::getByLabels([Opus_Job_Worker_MetadataImport::LABEL], null, Opus_Job::STATE_FAILED); + $failedJobs = Job::getByLabels([MetadataImport::LABEL], null, Job::STATE_FAILED); $this->assertTrue(empty($failedJobs), 'Expected no failed jobs in queue'); $this->documentImported = true; diff --git a/tests/scripts/cron/OpusDocumentMock.php b/tests/scripts/cron/OpusDocumentMock.php index 3183e816ab..aa4aa74870 100644 --- a/tests/scripts/cron/OpusDocumentMock.php +++ b/tests/scripts/cron/OpusDocumentMock.php @@ -1,5 +1,4 @@ createJob(Opus_Job_Worker_MailNotification::LABEL, [ + $this->createJob(MailNotification::LABEL, [ 'subject' => 'SendNotification Test', 'message' => 'This is a test message generated in ' . __FILE__, 'users' => [['address' => 'user@example.org', 'name' => 'Test User']] ]); $this->executeScript('cron-send-notification.php'); - $allJobs = Opus_Job::getByLabels([Opus_Job_Worker_MailNotification::LABEL], null, Opus_Job::STATE_UNDEFINED); + $allJobs = Job::getByLabels([MailNotification::LABEL], null, Job::STATE_UNDEFINED); $this->assertTrue(empty($allJobs), 'Expected no more jobs in queue'); - $failedJobs = Opus_Job::getByLabels([Opus_Job_Worker_MailNotification::LABEL], null, Opus_Job::STATE_FAILED); + $failedJobs = Job::getByLabels([MailNotification::LABEL], null, Job::STATE_FAILED); $this->assertTrue(empty($failedJobs), 'Expected no failed jobs in queue'); } public function testFailSendNotification() { - $this->createJob(Opus_Job_Worker_MailNotification::LABEL, [ + $this->createJob(MailNotification::LABEL, [ 'subject' => 'SendNotification Test', 'message' => 'This is a test message generated in ' . __FILE__, 'users' => '' ]); $this->executeScript('cron-send-notification.php'); - $failedJobs = Opus_Job::getByLabels([Opus_Job_Worker_MailNotification::LABEL], null, Opus_Job::STATE_FAILED); + $failedJobs = Job::getByLabels([MailNotification::LABEL], null, Job::STATE_FAILED); $this->assertEquals(1, count($failedJobs), 'Expected one failed job in queue'); } } diff --git a/tests/scripts/cron/SolrUpdateTest.php b/tests/scripts/cron/SolrUpdateTest.php index 32d7ac2040..aca260213d 100644 --- a/tests/scripts/cron/SolrUpdateTest.php +++ b/tests/scripts/cron/SolrUpdateTest.php @@ -34,6 +34,8 @@ */ require_once('CronTestCase.php'); +use Opus\Job; + /** * */ @@ -49,7 +51,7 @@ public function setUp() parent::setUp(); $this->document = $this->createTestDocument(); $this->document->store(); - Opus_Job::deleteAll(); + Job::deleteAll(); } public function testSolrUpdateIndex() @@ -58,9 +60,9 @@ public function testSolrUpdateIndex() 'documentId' => $this->document->getId(), 'task' => 'index']); $this->executeScript('cron-solr-update.php'); - $allJobs = Opus_Job::getByLabels([Opus\Search\Task\IndexOpusDocument::LABEL], null, Opus_Job::STATE_UNDEFINED); + $allJobs = Job::getByLabels([Opus\Search\Task\IndexOpusDocument::LABEL], null, Job::STATE_UNDEFINED); $this->assertTrue(empty($allJobs), 'Expected no more jobs in queue'); - $failedJobs = Opus_Job::getByLabels([Opus\Search\Task\IndexOpusDocument::LABEL], null, Opus_Job::STATE_FAILED); + $failedJobs = Job::getByLabels([Opus\Search\Task\IndexOpusDocument::LABEL], null, Job::STATE_FAILED); $this->assertTrue(empty($failedJobs), 'Expected no failed jobs in queue'); } @@ -70,9 +72,9 @@ public function testSolrRemoveIndex() 'documentId' => $this->document->getId(), 'task' => 'remove']); $this->executeScript('cron-solr-update.php'); - $allJobs = Opus_Job::getByLabels([Opus\Search\Task\IndexOpusDocument::LABEL], null, Opus_Job::STATE_UNDEFINED); + $allJobs = Job::getByLabels([Opus\Search\Task\IndexOpusDocument::LABEL], null, Job::STATE_UNDEFINED); $this->assertTrue(empty($allJobs), 'Expected no more jobs in queue'); - $failedJobs = Opus_Job::getByLabels([Opus\Search\Task\IndexOpusDocument::LABEL], null, Opus_Job::STATE_FAILED); + $failedJobs = Job::getByLabels([Opus\Search\Task\IndexOpusDocument::LABEL], null, Job::STATE_FAILED); $this->assertTrue(empty($failedJobs), 'Expected no failed jobs in queue'); } @@ -82,7 +84,7 @@ public function testJobFailsIfInvalidTask() 'documentId' => $this->document->getId(), 'task' => 'do-the-unexpected']); $this->executeScript('cron-solr-update.php'); - $allJobs = Opus_Job::getByLabels([Opus\Search\Task\IndexOpusDocument::LABEL], null, Opus_Job::STATE_FAILED); + $allJobs = Job::getByLabels([Opus\Search\Task\IndexOpusDocument::LABEL], null, Job::STATE_FAILED); $this->assertEquals(1, count($allJobs), 'Expected one failed job in queue (found ' . count($allJobs) . ')'); } } diff --git a/tests/scripts/cron/UpdateDocumentCacheTest.php b/tests/scripts/cron/UpdateDocumentCacheTest.php index de236e92e6..66c8f10630 100644 --- a/tests/scripts/cron/UpdateDocumentCacheTest.php +++ b/tests/scripts/cron/UpdateDocumentCacheTest.php @@ -33,6 +33,9 @@ require_once('CronTestCase.php'); +use Opus\Licence; +use Opus\Db\DocumentXmlCache; + /** * */ @@ -46,7 +49,7 @@ public function testUpdateOnLicenceChange() $document = $this->createTestDocument(); $document->store(); - $documentCacheTable = new Opus_Db_DocumentXmlCache(); + $documentCacheTable = new DocumentXmlCache(); $docXmlCache = $documentCacheTable->find($document->getId(), '1')->current()->xml_data; $domDoc = new DomDocument(); @@ -54,7 +57,7 @@ public function testUpdateOnLicenceChange() $licences = $domDoc->getElementsByTagName('Licence'); $this->assertTrue($licences->length == 0, 'Expected no Licence element in dom.'); - $licence = new Opus_Licence(); + $licence = new Licence(); $licence->setNameLong('TestLicence'); $licence->setLinkLicence('http://example.org/licence'); $licenceId = $licence->store(); @@ -62,7 +65,7 @@ public function testUpdateOnLicenceChange() $document->setLicence($licence); $docId = $document->store(); - $licence = new Opus_Licence($licenceId); + $licence = new Licence($licenceId); $licence->setNameLong('TestLicenceAltered'); $licence->store(); diff --git a/tests/security/CollectionsAdminTest.php b/tests/security/CollectionsAdminTest.php index aa302c8e6c..65146bf9e5 100644 --- a/tests/security/CollectionsAdminTest.php +++ b/tests/security/CollectionsAdminTest.php @@ -1,6 +1,6 @@ - * @copyright Copyright (c) 2008-2019, OPUS 4 development team + * @copyright Copyright (c) 2008-2022, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ @@ -36,7 +34,7 @@ class CollectionsAdminTest extends ControllerTestCase protected $configModifiable = true; - protected $additionalResources = ['authz', 'database', 'view', 'mainMenu', 'navigation', 'translation']; + protected $additionalResources = ['database', 'view', 'mainMenu', 'navigation', 'translation']; public function setUp() { diff --git a/tests/security/FullAdminTest.php b/tests/security/FullAdminTest.php index f2bfeeed2f..e9c25a15a1 100644 --- a/tests/security/FullAdminTest.php +++ b/tests/security/FullAdminTest.php @@ -1,5 +1,6 @@ - * @author Jens Schwidder - * @copyright Copyright (c) 2008-2019, OPUS 4 development team + * @copyright Copyright (c) 2008-2022, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ @@ -36,7 +34,7 @@ class FullAdminTest extends ControllerTestCase protected $configModifiable = true; - protected $additionalResources = ['authz', 'database', 'view', 'navigation', 'mainMenu', 'translation']; + protected $additionalResources = ['database', 'view', 'navigation', 'mainMenu', 'translation']; public function setUp() { diff --git a/tests/security/IpRangeTest.php b/tests/security/IpRangeTest.php new file mode 100644 index 0000000000..016904e01f --- /dev/null +++ b/tests/security/IpRangeTest.php @@ -0,0 +1,64 @@ +enableSecurity(); + } + + public function tearDown() + { + $this->restoreSecuritySetting(); + parent::tearDown(); + } + + public function testClientIpSetDuringRouting() + { + $_SERVER['REMOTE_ADDR'] = '127.0.0.2'; + $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.3'; + + $this->dispatch('/home'); + + $realm = Realm::getInstance(); + + $this->assertEquals('127.0.0.2', $realm->getIp()); + } +} diff --git a/tests/security/LicencesAdminTests.php b/tests/security/LicencesAdminTest.php similarity index 88% rename from tests/security/LicencesAdminTests.php rename to tests/security/LicencesAdminTest.php index 4d91f79d9b..00e7e090d2 100644 --- a/tests/security/LicencesAdminTests.php +++ b/tests/security/LicencesAdminTest.php @@ -1,5 +1,4 @@ assertNotQuery('//a[@href="/admin/series"]'); $this->assertNotQuery('//a[@href="/admin/language"]'); $this->assertNotQuery('//a[@href="/admin/dnbinstitute"]'); - $this->assertQuery('//a[@href="/admin/index/setup"]'); + $this->assertNotQuery('//a[@href="/admin/index/setup"]'); $this->assertNotQuery('//a[@href="/review"]'); } @@ -86,7 +85,7 @@ public function testAccessLicenceController() public function testNoAccessDocumentsController() { $this->dispatch('/admin/documents'); - $this->assertRedirectTo('/auth'); + $this->assertRedirectTo('/auth/index/rmodule/admin/rcontroller/documents/raction/index'); } /** @@ -102,18 +101,20 @@ public function testEditLinkInFrontdoorNotPresent() public function testNoAccessFilebrowserController() { $this->dispatch('/admin/filebrowser/index/docId/92'); - $this->assertRedirectTo('/auth'); + $this->assertRedirectTo('/auth/index/rmodule/admin/rcontroller/filebrowser/raction/index/docId/92'); } public function testNoAccessWorkflowController() { $this->dispatch('/admin/workflow/changestate/docId/300/targetState/deleted'); - $this->assertRedirectTo('/auth'); + $this->assertRedirectTo( + '/auth/index/rmodule/admin/rcontroller/workflow/raction/changestate/docId/300/targetState/deleted' + ); } public function testNoAccessAccessController() { $this->dispatch('/admin/access/listmodule/roleid/2'); - $this->assertRedirectTo('/auth'); + $this->assertRedirectTo('/auth/index/rmodule/admin/rcontroller/access/raction/listmodule/roleid/2'); } } diff --git a/tests/security/RefereeTest.php b/tests/security/RefereeTest.php index 2beee718c5..bbdac1565a 100644 --- a/tests/security/RefereeTest.php +++ b/tests/security/RefereeTest.php @@ -1,6 +1,6 @@ - * @copyright Copyright (c) 2008-2019, OPUS 4 development team + * @copyright Copyright (c) 2008-2022, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Account; +use Opus\UserRole; + class RefereeTest extends ControllerTestCase { - protected $additionalResources = ['authz', 'database', 'view', 'mainMenu', 'navigation', 'translation']; + protected $additionalResources = ['database', 'view', 'mainMenu', 'navigation', 'translation']; private $_refereeAccount; @@ -42,9 +43,9 @@ public function setUp() { parent::setUp(); - $userRole = Opus_UserRole::fetchByName('reviewer'); + $userRole = UserRole::fetchByName('reviewer'); - $account = new Opus_Account(); + $account = new Account(); $account->setLogin('referee'); $account->setPassword('refereereferee'); $account->setRole([$userRole]); diff --git a/tests/security/ReviewerAndFullAdminTest.php b/tests/security/ReviewerAndFullAdminTest.php index f4d5ba9d70..45a207a8ea 100644 --- a/tests/security/ReviewerAndFullAdminTest.php +++ b/tests/security/ReviewerAndFullAdminTest.php @@ -1,6 +1,6 @@ - * @copyright Copyright (c) 2008-2019, OPUS 4 development team + * @copyright Copyright (c) 2008-2022, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ @@ -36,7 +34,7 @@ class ReviewerAndFullAdminTest extends ControllerTestCase protected $configModifiable = true; - protected $additionalResources = ['authz', 'database', 'translation', 'view', 'mainMenu', 'navigation']; + protected $additionalResources = ['database', 'translation', 'view', 'mainMenu', 'navigation']; public function setUp() { diff --git a/tests/security/ReviewerAndPartialAdminTest.php b/tests/security/ReviewerAndPartialAdminTest.php index 18af0fcd60..853653f961 100644 --- a/tests/security/ReviewerAndPartialAdminTest.php +++ b/tests/security/ReviewerAndPartialAdminTest.php @@ -1,6 +1,6 @@ - * @copyright Copyright (c) 2008-2019, OPUS 4 development team + * @copyright Copyright (c) 2008-2022, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ @@ -36,7 +34,7 @@ class ReviewerAndPartialAdminTest extends ControllerTestCase protected $configModifiable = true; - protected $additionalResources = ['authz', 'database', 'translation', 'view', 'mainMenu', 'navigation']; + protected $additionalResources = ['database', 'translation', 'view', 'mainMenu', 'navigation']; public function setUp() { diff --git a/tests/security/ReviewerTest.php b/tests/security/ReviewerTest.php index 0f4335313f..b2a7d984ea 100644 --- a/tests/security/ReviewerTest.php +++ b/tests/security/ReviewerTest.php @@ -1,6 +1,6 @@ - * @copyright Copyright (c) 2008-2019, OPUS 4 development team + * @copyright Copyright (c) 2008-2022, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ @@ -36,7 +34,7 @@ class ReviewerTest extends ControllerTestCase protected $configModifiable = true; - protected $additionalResources = ['authz', 'database', 'translation', 'view', 'mainMenu']; + protected $additionalResources = ['database', 'translation', 'view', 'mainMenu']; public function setUp() { diff --git a/tests/security/SecurityAdminTest.php b/tests/security/SecurityAdminTest.php index 7575243034..7f8d0d632d 100644 --- a/tests/security/SecurityAdminTest.php +++ b/tests/security/SecurityAdminTest.php @@ -1,5 +1,6 @@ - * @author Jens Schwidder - * @copyright Copyright (c) 2008-2019, OPUS 4 development team + * @copyright Copyright (c) 2008-2022, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ class SecurityAdminTest extends ControllerTestCase @@ -35,7 +33,7 @@ class SecurityAdminTest extends ControllerTestCase protected $configModifiable = true; - protected $additionalResources = ['authz', 'view', 'navigation', 'mainMenu', 'database', 'translation']; + protected $additionalResources = ['view', 'navigation', 'mainMenu', 'database', 'translation']; public function setUp() { diff --git a/tests/security/SeriesAdminTest.php b/tests/security/SeriesAdminTest.php index d9809e5a67..88e292026d 100644 --- a/tests/security/SeriesAdminTest.php +++ b/tests/security/SeriesAdminTest.php @@ -1,5 +1,4 @@ enableSecurity(); - $userRole = new Opus_UserRole(); + $userRole = new UserRole(); $userRole->setName($this->roleName); $userRole->appendAccessModule('admin'); $userRole->appendAccessModule('resource_series'); $userRole->store(); - $user = new Opus_Account(); + $user = new Account(); $user->setLogin($this->userName); $user->setPassword('seriesadminpwd'); $user->addRole($userRole); @@ -67,10 +69,10 @@ public function tearDown() $this->logoutUser(); $this->restoreSecuritySetting(); - $user = Opus_Account::fetchAccountByLogin($this->userName); + $user = Account::fetchAccountByLogin($this->userName); $user->delete(); - $userRole = Opus_UserRole::fetchByName($this->roleName); + $userRole = UserRole::fetchByName($this->roleName); $userRole->delete(); parent::tearDown(); diff --git a/tests/simple.ini b/tests/simple.ini index 2c91bbe0fa..b76c468338 100644 --- a/tests/simple.ini +++ b/tests/simple.ini @@ -57,3 +57,5 @@ resources.frontController.returnResponse=0 workspacePath = APPLICATION_PATH "/workspace" [testing : production] + +opus.disableDatabaseVersionCheck = 1 diff --git a/tests/sql/990_create_documents_testdata__hhhar.sql b/tests/sql/990_create_documents_testdata__hhhar.sql index 7fb9d0d952..a08aa7ca0f 100644 --- a/tests/sql/990_create_documents_testdata__hhhar.sql +++ b/tests/sql/990_create_documents_testdata__hhhar.sql @@ -663,7 +663,7 @@ INSERT INTO `document_subjects` (`id`, `document_id`, `language`, `type`, `value (103, 41, 'deu', 'swd', 'Fluid-Struktur-Wechselwirkung', NULL), (104, 41, 'deu', 'swd', 'Nichtlineare Dynamik', NULL), (105, 41, 'deu', 'swd', 'Verzweigung ', NULL), -(106, 41, 'deu', 'swd', '\n Dynamische Verzweigung', NULL), +(106, 41, 'deu', 'swd', 'Dynamische Verzweigung', NULL), (107, 41, 'deu', 'swd', 'Ordnungsreduktion', NULL), (108, 41, 'deu', 'uncontrolled', 'Kalman-Filter', NULL), (109, 41, 'deu', 'uncontrolled', 'Schiff', NULL), @@ -965,7 +965,7 @@ INSERT INTO `document_title_abstracts` (`id`, `document_id`, `type`, `value`, `l (100, 40, 'abstract', 'In den letzten Jahren hat sich die endovaskuläre Versorgung von abdominalen Aorten-Aneurysmen mittels Stentgrafts neben der konventionellen, offenen Operation als Alternativverfahren zur Vermeidung einer Gefäßruptur etabliert. Das erkrankte Gefäß wird durch eine Schlauchprothese überbrückt und somit vom systemischen Druck abgeschirmt. Trotz der Weiterentwicklung von endovaskulären Aortenprothesen in den letzten 15 Jahren weist die minimal-invasive Versorgung noch eine Re-Interventionsrate von 20% innerhalb von 4 Jahren auf. Mangelnde Abdichtung und Migration der Prothesen zählen zu den häufigsten Versagensursachen.\nIn dieser Arbeit wurden Faktoren für das Versagen von Stentgrafts identifiziert, Grundlagen zur Testung dieser Prothesen gelegt sowie Designkriterien zur Weiterentwicklung dieser Prothesen abgeleitet. Auf Grundlage von klinischen Daten, Experimenten und Berechnungen wurde eine Bestimmung und Beurteilung von Migrations- und Abdichtungsparameter qualitativ\nund quantitativ ermöglicht.\nIn 80% der untersuchten Patienten waren ein Fixierungsverlust infolge einer Gefäßdilatation oder das Abknicken der Prothese verantwortlich für die Migration der Prothesen. Es wurde gezeigt, dass die Permeabilität von Thrombus zu einem erhöhten Druck im Aneurysmasack und somit zu einem Versagen der Behandlung bei wasserdurchlässigen Prothesen und kurzen Fixierungszonen führt. Endoleckagen II verursachen eine Wiederbelastung der Gefäßwand bis zu Werten des systemischen Drucks und führen häufig zum Anwachsen des Aneurysmas.\nAufgrund der hohen Inzidenz dieser Leckage wurde ein neues Prothesendesign in Form einer dünnen, überdimensionierten Membran entwickelt, welche einen Verschluss der Kollateralen ermöglicht. Erste Ergebnisse zeigten, dass durch das Auskleiden des Aneurysmas eine verbesserte Abdichtung des Aneurysmas im Vergleich zu einer Standardprothese und eine adäquate Fixierung im Gefäß erzielt werden.', 'deu'), (101, 40, 'abstract', 'In recent years minimally-invasive endovascular surgery of abdominal aortic aneurysms by means of stentgrafts has emerged alongside conventional open surgery as an alternative procedure for the prevention of vessel rupture. The degenerated vessel is bridged by a tubular prosthesis and is thereby decoupled from the systemic pressure. Despite the continuous evolution of endovascular stentgrafts over the last 15 years minimally-invasive treatment still suffers\na re-intervention rate of 20% within 4 years. Inadequate sealing and migration of the prostheses rank among the most frequent failure causes.\nIn this study, factors of stentgraft failure were identified, basic principles for component testing were established and design criteria for the development of prostheses were derived.\nBased on clinical data, parametric and patient-specific in vitro experiments and on mathematical models, fixation and flow forces were related to occurrence of migration in individual patients. Based on in vitro permeability measurements of thrombus and clotted grafts an analytical model was used to investigate the role of the thrombus as a sealing medium against pressure build-up in the aneurysm sac. Additionally, the influence of retrograde flow through the collateral vessels into the bridged aneurysm (endoleak II) on the pressure acting in the aneurysm was analyzed.\nIn 80% of the patient data examined, a loss of fixation due to vessel dilation in the fixation region, or kinking of the prosthesis, were responsible for migration of the prostheses. The permeability of the thrombus was found to be sufficiently high to lead to pressurisation of the aneurysm sac and thus to a failure of the treatment for a permeable prosthesis and short attachment zones. Endoleak II was found topotentially lead to re-pressurization of the vessel\nwall up to the systemic pressure and was frequently found to be the cause for dilatation of the aneurysm clinically.\nDue to the high incidence of this leakage type a new design was proposed, to completely seal the collateral vessels by means of a thin, oversized membrane. It was demonstrated that sealing of the aneurysm was improved in comparison to a standard prosthesis and appropriate fixation stability could be achieved with the new implant design.', 'eng'), (102, 41, 'main', 'Ein Beitrag zur numerischen und experimentellen Untersuchung extremer Schiffsbewegungen', 'deu'), -(103, 41, 'abstract', 'Die Dynamik von Schiffen kann bei kleinen Anregungen durch lineare Modelle exakt beschrieben und analysiert \n werden. Wachsen die Anregungen, können die Bewegungen Amplituden annehmen, bei denen die Nichtlinearitäten des Systems nicht mehr \n vernachlässigt werden können. In diesen Fällen können das Bewegungsverhalten und das Vorhandensein kritischer Bewegungszustände nur \n noch im Zeitbereich untersucht werden, was auf Simulationen hinausläuft. Das Ergebnis einer Simulation eines nichtlinearen dynamischen \n Systems ist jedoch stark von den Parametern des Systems sowie von den Anfangsbedingungen abhängig, so dass zu jeder Kombination aus \n Anfangsbedingungen und Systemparametern eine Simulation erstellt werden müsste, um die Reaktion eines Schiffes auf alle relevanten \n Seegangsbedingungen bewerten zu können.\n\nSeit zwei Jahrzehnten stehen effiziente mathematische Analyseverfahren zur Behandlung stark nichtlinearer Probleme zur Verfügung. In dieser Arbeit wird \nmit Hilfe der lokalen Verzweigungsanalyse die Existenz kritischer Bewegungsformen gezeigt. Die hydrodynamischen Kräfte und Momente werden dabei mit dem \nProgrammpaket Simbel berechnet. Trotz einer Modifikation der in Simbel implementierten Hydrodynamikberechnung stellte sich heraus, dass die Analyse eines \nvollständig modellierten Schiffes bis heute noch nicht zufriedenstellend gelingt, da die Rechenzeiten immer noch sehr lang sind. Das gleiche gilt für die \nMöglichkeit, in Versuchen preisgünstig gezielt kritische Stellen, die zu einer abrupten Änderung des Systemverhaltens durch eine minimale \nParameteränderung führen, im Experiment zu zeigen. Dabei soll es in diesen Versuchen im Entwicklungsstadium der Methoden nicht um die Untersuchung eines \nspeziellen Schiffsrumpfes unter möglichst realen Seegangsbedingungen gehen, sondern um den experimentellen Nachweis der numerisch ermittelten Phänomene. \n\nIn der vorgestellten Arbeit wird zu beiden Problemen ein Lösungsansatz entwickelt und die Tauglichkeit demonstriert. Für die Versuche ist ein Versuchsschwimmkörper mit einfacher Geometrie entwickelt worden, mit dem im Labor des Institutes umfangreiche Parameterstudien kostengünstig durchgeführt\nwerden können. Das dafür entwickelte berührungslose Positions- und Lagemesssystem liefert Messwerte mit einer Genauigkeit von bis zu einem halben Millimeter in den translatorischen und von einem Hundertstel Grad bei den rotatorischen Freiheitsgraden bei einer Frequenz von 228Hz. Diese Präzision bei einer so hohen Dynamik wird durch den Einsatz eines integrierten Messsystems aus Stereokamera und einer Inertialmesseinheit (IMU) der tactical grade–Klasse, die durch ein erweitertes kontinuierlich–diskretes Kalman–Filter in Echtzeit miteinander kombiniert werden, erreicht. Sowohl die IMU als auch die Stereokamera wurden aus Standardkomponenten aufgebaut, so dass sämtliche Sensorrohdaten und die Zwischenwerte jeder Verarbeitungsstufe vorliegen. Dieser Vorteil im Vergleich zum Einsatz einer kommerziellen IMU oder Stereokamera ermöglicht die Umsetzung unterschiedlicher Integrationstiefen bei der Kombination beider Systeme. In der rechenintensivsten Variante werden Parameter beider Subsysteme als Zustandsgröße des Gesamtsystems geführt, so dass sich einzelne Kameraparameter und IMU–Sensorfehler während des Betriebs schätzen und kompensieren lassen. Im Wellenkanal des Institutes für Mechanik und Meerestechnik ist kein Platz für umfangreiche Manöver oder Tests mit dem fahrenden Schwimmkörper vorhanden. Daher werden die Versuche hier auf einen\nstehenden oder langsam fahrenden Schwimmkörper beschränkt, was jedoch nur eine geringe Einschränkung für die Methodenvalidierung bedeutet. Durch ein dynamisches Positioniersystem wird der Schwimmkörper bei Wellenanregungen auf seiner Sollposition gehalten, ohne dass dabei die Roll- oder die Stampfbewegungen nennenswert angeregt werden. Die Positioniergenauigkeit liegt bei schwachen Anregungen bei schlimmstenfalls ±2mm, bei hohen Wellen und starken Bewegungen liegt die Genauigkeit bei ca. ±10mm quer zu den Wellen und ca. ±30mm in Wellenrichtung.\n\nMit dieser Versuchsanordnung ist es zukünftig möglich, unter beliebigen Winkeln zu den einfallenden Wellen gut wiederholbare Messungen durchzuführen, bei denen man sich in Abstimmung mit den Berechnungen den kritischen Systemzuständen nähern kann. Da die Messungen, die Regelung und die Wellenklappensteuerung miteinander vernetzt sind, kann diese Parametersuche weitestgehend automatisiert ablaufen und gegebenenfalls durch Optimierer beschleunigt werden. \n\nDie numerischen Untersuchungen werden durch ein hier in dieser Arbeit entwickeltes Modellreduktionsverfahren beschleunigt, mit dem die Ordnung des mathematischen Systems deutlich reduziert werden kann. Dies verkürzt zum einen die Rechenzeit, führt aber vor allen Dingen zu einem schnelleren Einschwingen des Systems auf eine periodische Bewegung.', 'deu'), +(103, 41, 'abstract', 'Die Dynamik von Schiffen kann bei kleinen Anregungen durch lineare Modelle exakt beschrieben und analysiert \n werden. Wachsen die Anregungen, können die Bewegungen Amplituden annehmen, bei denen die Nichtlinearitäten des Systems nicht mehr \n vernachlässigt werden können. In diesen Fällen können das Bewegungsverhalten und das Vorhandensein kritischer Bewegungszustände nur \n noch im Zeitbereich untersucht werden, was auf Simulationen hinausläuft. Das Ergebnis einer Simulation eines nichtlinearen dynamischen \n Systems ist jedoch stark von den Parametern des Systems sowie von den Anfangsbedingungen abhängig, so dass zu jeder Kombination aus \n Anfangsbedingungen und Systemparametern eine Simulation erstellt werden müsste, um die Reaktion eines Schiffes auf alle relevanten \n Seegangsbedingungen bewerten zu können.\n\nSeit zwei Jahrzehnten stehen effiziente mathematische Analyseverfahren zur Behandlung stark nichtlinearer Probleme zur Verfügung. In dieser Arbeit wird \nmit Hilfe der lokalen Verzweigungsanalyse die Existenz kritischer Bewegungsformen gezeigt. Die hydrodynamischen Kräfte und Momente werden dabei mit dem \nProgrammpaket Simbel berechnet. Trotz einer Modifikation der in Simbel implementierten Hydrodynamikberechnung stellte sich heraus, dass die Analyse eines \nvollständig modellierten Schiffes bis heute noch nicht zufriedenstellend gelingt, da die Rechenzeiten immer noch sehr lang sind. Das gleiche gilt für die \nMöglichkeit, in Versuchen preisgünstig gezielt kritische Stellen, die zu einer abrupten Änderung des Systemverhaltens durch eine minimale \nParameteränderung führen, im Experiment zu zeigen. Dabei soll es in diesen Versuchen im Entwicklungsstadium der Methoden nicht um die Untersuchung eines \nspeziellen Schiffsrumpfes unter möglichst realen Seegangsbedingungen gehen, sondern um den experimentellen Nachweis der numerisch ermittelten Phänomene. \n\nIn der vorgestellten Arbeit wird zu beiden Problemen ein Lösungsansatz entwickelt und die Tauglichkeit demonstriert. Für die Versuche ist ein Versuchsschwimmkörper mit einfacher Geometrie entwickelt worden, mit dem im Labor des Institutes umfangreiche Parameterstudien kostengünstig durchgeführt\nwerden können. Das dafür entwickelte berührungslose Positions- und Lagemesssystem liefert Messwerte mit einer Genauigkeit von bis zu einem halben Millimeter in den translatorischen und von einem Hundertstel Grad bei den rotatorischen Freiheitsgraden bei einer Frequenz von 228Hz. Diese Präzision bei einer so hohen Dynamik wird durch den Einsatz eines integrierten Messsystems aus Stereokamera und einer Inertialmesseinheit (IMU) der tactical grade–Klasse, die durch ein erweitertes kontinuierlich–diskretes Kalman–Filter in Echtzeit miteinander kombiniert werden, erreicht. Sowohl die IMU als auch die Stereokamera wurden aus Standardkomponenten aufgebaut, so dass sämtliche Sensorrohdaten und die Zwischenwerte jeder Verarbeitungsstufe vorliegen. Dieser Vorteil im Vergleich zum Einsatz einer kommerziellen IMU oder Stereokamera ermöglicht die Umsetzung unterschiedlicher Integrationstiefen bei der Kombination beider Systeme. In der rechenintensivsten Variante werden Parameter beider Subsysteme als Zustandsgröße des Gesamtsystems geführt, so dass sich einzelne Kameraparameter und IMU–Sensorfehler während des Betriebs schätzen und kompensieren lassen. Im Wellenkanal des Institutes für Mechanik und Meerestechnik ist kein Platz für umfangreiche Manöver oder Tests mit dem fahrenden Schwimmkörper vorhanden. Daher werden die Versuche hier auf einen\nstehenden oder langsam fahrenden Schwimmkörper beschränkt, was jedoch nur eine geringe Einschränkung für die Methodenvalidierung bedeutet. Durch ein dynamisches Positioniersystem wird der Schwimmkörper bei Wellenanregungen auf seiner Sollposition gehalten, ohne dass dabei die Roll- oder die Stampfbewegungen nennenswert angeregt werden. Die Positioniergenauigkeit liegt bei schwachen Anregungen bei schlimmstenfalls ±2mm, bei hohen Wellen und starken Bewegungen liegt die Genauigkeit bei ca. ±10mm quer zu den Wellen und ca. ±30mm in Wellenrichtung.\n\nMit dieser Versuchsanordnung ist es zukünftig möglich, unter beliebigen Winkeln zu den einfallenden Wellen gut wiederholbare Messungen durchzuführen, bei denen man sich in Abstimmung mit den Berechnungen den kritischen Systemzuständen nähern kann. Da die Messungen, die Regelung und die Wellenklappensteuerung miteinander vernetzt sind, kann diese Parametersuche weitestgehend automatisiert ablaufen und gegebenenfalls durch Optimierer beschleunigt werden. \n\nDie numerischen Untersuchungen werden durch ein hier in dieser Arbeit entwickeltes Modellreduktionsverfahren beschleunigt, mit dem die Ordnung des mathematischen Systems deutlich reduziert werden kann. Dies verkürzt zum einen die Rechenzeit, führt aber vor allen Dingen zu einem schnelleren Einschwingen des Systems auf eine periodische Bewegung.', 'deu'), (104, 42, 'main', 'Charakterisierung von MOS-Transistoren vor und nach Gateoxiddurchbruch', 'deu'), (105, 42, 'main', 'Characterization of MOS transistors before and after gate oxide breakdown', 'eng'), (106, 42, 'abstract', 'Die fortschreitende Skalierung und zunehmende Packungsdichte integrierter Schaltkreise führt zu immer höheren Belastungen der elektronischen Bauelemente. Bei MOS-Transistoren erhöht sich dadurch die Wahrscheinlichkeit eines Gateoxiddurchbruchs. In der vorliegenden Arbeit werden Untersuchungen zum Verhalten von MOS-Transistoren vor und nach einem Gateoxiddurchbruch präsentiert. Dabei werden unterschiedliche Durchbruchsarten klassifiziert und Modelle für die DC-Kennlinien sowie für das Rauschen (Random Telegraph Signals) nach Durchbruch entwickelt. Mit Hilfe der Modelle wird abschließend die Funktion ausgewählter analoger und digitaler Schaltungen analysiert. Es zeigt sich, daß je nach Anwendung und Durchbruchstyp auch nach Durchbruch eines Transistors die Funktion der Schaltkreise erhalten bleiben kann. Mit diesem Ansatz kann bereits während der Design-Phase die Zuverlässigkeit der Schaltung untersucht werden.', 'deu'), diff --git a/tests/support/AccessModuleAdminOneResourceOnlyTest.php b/tests/support/AccessModuleAdminOneResourceOnlyTest.php index 290bf20bda..7342ec1a7c 100644 --- a/tests/support/AccessModuleAdminOneResourceOnlyTest.php +++ b/tests/support/AccessModuleAdminOneResourceOnlyTest.php @@ -1,6 +1,6 @@ - * @copyright Copyright (c) 2008-2019, OPUS 4 development team + * @copyright Copyright (c) 2008-2022, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License * * TODO statt der Redirect Prüfung (für Access) eine Funktion definieren (assertNoAccess) @@ -38,7 +36,7 @@ abstract class AccessModuleAdminOneResourceOnlyTest extends ControllerTestCase protected $configModifiable = true; - protected $additionalResources = ['authz', 'database', 'view', 'mainMenu', 'navigation', 'translation']; + protected $additionalResources = ['database', 'view', 'mainMenu', 'navigation', 'translation']; private $acls = [ 'module_admin' => false, diff --git a/tests/support/AssumptionChecker.php b/tests/support/AssumptionChecker.php index 1442f64e79..077fd4ac71 100644 --- a/tests/support/AssumptionChecker.php +++ b/tests/support/AssumptionChecker.php @@ -59,12 +59,12 @@ public function checkYearFacetAssumption() $this->testCase->resetRequest(); $this->testCase->resetResponse(); - Zend_Registry::get('Zend_Config')->merge(new Zend_Config( - ['searchengine' => ['solr' => [ + $this->adjustConfiguration([ + 'searchengine' => ['solr' => [ 'facetlimit' => ['year' => '10', 'year_inverted' => '10'], 'facets' => 'year,doctype,author_facet,language,has_fulltext,belongs_to_bibliography,subject,institute' - ]]] - )); + ]] + ]); $this->testCase->dispatch('/solrsearch/index/search/searchtype/all'); @@ -90,12 +90,12 @@ public function checkYearFacetAssumption() for ($i = 0; $i < 10; $i++) { $lastPos = strpos($response, '>' . $searchStrings[$i] . '', $lastPos); if ($lastPos === false) { - Zend_Debug::dump("'" . $searchStrings[$i] . '\' not found in year facet list (iteration ' . $i . ')'); + \Zend_Debug::dump("'" . $searchStrings[$i] . '\' not found in year facet list (iteration ' . $i . ')'); } $this->testCase->assertFalse($lastPos === false, "'" . $searchStrings[$i] . '\' not found in year facet list (iteration ' . $i . ')'); if ($lastPos === false) { - break; $loopComplete = false; + break; } } $this->testCase->assertTrue($loopComplete); diff --git a/tests/support/ControllerTestCase.php b/tests/support/ControllerTestCase.php index d06fc82138..623ae11be0 100644 --- a/tests/support/ControllerTestCase.php +++ b/tests/support/ControllerTestCase.php @@ -1,4 +1,5 @@ - * @author Thoralf Klein - * @author Michael Lang - * @copyright Copyright (c) 2008-2020, OPUS 4 development team + * @copyright Copyright (c) 2008-2021, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Config; +use Opus\Db\TableGateway; +use Opus\Document; +use Opus\Doi\DoiManager; +use Opus\File; +use Opus\Repository; +use Opus\UserRole; +use Opus\Model\ModelException; +use Opus\Model\NotFoundException; +use Opus\Security\AuthAdapter; +use Opus\Security\Realm; +use Opus\Security\SecurityException; + /** * Base class for controller tests. * @@ -67,6 +77,8 @@ class ControllerTestCase extends TestCase private $cleanupModels; + private $baseConfig = null; + /** * Method to initialize Zend_Application for each test. */ @@ -104,14 +116,55 @@ public function tearDown() $this->logger = null; + DoiManager::setInstance(null); Application_Configuration::clearInstance(); // reset Application_Configuration + Application_Translate::setInstance(null); + Application_Security_AclProvider::clear(); parent::tearDown(); } + /** + * Overwrites selected properties of current configuration. + * + * @note A test doesn't need to backup and recover replaced configuration as + * this is done in setup and tear-down phases. + * + * @param array $overlay properties to overwrite existing values in configuration + * @param callable $callback callback to invoke with adjusted configuration before enabling e.g. to delete some options + * @return \Zend_Config reference on updated configuration + */ + protected function adjustConfiguration($overlay, $callback = null) + { + $previous = Config::get(); + + if ($this->baseConfig === null) { + $this->baseConfig = $previous; + } + + $updated = new \Zend_Config($previous->toArray(), true); + + $updated->merge(new \Zend_Config($overlay)); + + if (is_callable($callback)) { + $updated = call_user_func($callback, $updated); + } + + Config::set($updated); + + return $updated; + } + + protected function resetConfiguration() + { + if ($this->baseConfig !== null) { + Config::set($this->baseConfig); + } + } + public function getApplication() { - return new Zend_Application( + return new \Zend_Application( $this->applicationEnv, ["config" => [ APPLICATION_PATH . '/application/configs/application.ini', @@ -132,7 +185,7 @@ public function cleanupBefore() $this->closeDatabaseConnection(); // Resetting singletons or other kinds of persistent objects. - Opus_Db_TableGateway::clearInstances(); + TableGateway::clearInstances(); // Clean-up possible artifacts in $_SERVER of previous test. unset($_SERVER['REMOTE_ADDR']); @@ -142,7 +195,7 @@ public function cleanupBefore() public function cleanupDatabase() { - if (! is_null(Zend_Db_Table::getDefaultAdapter())) { + if (! is_null(\Zend_Db_Table::getDefaultAdapter())) { $this->deleteTestDocuments(); // data integrity checks TODO should be made unnecessary @@ -166,7 +219,7 @@ public function additionalChecks() */ protected function checkDoc146() { - $doc = new Opus_Document(146); + $doc = Document::get(146); $modified = $doc->getServerDateModified(); $this->assertEquals(2012, $modified->getYear()); @@ -174,7 +227,7 @@ protected function checkDoc146() protected function checkDoc1() { - $doc = new Opus_Document(1); + $doc = Document::get(1); $modified = $doc->getServerDateModified(); $this->assertEquals(2010, $modified->getYear()); @@ -182,7 +235,7 @@ protected function checkDoc1() protected function closeDatabaseConnection() { - $adapter = Zend_Db_Table::getDefaultAdapter(); + $adapter = \Zend_Db_Table::getDefaultAdapter(); if ($adapter) { $adapter->closeConnection(); } @@ -227,41 +280,54 @@ protected function checkForBadStringsInHtml($body) */ public function loginUser($login, $password) { - $adapter = new Opus_Security_AuthAdapter(); + $adapter = new AuthAdapter(); $adapter->setCredentials($login, $password); - $auth = Zend_Auth::getInstance(); + $auth = \Zend_Auth::getInstance(); $auth->authenticate($adapter); $this->assertTrue($auth->hasIdentity()); - $config = Zend_Registry::get('Zend_Config'); + $user = \Zend_Auth::getInstance()->getIdentity(); + + if (! is_null($user)) { + try { + $realm = Realm::getInstance(); + $realm->setUser($user); + } catch (SecurityException $ose) { + // unknown user -> invalidate session (logout) + \Zend_Auth::getInstance()->clearIdentity(); + $user = null; + } + } + + $config = Config::get(); if (isset($config->security) && filter_var($config->security, FILTER_VALIDATE_BOOLEAN)) { Application_Security_AclProvider::init(); // make sure ACLs are not cached in action helper TODO find better solution try { - $accessControl = Zend_Controller_Action_HelperBroker::getExistingHelper('accessControl'); + $accessControl = \Zend_Controller_Action_HelperBroker::getExistingHelper('accessControl'); $accessControl->setAcl(null); - } catch (Zend_Controller_Action_Exception $excep) { + } catch (\Zend_Controller_Action_Exception $excep) { } } } public function logoutUser() { - $instance = Zend_Auth::getInstance(); + $instance = \Zend_Auth::getInstance(); if (! is_null($instance)) { $instance->clearIdentity(); } - $realm = Opus_Security_Realm::getInstance(); + $realm = Realm::getInstance(); $realm->setUser(null); $realm->setIp(null); // make sure ACLs are not cached in action helper TODO find better solution try { - $accessControl = Zend_Controller_Action_HelperBroker::getExistingHelper('accessControl'); + $accessControl = \Zend_Controller_Action_HelperBroker::getExistingHelper('accessControl'); $accessControl->setAcl(null); - } catch (Zend_Controller_Action_Exception $excep) { + } catch (\Zend_Controller_Action_Exception $excep) { } } @@ -281,14 +347,13 @@ protected function requireSolrConfig() /** * Modifies Solr configuration to un unknown core to simulate connection failure. - * @throws Zend_Exception + * @throws \Zend_Exception */ protected function disableSolr() { - $config = Zend_Registry::get('Zend_Config'); // TODO old config path still needed? // $config->searchengine->index->app = 'solr/corethatdoesnotexist'; - $config->merge(new Zend_Config([ + $this->adjustConfiguration([ 'searchengine' => [ 'solr' => [ 'default' => [ @@ -302,12 +367,12 @@ protected function disableSolr() ] ] ] - ])); + ]); } /** * - * @param Zend_Controller_Response_Abstract $response + * @param \Zend_Controller_Response_Abstract $response * @param string $location */ protected function assertResponseLocationHeader($response, $location) @@ -324,17 +389,19 @@ protected function assertResponseLocationHeader($response, $location) public function enableSecurity() { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $this->securityEnabled = $config->security; $config->security = self::CONFIG_VALUE_TRUE; - Zend_Registry::set('Zend_Config', $config); + Application_Security_AclProvider::init(); } + /** + * TODO is this needed for tearDown? + */ public function restoreSecuritySetting() { - $config = Zend_Registry::get('Zend_Config'); + $config = $this->getConfig(); $config->security = $this->securityEnabled; - Zend_Registry::set('Zend_Config', $config); } /** @@ -342,9 +409,9 @@ public function restoreSecuritySetting() */ public function useGerman() { - $session = new Zend_Session_Namespace(); + $session = new \Zend_Session_Namespace(); $session->language = 'de'; - Zend_Registry::get('Zend_Translate')->setLocale('de'); + Application_Translate::getInstance()->setLocale('de'); Application_Form_Element_Language::initLanguageList(); } @@ -353,9 +420,9 @@ public function useGerman() */ public function useEnglish() { - $session = new Zend_Session_Namespace(); + $session = new \Zend_Session_Namespace(); $session->language = 'en'; - Zend_Registry::get('Zend_Translate')->setLocale('en'); + Application_Translate::getInstance()->setLocale('en'); Application_Form_Element_Language::initLanguageList(); } @@ -439,14 +506,14 @@ function ($public, $system, $context) use ($mapping) { // Array mit Fehlern ausgeben if (count($errors) !== 0) { - $output = Zend_Debug::dump($errors, 'XHTML Fehler', false); + $output = \Zend_Debug::dump($errors, 'XHTML Fehler', false); } else { $output = ''; } - $this->assertEquals( + $this->assertCount( 0, - count($errors), + $errors, 'XHTML Schemaverletzungen gefunden (' . count($errors) . ')' . PHP_EOL . $output ); @@ -489,7 +556,7 @@ public function verifyCommandAvailable($command) */ public function isFailTestOnMissingCommand() { - $config = Zend_Registry::get('Zend_Config'); + $config = Config::get(); return (isset($config->tests->failTestOnMissingCommand) && filter_var($config->tests->failTestOnMissingCommand, FILTER_VALIDATE_BOOLEAN)); } @@ -499,15 +566,15 @@ public function isFailTestOnMissingCommand() * * Fuer gruene Nachrichten Level muss self::MESSAGE_LEVEL_NOTICE verwendet werden. * - * @param $message Übersetzungsschlüssel bzw. Nachricht + * @param string $message Übersetzungsschlüssel bzw. Nachricht * @param string $level 'notice' oder 'failure' */ public function verifyFlashMessage($message, $level = self::MESSAGE_LEVEL_FAILURE) { - $flashMessenger = Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger'); + $flashMessenger = \Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger'); $flashMessages = $flashMessenger->getCurrentMessages(); - $this->assertEquals(1, count($flashMessages), 'Expected one flash message in queue.'); + $this->assertCount(1, $flashMessages, 'Expected one flash message in queue.'); $flashMessage = $flashMessages[0]; $this->assertEquals($message, $flashMessage['message']); @@ -519,15 +586,15 @@ public function verifyFlashMessage($message, $level = self::MESSAGE_LEVEL_FAILUR * * Fuer gruene Nachrichten Level muss self::MESSAGE_LEVEL_NOTICE verwendet werden. * - * @param $message Übersetzungsschlüssel bzw. Nachricht + * @param string $message Übersetzungsschlüssel bzw. Nachricht * @param string $level 'notice' oder 'failure' */ public function verifyNotFlashMessageContains($message, $level = self::MESSAGE_LEVEL_FAILURE) { - $flashMessenger = Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger'); + $flashMessenger = \Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger'); $flashMessages = $flashMessenger->getCurrentMessages(); - $this->assertEquals(1, count($flashMessages), 'Expected one flash message in queue.'); + $this->assertCount(1, $flashMessages, 'Expected one flash message in queue.'); $flashMessage = $flashMessages[0]; $this->assertNotContains($message, $flashMessage['message']); @@ -565,7 +632,7 @@ public function verifyBreadcrumbDefined($location = null) } } - $view = Zend_Registry::get('Opus_View'); + $view = $this->getView(); $path = explode('/', $location); @@ -585,7 +652,7 @@ public function verifyBreadcrumbDefined($location = null) if (! $breadcrumbDefined) { $breadcrumbDefined = true; - $translate = Zend_Registry::get('Zend_Translate'); + $translate = Application_Translate::getInstance(); $label = $page->getLabel(); @@ -607,14 +674,14 @@ public function verifyBreadcrumbDefined($location = null) */ public function dumpBody() { - Zend_Debug::dump($this->getResponse()->getBody()); + \Zend_Debug::dump($this->getResponse()->getBody()); } /** * Removes a test document from the database. * - * @param $value Opus_Document|int - * @throws Opus_Model_Exception + * @param $value Document|int + * @throws ModelException */ public function removeDocument($value) { @@ -623,10 +690,10 @@ public function removeDocument($value) } $doc = $value; - if (! ($value instanceof Opus_Document)) { + if (! ($value instanceof Document)) { try { - $doc = new Opus_Document($value); - } catch (Opus_Model_NotFoundException $e) { + $doc = Document::get($value); + } catch (NotFoundException $e) { // could not find document -> no cleanup operation required: exit silently return; } @@ -639,9 +706,9 @@ public function removeDocument($value) } try { - new Opus_Document($docId); - $doc->deletePermanent(); - } catch (Opus_Model_NotFoundException $omnfe) { + Document::get($docId); + $doc->delete(); + } catch (NotFoundException $omnfe) { // Model nicht gefunden -> alles gut (hoffentlich) $this->getLogger()->debug("Test document {$docId} was deleted successfully by test."); return; @@ -652,9 +719,9 @@ public function removeDocument($value) // make sure test documents have been deleted try { - new Opus_Document($docId); + Document::get($docId); $this->getLogger()->debug("Test document {$docId} was not deleted."); - } catch (Opus_Model_NotFoundException $omnfe) { + } catch (NotFoundException $omnfe) { // ignore - document was deleted successfully $this->getLogger()->debug("Test document {$docId} was deleted successfully."); } @@ -675,18 +742,28 @@ protected function deleteTestDocuments() protected function getDocument($docId) { - return new Opus_Document($docId); + return Document::get($docId); } + /** + * Returns finder for documents. + * @return DocumentFinderInterface + */ + protected function getDocumentFinder() + { + return Repository::getInstance()->getDocumentFinder(); + } + + /** * Erzeugt ein Testdokument, das nach der Testausführung automatisch aufgeräumt wird. * - * @return Opus_Document - * @throws Opus_Model_Exception + * @return Document + * @throws ModelException */ protected function createTestDocument() { - $doc = new Opus_Document(); + $doc = Document::new(); $this->addTestDocument($doc); return $doc; } @@ -723,9 +800,11 @@ protected function deleteTempFiles() /** * @param string $filename * @param string $filepath - * @return Opus_File - * @throws Opus_Model_Exception + * @return File + * @throws ModelException * @throws Zend_Exception + * + * TODO allow same filename in different locations */ protected function createOpusTestFile($filename, $filepath = null) { @@ -742,16 +821,27 @@ protected function createOpusTestFile($filename, $filepath = null) } $this->assertTrue(is_readable($filepath)); - $file = new Opus_File(); + $file = new File(); $file->setPathName(basename($filepath)); $file->setTempFile($filepath); if (array_key_exists($filename, $this->testFiles)) { - throw Exception('filenames should be unique'); + throw new \Exception('filenames should be unique'); } $this->testFiles[$filename] = $filepath; return $file; } + public function addFileToCleanup($filePath) + { + if ($this->testFiles === null) { + $this->testFiles = []; + } + + $fileName = basename($filePath); + + $this->testFiles[$fileName] = $filePath; + } + protected function deleteTestFiles() { if (! is_null($this->testFiles)) { @@ -808,11 +898,6 @@ protected function setWorkspacePath($path) $this->workspacePath = $path; } - protected function getConfig() - { - return Zend_Registry::get('Zend_Config'); - } - protected function createTestFolder() { $workspacePath = $this->getWorkspacePath(); @@ -890,13 +975,10 @@ protected function deleteFolder($path, $deleteOutsideWorkspace = false) public function assertSecurityConfigured() { - $this->assertEquals('1', Zend_Registry::get('Zend_Config')->security); - $this->assertTrue( - Zend_Registry::isRegistered('Opus_Acl'), - 'Expected registry key Opus_Acl to be set' - ); - $acl = Zend_Registry::get('Opus_Acl'); - $this->assertTrue($acl instanceof Zend_Acl, 'Expected instance of Zend_Acl'); + $this->assertEquals('1', Config::get()->security); + Application_Security_AclProvider::init(); + $acl = Application_Security_AclProvider::getAcl(); + $this->assertTrue($acl instanceof \Zend_Acl, 'Expected instance of Zend_Acl'); } public function resetSearch() @@ -912,7 +994,7 @@ public function resetSearch() */ public function setHostname($host) { - $view = Zend_Registry::get('Opus_View'); + $view = $this->getView(); $view->getHelper('ServerUrl')->setHost($host); } @@ -927,7 +1009,7 @@ public function setHostname($host) */ public function setBaseUrl($baseUrl) { - Zend_Controller_Front::getInstance()->setBaseUrl($baseUrl); + \Zend_Controller_Front::getInstance()->setBaseUrl($baseUrl); } /** @@ -941,14 +1023,16 @@ public function setBaseUrl($baseUrl) public function disableTranslation() { if (is_null($this->translatorBackup)) { - $this->translatorBackup = Zend_Registry::get('Zend_Translate'); + $this->translatorBackup = Application_Translate::getInstance(); } - Zend_Registry::set('Zend_Translate', new Application_Translate([ + $translate = new Application_Translate([ 'adapter' => 'array', 'content' => [], 'locale' => 'auto' - ])); + ]); + + Application_Translate::setInstance($translate); } /** @@ -959,7 +1043,7 @@ public function disableTranslation() public function enableTranslation() { if (! is_null($this->translatorBackup)) { - Zend_Registry::set('Zend_Translate', $this->translatorBackup); + Application_Translate::setInstance($this->translatorBackup); } } @@ -967,14 +1051,14 @@ public function enableTranslation() * Allow the given user (identified by his or her name) to access the given module. * Returns true if access permission was added; otherwise false. * - * @param $moduleName module name - * @param $userName user name + * @param string $moduleName module name + * @param string $userName user name * @return bool - * @throws \Opus\Model\Exception + * @throws ModelException */ protected function addModuleAccess($moduleName, $userName) { - $r = Opus_UserRole::fetchByName($userName); + $r = UserRole::fetchByName($userName); $modules = $r->listAccessModules(); if (! in_array($moduleName, $modules)) { $r->appendAccessModule($moduleName); @@ -988,14 +1072,14 @@ protected function addModuleAccess($moduleName, $userName) * Disallow the given user (identified by his or her name) to access the given module. * Returns true if access permission was removed; otherwise false. * - * @param $moduleName module name - * @param $userName user name + * @param string $moduleName module name + * @param string $userName user name * @return bool - * @throws \Opus\Model\Exception + * @throws ModelException */ protected function removeModuleAccess($moduleName, $userName) { - $r = Opus_UserRole::fetchByName($userName); + $r = UserRole::fetchByName($userName); $modules = $r->listAccessModules(); if (in_array($moduleName, $modules)) { $r->removeAccessModule($moduleName); @@ -1028,4 +1112,9 @@ protected function cleanupModels() } } } + + protected function getView() + { + return $this->application->getBootstrap()->getResource('view'); + } } diff --git a/tests/support/CrudControllerTestCase.php b/tests/support/CrudControllerTestCase.php index 75bdfd203b..5fe77fe881 100644 --- a/tests/support/CrudControllerTestCase.php +++ b/tests/support/CrudControllerTestCase.php @@ -29,9 +29,10 @@ * @author Jens Schwidder * @copyright Copyright (c) 2008-2013, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id$ */ +use Opus\Model\NotFoundException; + abstract class CrudControllerTestCase extends ControllerTestCase { @@ -106,7 +107,6 @@ public function testIndexAction() $this->assertAction('index'); $models = $this->getModels(); - ; $this->assertQuery('a.add', 'Kein Add Button gefunden.'); if (count($models) > 0) { @@ -224,7 +224,7 @@ public function testDeleteActionYes() try { $this->getModel($modelId); - } catch (Opus_Model_NotFoundException $omnfe) { + } catch (NotFoundException $omnfe) { // alles gut, Modell wurde geloescht } diff --git a/tests/support/DepositTestHelper.php b/tests/support/DepositTestHelper.php index addcb68754..77b4679cf8 100644 --- a/tests/support/DepositTestHelper.php +++ b/tests/support/DepositTestHelper.php @@ -28,9 +28,15 @@ * @package Tests * @author Sascha Szott * @author Jens Schwidder - * @copyright Copyright (c) 2016-2017 + * @copyright Copyright (c) 2016-2021 * @license http://www.gnu.org/licenses/gpl.html General Public License */ + +use Opus\Collection; +use Opus\CollectionRole; +use Opus\Config; +use Opus\Document; + class DepositTestHelper extends PHPUnit_Framework_Assert { @@ -46,8 +52,6 @@ class DepositTestHelper extends PHPUnit_Framework_Assert private $collectionNumber; - private $configBackup; - private $frontdoorUrl; public function getCollectionId() @@ -103,7 +107,7 @@ public function uploadFile($request, $fileName, $checksum = null) public function addImportCollection() { if (is_null($this->collectionId)) { - $collectionRole = Opus_CollectionRole::fetchByName('Import'); + $collectionRole = CollectionRole::fetchByName('Import'); $this->assertFalse( is_null($collectionRole), 'Collection Role "Import" is part of standard distribution since OPUS 4.5' @@ -111,7 +115,7 @@ public function addImportCollection() $rootCollection = $collectionRole->getRootCollection(); // create temporary collection - $collection = new Opus_Collection(); + $collection = new Collection(); $timestamp = time(); $this->collectionNumber = 'sword-test-number-' . $timestamp; $collection->setNumber($this->collectionNumber); @@ -120,24 +124,21 @@ public function addImportCollection() $rootCollection->addLastChild($collection); $this->collectionId = $collection->store(); - $this->configBackup = Zend_Registry::get('Zend_Config'); - $config = Zend_Registry::get('Zend_Config'); + $config = Config::get(); $config->sword->collection->default->number = $this->collectionNumber; $config->sword->collection->default->abstract = 'sword.collection.default.abstract'; $config->sword->collection->default->collectionPolicy = 'sword.collection.default.collectionPolicy'; $config->sword->collection->default->treatment = 'sword.collection.default.treatment'; $config->sword->collection->default->acceptPackaging = 'sword.collection.default.acceptPackaging'; - Zend_Registry::set('Zend_Config', $config); } } public function removeImportCollection() { if (! is_null($this->collectionId)) { - $collection = new Opus_Collection($this->collectionId); + $collection = new Collection($this->collectionId); $collection->delete(); $this->collectionId = null; - Zend_Registry::set('Zend_Config', $this->configBackup); } } @@ -239,7 +240,7 @@ public function checkAtomEntryDocument( $idNode = $entryChildren->item(0); $this->assertEquals('id', $idNode->nodeName); $docId = $idNode->nodeValue; - $doc = new Opus_Document($docId); + $doc = Document::get($docId); $this->assertNodeProperties(1, $entryChildren, 'updated', $doc->getServerDateCreated()); $this->assertNodeProperties(2, $entryChildren, 'title', $doc->getTitleMain(0)->getValue()); @@ -272,7 +273,7 @@ public function checkAtomEntryDocument( $this->frontdoorUrl = 'http:///frontdoor/index/index/docId/' . $docId; $this->assertEquals($this->frontdoorUrl, $attribute->nodeValue); - $config = Zend_Registry::get('Zend_Config'); + $config = Config::get(); $generatorValue = $config->sword->generator; $this->assertNodeProperties(5 + $offset, $entryChildren, 'generator', $generatorValue); diff --git a/tests/support/DummyValidator.php b/tests/support/DummyValidator.php index cd14797d61..66ab37a700 100644 --- a/tests/support/DummyValidator.php +++ b/tests/support/DummyValidator.php @@ -30,7 +30,7 @@ * @copyright Copyright (c) 2020 * @license http://www.gnu.org/licenses/gpl.html General Public License */ -class DummyValidator extends Zend_Validate_Abstract +class DummyValidator extends \Zend_Validate_Abstract { public function isValid($value) diff --git a/tests/support/FormElementTestCase.php b/tests/support/FormElementTestCase.php index 7e39b930f2..e4245a77d3 100644 --- a/tests/support/FormElementTestCase.php +++ b/tests/support/FormElementTestCase.php @@ -113,7 +113,7 @@ public function testConstruct() { $element = $this->getElement(); - $paths = $element->getPluginLoader(Zend_Form::DECORATOR)->getPaths(); + $paths = $element->getPluginLoader(\Zend_Form::DECORATOR)->getPaths(); $this->assertArrayHasKey('Application_Form_Decorator_', $paths); $this->assertContains('Application/Form/Decorator/', $paths['Application_Form_Decorator_']); } diff --git a/tests/support/LogFilter.php b/tests/support/LogFilter.php index b76175982b..de3e1da05f 100644 --- a/tests/support/LogFilter.php +++ b/tests/support/LogFilter.php @@ -29,7 +29,6 @@ * @author Jens Schwidder * @copyright Copyright (c) 2013-2014, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id: MockLogger.php 13692 2014-10-10 11:08:14Z schwidder $ */ /** @@ -37,7 +36,7 @@ * * TODO expand functionality */ -class LogFilter implements Zend_Log_Filter_Interface +class LogFilter implements \Zend_Log_Filter_Interface { private $messages = []; diff --git a/tests/support/MockAccessControl.php b/tests/support/MockAccessControl.php index 321b11f636..178b653a57 100644 --- a/tests/support/MockAccessControl.php +++ b/tests/support/MockAccessControl.php @@ -29,13 +29,12 @@ * @author Jens Schwidder * @copyright Copyright (c) 2008-2013, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id$ */ class MockAccessControl implements Application_Security_AccessControl { - private $defaultAnswer = false; + private $defaultAnswer; public function __construct($answer = false) { diff --git a/tests/support/MockLogger.php b/tests/support/MockLogger.php index e91999de07..d99acd8303 100644 --- a/tests/support/MockLogger.php +++ b/tests/support/MockLogger.php @@ -29,7 +29,6 @@ * @author Jens Schwidder * @copyright Copyright (c) 2013-2014, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id$ */ /** @@ -37,12 +36,12 @@ * * TODO Unterscheidung von Nachrichten in Log-Leveln? */ -class MockLogger extends Zend_Log +class MockLogger extends \Zend_Log { private $messages = []; - private $logger = null; + private $logger; public function __construct($logger = null) { diff --git a/tests/support/MockRealm.php b/tests/support/MockRealm.php index 9ba4cffe18..34a0cf154d 100644 --- a/tests/support/MockRealm.php +++ b/tests/support/MockRealm.php @@ -29,11 +29,11 @@ * @author Jens Schwidder * @copyright Copyright (c) 2008-2013, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id$ */ +use Opus\Security\IRealm; -class MockRealm implements Opus_Security_IRealm +class MockRealm implements IRealm { private $fileAllowed; @@ -68,9 +68,11 @@ public function getRoles() public function setUser($username) { } + public function setIp($ipaddress) { } + public function check($privilege, $documentServerState = null, $fileId = null) { } diff --git a/tests/support/SendMailMock.php b/tests/support/SendMailMock.php index f91673bce2..c77d168495 100644 --- a/tests/support/SendMailMock.php +++ b/tests/support/SendMailMock.php @@ -29,7 +29,6 @@ * @author Sascha Szott * @copyright Copyright (c) 2008-2011, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id$ */ class SendMailMock @@ -49,7 +48,7 @@ class SendMailMock * @param string $bodyText * @param array $address Recipients (array [#] => array ('name' => '...', 'address' => '...')) */ - public function sendMail($from, $fromName, $subject, $bodyText, $address) + public function sendMail(string $from, string $fromName, string $subject, string $bodyText, array $address) { $this->from = $from; $this->fromName = $fromName; diff --git a/tests/support/SimpleBootstrap.php b/tests/support/SimpleBootstrap.php index 8701c2b444..fa64388ef0 100644 --- a/tests/support/SimpleBootstrap.php +++ b/tests/support/SimpleBootstrap.php @@ -27,12 +27,17 @@ * @category Tests * @package Support * @author Jens Schwidder - * @copyright Copyright (c) 2019, OPUS 4 development team + * @copyright Copyright (c) 2019-2021, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License * * TODO take care of duplicated code (from regular bootstrap) - maybe SimpleBootstrap is not needed anymore? */ -class SimpleBootstrap extends Zend_Application_Bootstrap_Bootstrap + +use Opus\Config; +use Opus\Log; +use Opus\Log\LogService; + +class SimpleBootstrap extends \Zend_Application_Bootstrap_Bootstrap { /** @@ -52,8 +57,8 @@ class SimpleBootstrap extends Zend_Application_Bootstrap_Bootstrap */ protected function _initConfiguration() { - $config = new Zend_Config($this->getOptions(), true); - Zend_Registry::set('Zend_Config', $config); + $config = new \Zend_Config($this->getOptions(), true); + Config::set($config); return $config; } @@ -61,75 +66,20 @@ protected function _initConfiguration() * Setup Logging * * @throws Exception If logging file couldn't be opened. - * @return void + * @return Zend_Log * */ protected function _initLogging() { $this->bootstrap('Configuration'); - $config = $this->getResource('Configuration'); - $logFilename = "opus-console.log"; - $logfilePath = $config->workspacePath . '/log/' . $logFilename; - - $logfile = @fopen($logfilePath, 'a', false); - - if ($logfile === false) { - $path = dirname($logfilePath); - - if (! is_dir($path)) { - throw new Exception('Directory for logging does not exist'); - } else { - throw new Exception("Failed to open logging file: $logfilePath"); - } - } - - // Write ID string to global variables, so we can identify/match individual runs. - $GLOBALS['id_string'] = uniqid(); - - $format = '%timestamp% %priorityName% (%priority%, ID '.$GLOBALS['id_string'].'): %message%' . PHP_EOL; - $formatter = new Zend_Log_Formatter_Simple($format); - - $writer = new Zend_Log_Writer_Stream($logfile); - $writer->setFormatter($formatter); - - $logger = new Zend_Log($writer); - $logLevelName = 'INFO'; - $logLevelNotConfigured = false; - - if (isset($config->log->level)) { - $logLevelName = strtoupper($config->log->level); - } else { - $logLevelNotConfigured = true; - } - - $zendLogRefl = new ReflectionClass('Zend_Log'); - - $invalidLogLevel = false; - - $logLevel = $zendLogRefl->getConstant($logLevelName); - - if (empty($logLevel)) { - $logLevel = Zend_Log::INFO; - $invalidLogLevel = true; - } - - // filter log output - $priorityFilter = new Zend_Log_Filter_Priority($logLevel); - Zend_Registry::set('LOG_LEVEL', $logLevel); - $logger->addFilter($priorityFilter); - - if ($logLevelNotConfigured) { - $logger->warn("Log level not configured, using default '$logLevelName'."); - } + $logService = LogService::getInstance(); - if ($invalidLogLevel) { - $logger->err("Invalid log level '$logLevelName' configured."); - } + $logger = $logService->createLog(LogService::DEFAULT_LOG, null, null, $logFilename); - Zend_Registry::set('Zend_Log', $logger); + Log::set($logger); $logger->debug('Logging initialized'); diff --git a/tests/support/TestCase.php b/tests/support/TestCase.php index ad379065e8..3204ad6bf0 100644 --- a/tests/support/TestCase.php +++ b/tests/support/TestCase.php @@ -26,17 +26,20 @@ * * @category Application Unit Test * @author Jens Schwidder - * @copyright Copyright (c) 2008-2019, OPUS 4 development team + * @copyright Copyright (c) 2008-2021, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ +use Opus\Config; +use Opus\Log; + /** * Base class for application tests. * * TODO any effect vvv ? * @preserveGlobalState disabled */ -class TestCase extends Zend_Test_PHPUnit_ControllerTestCase +class TestCase extends \Zend_Test_PHPUnit_ControllerTestCase { protected $application; @@ -84,14 +87,14 @@ public function tearDown() public function cleanupBefore() { // FIXME Does it help with the mystery bug? - Zend_Registry::_unsetInstance(); + \Zend_Registry::_unsetInstance(); $this->resetAutoloader(); } public function getApplication() { - return new Zend_Application( + return new \Zend_Application( $this->applicationEnv, ["config" => [ APPLICATION_PATH . '/tests/simple.ini' @@ -125,8 +128,8 @@ public function appBootstrap() */ public function resetAutoloader() { - Zend_Loader_Autoloader::resetInstance(); - $autoloader = Zend_Loader_Autoloader::getInstance(); + \Zend_Loader_Autoloader::resetInstance(); + $autoloader = \Zend_Loader_Autoloader::getInstance(); $autoloader->suppressNotFoundWarnings(false); $autoloader->setFallbackAutoloader(true); } @@ -136,22 +139,26 @@ public function resetAutoloader() */ protected function closeLogfile() { - if (! Zend_Registry::isRegistered('Zend_Log')) { - return; - } + $log = Log::get(); - $log = Zend_Registry::get('Zend_Log'); if (isset($log)) { $log->__destruct(); - Zend_Registry::set('Zend_Log', null); } - Opus_Log::drop(); + Log::drop(); } + /** + * TODO adjustConfiguration also makes it configurable - so maybe not needed anymore + */ public function makeConfigurationModifiable() { - $config = new Zend_Config([], true); - Zend_Registry::set('Zend_Config', $config->merge(Zend_Registry::get('Zend_Config'))); + $config = new \Zend_Config([], true); + Config::set($config->merge(Config::get())); + } + + protected function getConfig() + { + return Config::get(); } }