Code Monkey home page Code Monkey logo

wp-browser's Introduction

wp-browser

You can use wp-browser to test WordPress sites, plugins and themes.

An easy and quick setup, with a default configuration that will work for most projects, run end-to-end tests, integration tests and unit tests all wit the same tool.

This document refers to version 4 of the project. If you're using version 3 or version 3.5, and are looking for the migration and troubleshooting guide, you can find it here

Requirements

Depending on the nature of your project, there are different requirements it will need to satisfy before getting started.

Site

  • Ensure you're running the vendor/bin/codecept init wpbrowser command from the root directory of your WordPress site.
  • Ensure the directory contains the WordPress installation files. In a standard scenario you should have extracted WordPress files in this directory.
  • Ensure your installation is configured: it should contain a wp-config.php file.

Plugin

  • Ensure you're running the vendor/bin/codecept init wpbrowser command from the root directory of your plugin; this should be the directory that contains the PHP file defining the plugin header.

Theme

  • Ensure you're running the vendor/bin/codecept init wpbrowser command from the root directory of your theme; this should be the directory that contains the style.css file defining [the theme header][7].

If you decide to use the quick installation, then your PHP version should have the sqlite3 extensions installed and activated. You can check this using the php -m command and verifying the sqlite3 extension is among the active extensions.

Installation

Add wp-browser to your project as a development dependency using Composer

cd my-wordrpess-project
composer require --dev lucatume/wp-browser

Initialize wp-browser to quickly configured to suite your project and setup:

vendor/bin/codecept init wpbrowser

The command will set up your project to run integration and end-to-end tests using:

  • SQLite as the database engine, leveraging the SQLite Database Integration plugin
  • PHP built-in web server to serve the WordPress site on localhost (e.g. http://localhost:8080)
  • Chromedriver to drive the local version of Chrome installed on your machine

If you're working on a plugin or theme project, the default configuration will add some extra steps:

  • install the latest version of WordPress in the tests/_wordpress directory
  • create a tests/_plugins directory: any file or directory in this directory will be symlinked into the WordPress installation in tests/_wordpress/wp-content/plugins
  • create a tests/_themes directory: any file or directory in this directory will be symlinked into the WordPress installation in tests/_wordpress/wp-content/themes

For most projects this configuration will be enough to get started with testing.

You can run your tests immediately using the vendor/bin/codecept run command.

Read more about the commands provided by the library here.

Using a custom configuration

If you decide to skip the default configuration, you will be able to set up wp-browser to suit your needs and local setup by editing the tests/.env file. The inline documentation in the file will guide you through the configuration process.

Read more about using a custom configuration here.

Getting support for wp-browser configuration and usage

The best place to get support for wp-browser is the project documentation.
Since this project builds on top of PHPUnit and Codeception, you can also refer to their documentation.

If you can't find the answer to your question here you can ask on the "Issues" section of the wp-browser repository taking care to provide as much information as possible.

Finally, you can contact me directly to set up a call to discuss your project needs and how wp-browser can help you.

Sponsors

A thanks to my sponsors: you make maintaining this project easier.

wp-browser's People

Contributors

aberkow avatar barryhughes avatar borkweb avatar brianhenryie avatar calvinalkan avatar cliffordp avatar discoinfiltrator avatar firejdl avatar hendrikroehm avatar iateadonut avatar jcabot avatar johnbillion avatar joppuyo avatar kadimi avatar kagg-design avatar kmbt avatar lots0logs avatar luc45 avatar lucasdemea avatar lucatume avatar maxchirkov avatar mboldt avatar mitogh avatar roborourke avatar sc0ttkclark avatar staabm avatar szepeviktor avatar tangrufus avatar timothybjacobs avatar zdenekca avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

wp-browser's Issues

[Facebook\WebDriver\Exception\WebDriverException] JSON decoding of remote response failed.

this is fantastic and I've just started using codeception+wp-browser

everything runs perfectly but I ran into an issue while trying out the webdriver though

I can't get it to work... I'm quite sure this is not a bug but a configuration error - apologies but I've been running in circles for a couple of hours and couldn't find anything useful on google

in the moment I enable WPWebDriver I get this error when running wpcept run

[Facebook\WebDriver\Exception\WebDriverException]                                                                                                                         
  JSON decoding of remote response failed.          

and immediately below follows the whole HTML page from the test site printed in my console...

I've made a script with wp-cli to quickly start a server but everything else, both the server, unit tests and codeception acceptance tests they all run fine - I'm on Ubuntu 15.10, phantomjs is correctly installed

this is my codeception.yml

actor: Tester
paths:
    tests: tests
    log: tests/_output
    data: tests/_data
    helpers: tests/_support
settings:
    bootstrap: _bootstrap.php
    colors: true
    memory_limit: 1024M
modules:
    enabled:
      - WPLoader
      - WPBrowser
      - WPWebDriver
    config:
        Db:
            dsn: 'mysql:host=localhost;dbname=wp_codeception_tests'
            user: wpcept
            password:
            dump: tests/_data/dump.sql
        WPBrowser:
            url: 'http://0.0.0.0:8080'
            adminUsername: admin
            adminPassword: password
            adminUrl: /wp-admin
        WPDb:
            dsn: 'mysql:host=localhost;dbname=wp_codeception_tests'
            user: wpcept
            password:
            dump: tests/_data/dump.sql
            populate: true
            cleanup: true
            url: 'http://0.0.0.0:8080'
            tablePrefix: wp_
        WPLoader:
            wpRootFolder: temp/wordpress
            dbName: wp_codeception_tests
            dbHost: localhost
            dbUser: root
            dbPassword:
            wpDebug: true
            dbCharset: utf8
            dbCollate: ''
            tablePrefix: wp_
            domain: localhost
            adminEmail: [email protected]
            title: 'SkyVerge Tests'
            phpBinary: php
        WPWebDriver:
            url: 'http://0.0.0.0'
            browser: phantomjs
            port: 8080
            restart: true
            wait: 2
            adminUsername: admin
            adminPassword: password
            adminUrl: '/wp-admin'

many thanks!

Some issues

Codeception is totally new to me, so may be some of these issues are just my settings, but I do need some help to figure them out.

1. Installation Issue:

Ran into this weird issue when tried running composer install or/and composer update:

Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for lucatume/wp-browser master@dev -> satisfiable by lucatume/wp-browser[dev-master].
    - lucatume/wp-browser dev-master requires badcow/lorem-ipsum dev-master -> no matching package found.

Potential causes:
 - A typo in the package name
 - The package is not available in a stable-enough version according to your minimum-stability setting
   see <https://groups.google.com/d/topic/composer-dev/_g3ASeIFlrc/discussion> for more details.

Read <http://getcomposer.org/doc/articles/troubleshooting.md> for further common problems.

Included the package in question into the composer like so, and the installation went through:

{
  "require": {
    "badcow/lorem-ipsum": "dev-master"
  },
  "require-dev": {
    "lucatume/wp-browser": "master@dev"
  }
}

3. WPDb Config Issue:

To begin with, I was under impression that I could provide WPDb credentials for existing WP Install and run tests against it. Oh man, was I wrong - it simply wiped out my existing DB without any warnings. Even though it was my dev site where I test plugins, I still had quite a bit of test pages with shortcodes and what not that I need to recreate manually now. Only later I noticed it's mentioned in the instructions for WPLoader that dbNAme will drop existing DB.

After the unfortunate experience, I figured that I probably need a blank DB with dedicated user name and a ~/wordpress/ folder with WP package in it. I spent over 2 hours trying to get WPDb config to work and still couldn't do it.

Here is the config:

class_name: AcceptanceTester
modules:
    enabled:
        - WPBrowser
        - AcceptanceHelper
        - WPDb
    config:
        WPBrowser:
            url: 'http://wptests.dev'
            adminUsername: 'admin'
            adminPassword: 'password'
            adminUrl: '/wp-core/wp-admin'
        WPDb:
            dsn: 'mysql:host=localhost;dbname=wptests'
            user: "wptester"
            password: "test"
            dump: 'tests/_data/dump.sql'
            populate: true
            cleanup: true
            url: 'http://wptests.dev'
            tablePrefix: wp_
            checkExistence: true
            update: true   

and this is the error that I get:

 [Codeception\Exception\Module]                                                                                                           
  (Exception in WPDb) SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: NO) while creating PDO connection 

I don't understand why the error references root, since I don't use that user name anywhere in the config. I tried changing user to something that doesn't exist, then it references the name in the error correctly, but then there is simply no such user name. If I add that custom user to mysql db - it goes back to referencing root in the error.

3. WPLoader
It is spelled dbNAme in the instructions, which I copied and pasted into my yml file. This was throwing the following error:

[Codeception\Exception\ModuleConfig]                                              
  WPLoader module is not configured!                                                
  Options: wpRootFolder, dbName, dbHost, dbUser, dbPassword are required            
                  Please, update the configuration and set all the required fields 

Renaming the property to dbName fixed the error, but there is no any activity/reporting when running codecept run. All I get is:

Codeception PHP Testing Framework v2.0.9
Powered by PHPUnit 4.4.1 by Sebastian Bergmann.

and nothing else. The DB stays empty.

Here is my WP Loader:

WPLoader:
            wpRootFolder: '/Users/username/Sites/wptests.dev'
            dbName: 'wptests'
            dbHost: 'localhost'
            dbUser: 'wptester'
            dbPassword: 'test'
            wpDebug: true
            dbCharset: 'utf8'
            dbCollate: ''
            tablePrefix: 'wp_'
            domain: 'wptests.dev'
            adminEmail: '[email protected]'
            title: 'Test Blog'
            phpBinary: 'php'
            language: ''

I ran configs one by one and all together. Always same results.

It would be nice to be able to take a look at a working example, otherwise I'm not sure if this package is stable or I'm simply misconfiguring it.

I would appreciate any pointers you could give me as far as getting this baby going.

Thanks!

WP installation removes custom DB tables/fields

One of the big differences between the WP boostrap in WPLoader and that in the WordPress phpunit test suite is that the latter runs install.php in a separate process. I've been running into problems of late with plugins that add custom DB tables and fields, because WPLoader runs it in the same process.

Example: You have a plugin that adds a table on init. This happens when install.php includes wp-settings.php. Then all the tables are removed and re-installed farther down the file. At this point, init has already run, and the require_once rtrim( ABSPATH, '/\\' ) . '/wp-settings.php'; in bootstrap.php isn't going to do anything. Any tests that expect the table to be there will fail.

I'm currently working around this by:

  1. Importing a correct database
  2. Modifying bootstrap.php to removed the require 'install.php';
  3. Further modifying bootstrap.php to add $table_prefix = WP_TESTS_TABLE_PREFIX; (otherwise you get an error when wp-settings.php loads)

Would it be possible to add a flag to the config to skip the install? Or perhaps check if WP is already installed and skip installation if it is? Or run the installation in a separate process as WordPress does?

Change action used to activate plugins?

Hey @lucatume!

Re this section of code - if we activate plugins on muplugins_loaded then various bits and bobs won't yet have been initialized by WP.

For instance, the global WP_Rewrite object hasn't yet been instantiated (can lead to problems when it's needed - even indirectly like if plugin code registers a post type upon activation). Might wp (or some other later point in the request) be a better action for this?

tests_add_filter( 'wp', [ $this, 'activatePlugins' ] );

Grab WP Cookie issue

Hi Luca,

I tried using your example for re-setting cookies instead of logging user in in every single test: http://theaveragedev.com/backend-wordpress-04/ I literally copied and pasted your first 2 methods into my class (+ the namespace references), but I get this error:

Call to a member function getName() on a non-object 

And that happens on the following lines:

$I->setCookie( self::$authCookie->getName(), self::$authCookie->getValue() );
$I->setCookie( self::$loginCookie->getName(), self::$loginCookie->getValue() );

any ideas why this would happen?

PHP Error

All of a sudden tests starting to fail this morning with the following error:

Parse error: syntax error, unexpected 'require_once' (T_REQUIRE_ONCE), expecting identifier (T_STRING) in /vendor/lucatume/wp-browser-commons/src/tad/WPBrowser/Filesystem/Filesystem.php on line 8

Running WebDriver tests on Travis CI

I've been trying to get my WebDriver tests running on Travis CI. See WordPoints/hooks-api#92 and WordPoints/dev-lib#46. What I'm trying to do is set up a PHP server during the Travis build, so that the acceptance tests can be run against whatever version of WordPress and PHP and the plugin that are being tested. So what I basically have is the site running at localhost:8888 during the Travis build. Then I'm attempting to run the acceptance tests with that as the site URL. The problem I've run into is that the acceptance tester isn't able to log in:

1) Failed to save a points reaction in savePointsReactionCept (tests/codeception/acceptance/savePointsReactionCept.php)

 Step  I login as admin 

 Fail  Field by name, label, CSS or XPath element with '#user_login' was not found.

Scenario Steps:

 2. $I->loginAsAdmin() at tests/codeception/_support/AcceptanceTester.php:34

 1. $I->loadSessionSnapshot("admin") at tests/codeception/_support/AcceptanceTester.php:30

I'm sure this is due to an issue with how I'm configuring the local server or something, but I'm kind of stuck. I was wondering if maybe somebody out there has already done this and could tell me how they got it to work.

AcceptanceHelper Question

I'd like to create a test sequence that could be easily re-used in different projects. I wonder if it could be created within AcceptanceHelper class. Is there a way to add methods to AcceptanceHelper that could utilize already existing WP functions in AcceptanceTester?

For example:

$I->seeWPTestSequence1Passed($pluginSlug)

where seeWPTestSequence1Passed() would login into the WP admin, activate/deactivate plugins and perform all sorts of routine assertions.

Requiring wp-browser causes WordPress to throw an error

Fatal error: Call to undefined method Requests_Response::is_redirect() in /Applications/MAMP/htdocs/wordpress/wp-includes/class-requests.php on line 685

After I require wp-browser in composer I then get this error when trying to access my site. If I remove wp-browser everything works fine.
Tried on php 5.5, 5.6, and 7.0
WordPress version 4.6.1

WordPress does not implement getInternalDomains() method

Hi,

The recent versions of Codeception throw an ExternalUrlException exception when the domain is not localhost and does not match any of the patterns returned by getInternalDomains(). The default method for Framework class returns simply [], so you can get an error like:

[ExternalUrlException] Codeception\Module\WordPress can't open external URL: http://mydomain.local/some/address

if you use a domain which is not localhost. I believe, the getInternalDomains() method should be implemented, returning an array with pattern matching siteUrl.

Please, see this issue.

Config remote test coverage for WPBrowser

How can I add remote test coverage for WPBrowser?
My setup is more less the same as lucatume/rest-calculator's acceptance suite.

Following the docs of Codeception and c3, I pulled c3.php to my plugin root and added require_once __DIR__ . '/wp-content/plugins/my-plugin-name/c3.php'; to wp-config.php (tried index.php and my-plugin-name.php also)

# .codeception.yml
coverage:
    enable: true
    remote: true # Also tried false
    c3_url: 'http://my-local-site.dev/wp-content/plugins/my-plugin-name/c3.php' # Also tried to omit this

However, tests/_output/coverage.xml always report zero coverage.
Am I missed anything?

Thanks!

http://codeception.com/docs/11-Codecoverage
https://github.com/Codeception/c3

Fatal error: Class 'Codeception\TestCase\Test' not found

Hello,
My all tests were running fine but suddenly I started getting below error. Is this error is due to new version of wpcept?

Fatal error: Class 'Codeception\TestCase\Test' not found in /home/travis/build/anspress/anspress/vendor/lucatume/wp-browser/src/Codeception/TestCase/WPTestCase.php on line 11

Call Stack:

    0.0003     269312   1. {main}() /home/travis/build/anspress/anspress/vendor/lucatume/wp-browser/wpcept:0

    0.0475    5722672   2. Codeception\Application->run() /home/travis/build/anspress/anspress/vendor/lucatume/wp-browser/wpcept:52

    0.0475    5722920   3. Symfony\Component\Console\Application->run() /home/travis/build/anspress/anspress/vendor/codeception/codeception/src/Codeception/Application.php:103

    0.0498    6017384   4. Symfony\Component\Console\Application->doRun() /home/travis/build/anspress/anspress/vendor/symfony/console/Application.php:117

    0.0500    6018320   5. Symfony\Component\Console\Application->doRunCommand() /home/travis/build/anspress/anspress/vendor/symfony/console/Application.php:186

    0.0500    6018864   6. Symfony\Component\Console\Command\Command->run() /home/travis/build/anspress/anspress/vendor/symfony/console/Application.php:815

    0.0506    6025072   7. Codeception\Command\Run->execute() /home/travis/build/anspress/anspress/vendor/symfony/console/Command/Command.php:256

    0.0667    7632688   8. Codeception\Command\Run->runSuites() /home/travis/build/anspress/anspress/vendor/codeception/codeception/src/Codeception/Command/Run.php:256

   27.4261   52434616   9. Codeception\Codecept->run() /home/travis/build/anspress/anspress/vendor/codeception/codeception/src/Codeception/Command/Run.php:329

   27.4276   52438696  10. Codeception\Codecept->runSuite() /home/travis/build/anspress/anspress/vendor/codeception/codeception/src/Codeception/Codecept.php:178

   27.4290   52477768  11. Codeception\SuiteManager->loadTests() /home/travis/build/anspress/anspress/vendor/codeception/codeception/src/Codeception/Codecept.php:208

   27.4298   52507568  12. Codeception\Test\Loader->loadTests() /home/travis/build/anspress/anspress/vendor/codeception/codeception/src/Codeception/SuiteManager.php:96

   27.4317   52571648  13. Codeception\Test\Loader\Unit->loadTests() /home/travis/build/anspress/anspress/vendor/codeception/codeception/src/Codeception/Test/Loader.php:134

   27.4317   52571744  14. Codeception\Lib\Parser::load() /home/travis/build/anspress/anspress/vendor/codeception/codeception/src/Codeception/Test/Loader/Unit.php:20

   27.4610   52571744  15. Codeception\Lib\Parser::includeFile() /home/travis/build/anspress/anspress/vendor/codeception/codeception/src/Codeception/Lib/Parser.php:141

   27.4613   52606600  16. include_once('/home/travis/build/anspress/anspress/tests/wpunit/ActivityTest.php') /home/travis/build/anspress/anspress/vendor/codeception/codeception/src/Codeception/Lib/Parser.php:197

   27.4613   52606896  17. spl_autoload_call() /home/travis/build/anspress/anspress/vendor/codeception/codeception/src/Codeception/Lib/Parser.php:4

   27.4613   52606944  18. Composer\Autoload\ClassLoader->loadClass() /home/travis/build/anspress/anspress/vendor/codeception/codeception/src/Codeception/Lib/Parser.php:4

   27.4615   52607128  19. Composer\Autoload\includeFile() /home/travis/build/anspress/anspress/vendor/composer/ClassLoader.php:301

   27.4626   52860712  20. include('/home/travis/build/anspress/anspress/vendor/lucatume/wp-browser/src/Codeception/TestCase/WPTestCase.php') /home/travis/build/anspress/anspress/vendor/composer/ClassLoader.php:412

FATAL ERROR. TESTS NOT FINISHED.

Class 'Codeception\TestCase\Test' not found 

in /home/travis/build/anspress/anspress/vendor/lucatume/wp-browser/src/Codeception/TestCase/WPTestCase.php:11

The command "./vendor/bin/wpcept run --steps --debug" exited with 255.

something wrong with composer

I was trying to get your library and got this:

$ composer update
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for lucatume/wp-browser master@dev -> satisfiable by lucatume/wp-browser[dev-master].
    - lucatume/wp-browser dev-master requires badcow/lorem-ipsum dev-master -> no matching package found.

Potential causes:
 - A typo in the package name
 - The package is not available in a stable-enough version according to your minimum-stability setting
   see <https://groups.google.com/d/topic/composer-dev/_g3ASeIFlrc/discussion> for more details.

Read <http://getcomposer.org/doc/articles/troubleshooting.md> for further common problems.

All acceptance tests fail after updating to latest version of WP-Browser

I decided to update to the latest version of wp-browser and codeception, since my lock file hasn't been refreshed since February (was still on codeception 2.0.1). After updating, all my acceptance tests fail and I'm getting this fatal error at the end:

FATAL ERROR. TESTS NOT FINISHED.
Call to undefined function Codeception\Subscriber\codecept_relative_path() 
in /.../vendor/codeception/codeception/src/Codeception/Subscriber/Console.php:305

All screenshots in /tests/_output/ display WordPpress standard 404 page. Any ideas on how to get it to work?

WPLoader loading options

Continues from #33 (comment)

@LeRondPoint WPBootstrapper is meant to be used in acceptance tests to have access to, and work on, the WP installation that's being hit by the acceptance tests.

Your seems to be a middle ground between calling wp-load.php straight and using the WPLoader module and its opinionated and destructive approach.
If I can have a firmer grasp on what you would like to do with it and in which tests you would like to use it maybe we could simply work out an option for the WPLoader module to have it work as intended.

Something in the league of

modules:
    config:
        WPLoader:
            startBlank: false

Let me make a first tentative call on your intentions:

As a tester I want to be able to bootstrap a WordPress installation without resetting it to a blank state and access WPLoader-like unit/functional test cases and methods in my unit and functional tests.

Please correct me below and let's make this work.

WPBrowser could not be found and loaded

I'm sorry this is probably not a bug. I am using github and travisci to run Codeception and having a hard time getting my composer installed CodeCeption + WPBrowser to work with an acceptance test.

I've gotten composer to work fine running the PHPBrowser module.

I have WPBrowser installed in my vendor folder, and I've added the setup data to my acceptance.suite.yml file, is there more I need to do?

travis.yml

https://github.com/inboundnow/landing-pages/blob/feature/Refactoring_metabox_modules/.travis.yml#L47-L52

composer.json

https://github.com/inboundnow/landing-pages/blob/feature/Refactoring_metabox_modules/composer.json

codeception.yml:

https://github.com/inboundnow/landing-pages/blob/feature/Refactoring_metabox_modules/codeception.yml

acceptance.suite.yml

https://github.com/inboundnow/landing-pages/blob/feature/Refactoring_metabox_modules/tests/codeception/acceptance.suite.yml

Any guidance is welcome, maybe it will help me help others.

Also, any recommendations on retrieving remote logs? After the travis build completes I do not have access to the output logs. My tests are passing locally but one is failing remotely and would love to look at the log.

Compatibility with Trellis and other setups with custom directory structure

Hi folks,

just learned about wp-browser today. I tried playing with it through a wordpress bedrock instance on a vagrant trellis box (if you're not familiar with these projects https://roots.io )

The first issue I stumbled upon is the WPLoader ensureWpRoot method
https://github.com/lucatume/wp-browser/blob/master/src/Codeception/Module/WPLoader.php#L156-160

Many setups today ( including the wordpress bedrock one ) treat WordPress as a dependency and then have a separate wp-content directory elsewhere, where all the instance code lies.

Like I said Bedrock is one such setup, so this is what happens:

  • if I give the correct root project directory, the ensureWpRoot method fails as wp-settings.php is under the wp subdirectory
  • if I try to give it the path to the wp subdirectory, the wp-content directory inside the wp directory is not the one that should be referenced as it only holds the default content (remember, the real wp-content directory is elsewhere, in this specific instance, it's the /project-root/web/app directory)

I have not looked extensively into the wp-browser codebase - do you guys think this is something that could be addressed easily?

The first hint that comes to mind is that maybe rather than looking for wp-settings.php to ensure we're in a wp project root, one could be trying to load the index.php file and seeing if doing that defines the standard wp constants plus eventually any custom ones.

In the trellis case, the index.php file loads the usual files in chain plus the bedrock specific one:

wp-blog-header.php > wp-load.php > wp-config.php > /config/application.php

the /config/application.php is where bedrock defines the CONTENT_DIR/WP_CONTENT_DIR/WP_CONTENT_URL constans and so on...

The trellis/bedrock setup is a good environment and I'm sure more and more devs will either adopt it or follow similar patterns to have both wp core and plugins managed as dependencies.

Supporting this kind of environment may be something worth looking into.

Thoughts?

Undefined index: adminPath

Hello,
Again a new issue appeared today, kindly check.

[PHPUnit_Framework_Exception (8)]
Undefined index: adminPath

Exception trace:
 () at /home/travis/build/anspress/anspress/vendor/codeception/codeception/src/Codeception/Subscriber/ErrorHandler.php:60

 Codeception\Subscriber\ErrorHandler->errorHandler() at /home/travis/build/anspress/anspress/vendor/lucatume/wp-browser/src/Codeception/Module/WPWebDriver.php:47

 Codeception\Module\WPWebDriver->_initialize() at /home/travis/build/anspress/anspress/vendor/codeception/codeception/src/Codeception/Module/WebDriver.php:317

 Codeception\Module\WebDriver->_before() at /home/travis/build/anspress/anspress/vendor/codeception/codeception/src/Codeception/Subscriber/Module.php:58

 Codeception\Subscriber\Module->before() at n/a:n/a

 call_user_func() at /home/travis/build/anspress/anspress/vendor/symfony/event-dispatcher/EventDispatcher.php:174

 Symfony\Component\EventDispatcher\EventDispatcher->doDispatch() at /home/travis/build/anspress/anspress/vendor/symfony/event-dispatcher/EventDispatcher.php:43

 Symfony\Component\EventDispatcher\EventDispatcher->dispatch() at /home/travis/build/anspress/anspress/vendor/codeception/codeception/src/Codeception/PHPUnit/Listener.php:124

 Codeception\PHPUnit\Listener->fire() at /home/travis/build/anspress/anspress/vendor/codeception/codeception/src/Codeception/PHPUnit/Listener.php:95

 Codeception\PHPUnit\Listener->startTest() at /home/travis/build/anspress/anspress/vendor/phpunit/phpunit/src/Framework/TestResult.php:388

 PHPUnit_Framework_TestResult->startTest() at /home/travis/build/anspress/anspress/vendor/codeception/codeception/src/Codeception/Test/Test.php:68

 Codeception\Test\Test->run() at /home/travis/build/anspress/anspress/vendor/phpunit/phpunit/src/Framework/TestSuite.php:753

 PHPUnit_Framework_TestSuite->run() at /home/travis/build/anspress/anspress/vendor/codeception/codeception/src/Codeception/PHPUnit/Runner.php:98

 Codeception\PHPUnit\Runner->doEnhancedRun() at /home/travis/build/anspress/anspress/vendor/codeception/codeception/src/Codeception/SuiteManager.php:152

 Codeception\SuiteManager->run() at /home/travis/build/anspress/anspress/vendor/codeception/codeception/src/Codeception/Codecept.php:209

 Codeception\Codecept->runSuite() at /home/travis/build/anspress/anspress/vendor/codeception/codeception/src/Codeception/Codecept.php:178

 Codeception\Codecept->run() at /home/travis/build/anspress/anspress/vendor/codeception/codeception/src/Codeception/Command/Run.php:329

 Codeception\Command\Run->runSuites() at /home/travis/build/anspress/anspress/vendor/codeception/codeception/src/Codeception/Command/Run.php:256

 Codeception\Command\Run->execute() at /home/travis/build/anspress/anspress/vendor/symfony/console/Command/Command.php:256

 Symfony\Component\Console\Command\Command->run() at /home/travis/build/anspress/anspress/vendor/symfony/console/Application.php:815

 Symfony\Component\Console\Application->doRunCommand() at /home/travis/build/anspress/anspress/vendor/symfony/console/Application.php:186

 Symfony\Component\Console\Application->doRun() at /home/travis/build/anspress/anspress/vendor/symfony/console/Application.php:117

 Symfony\Component\Console\Application->run() at /home/travis/build/anspress/anspress/vendor/codeception/codeception/src/Codeception/Application.php:103

 Codeception\Application->run() at /home/travis/build/anspress/anspress/vendor/lucatume/wp-browser/wpcept:52

PDOException when using WPDb and WPLoader in different suites

I'm having some exceptions in Cest classes when using both WPDb and WPLoader together in a suite. Given WPLoader is built on top of PHPUnit I think this is normal. However, I'm also getting the problem in acceptance Cest classes that do not use WPLoader if they run after my unit suite that does. When run in isolation, the acceptance suite runs fine. Here are some outputs :

When running acceptance alone:

sgravel@Rond-point-Wordpress:~/staging$ ./wpcept run acceptance --env phone --debug
Codeception PHP Testing Framework v2.1.4
Powered by PHPUnit 4.8.22 by Sebastian Bergmann and contributors.

  Initializing VisualCeptionReport
  VisualCeptionReporter: templateFile = /var/www-staging/vendor/digital-products-fork/codeception-visualception-wpbrowser/module/report/template.php

Acceptance (phone) Tests (2) ------------------------------------------------------------------------------------
Modules: WPWebDriver, WPDb, VisualCeption, VisualCeptionReporter, \Helper\Acceptance
-----------------------------------------------------------------------------------------------------------------
See the plugin in the menu on a mobile phone or tablet (MenuAccessCest::mobileMenuAccess)
Scenario:
* I login as admin

  [GET] http://meeserver/wp-login.php
* I am going to setup user authentication
* I have or update in database "wp_options",{"option_name":"gaep_access_token","option_value":"{"access_token":"ya29.gwLkJcn7t6cTAOKrsdvplLPp7sP-EDQTBh2yfXYZG3yrksMWjWxYYPAV084KKVl0puiSZQ","expires_in":3600,"created":1455057433}"}
  [Query] INSERT INTO `wp_options` (`option_name`, `option_value`) VALUES (?, ?) ON DUPLICATE KEY UPDATE option_name='gaep_access_token', option_value='{"access_token":"ya29.gwLkJcn7t6cTAOKrsdvplLPp7sP-EDQTBh2yfXYZG3yrksMWjWxYYPAV084KKVl0puiSZQ","expires_in":3600,"created":1455057433}'
* I have or update in database "wp_options",{"option_name":"gaep_linked_account","option_value":"73314709"}
  [Query] INSERT INTO `wp_options` (`option_name`, `option_value`) VALUES (?, ?) ON DUPLICATE KEY UPDATE option_name='gaep_linked_account', option_value='73314709'
* I have or update in database "wp_options",{"option_name":"gaep_linked_property","option_value":"GA-73314709-1"}
  [Query] INSERT INTO `wp_options` (`option_name`, `option_value`) VALUES (?, ?) ON DUPLICATE KEY UPDATE option_name='gaep_linked_property', option_value='GA-73314709-1'
* As an administrator
* I click "li#wp-admin-bar-menu-toggle .ab-item"
* I click "GA Experiments Plus"
* I click "GA Authentication"
* I see current url matches "/admin\.php.*page=gaep_auth/"
* I click "li#wp-admin-bar-menu-toggle .ab-item"
* I click "GA Experiments Plus"
* I click "Experiments"
* I see current url matches "/admin\.php.*page=ga_experiments_plus/"
* I don't have in database "wp_options",{"option_name":"gaep_access_token"}
* I don't have in database "wp_options",{"option_name":"gaep_linked_account"}
* I don't have in database "wp_options",{"option_name":"gaep_linked_property"}
 PASSED

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
See the plugin in the menu on a mobile phone or tablet (NoAuthMenuAccessCest::mobileMenuAccess)
Scenario:
* As an administrator
* I login as admin

  [GET] http://meeserver/wp-login.php
* I see "Dashboard"
* I click "li#wp-admin-bar-menu-toggle .ab-item"
* I click "GA Experiments Plus"
* I click "GA Authentication"
* I see current url matches "/admin\.php.*page=gaep_auth/"
* I click "li#wp-admin-bar-menu-toggle .ab-item"
* I click "GA Experiments Plus"
* I click "Experiments"
* I see current url matches "/admin\.php.*page=gaep_auth/"
 PASSED

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  Trying to store file (tests/_output/phone-vcreport.html)
-----------------------------------------------------------------------------------------------------------------


Time: 47.07 seconds, Memory: 18.75Mb

OK (2 tests, 5 assertions)

When running both suites:

sgravel@Rond-point-Wordpress:~/staging$ ./wpcept run --debug --env default --env phone
Codeception PHP Testing Framework v2.1.4
Powered by PHPUnit 4.8.22 by Sebastian Bergmann and contributors.

  Running as single site
Installing...
Not running ajax tests. To execute these, use --group ajax.
Not running ms-files tests. To execute these, use --group ms-files.
Not running external-http tests. To execute these, use --group external-http.

Functional (default) Tests (13) -----------------------------------------------------------------------------------
Modules: Asserts, WPDb, WPLoader, WPBrowser, \Helper\Functional
-------------------------------------------------------------------------------------------------------------------
Test authenticate (AuthenticationAjaxTest::testAuthenticate)                                                 Ok
Test get accounts (AuthenticationAjaxTest::testGetAccounts)                                                  Ok
Test get accounts failures (AuthenticationAjaxTest::testGetAccountsFailures)                                 Ok
Test get properties (AuthenticationAjaxTest::testGetProperties)                                              Ok
Test get properties failures (AuthenticationAjaxTest::testGetPropertiesFailures)                             Ok
Test get views (AuthenticationAjaxTest::testGetViews)                                                        Ok
Test get views failures (AuthenticationAjaxTest::testGetViewsFailures)                                       Ok
Test experiment creation (ExperimentsAjaxTest::testExperimentCreation)                                       Ok
Test experiment creation failures (ExperimentsAjaxTest::testExperimentCreationFailures)                      Ok
Test experiment save (ExperimentsAjaxTest::testExperimentSave)                                               Ok
Test experiment save failures (ExperimentsAjaxTest::testExperimentSaveFailures)                              Ok
Test me (ExperimentsGetActionsTest::testMe)                                                                  Ok
Test options save (OptionsAjaxTest::testOptionsSave)                                                         Ok
-------------------------------------------------------------------------------------------------------------------

  Running as single site

Unit (default) Tests (20) --------------------------------------------------------------------------------
Modules: Asserts, WPDb, WPLoader, \Helper\Unit
----------------------------------------------------------------------------------------------------------
Try to test (PDOCest::tryToTest)
Scenario:
 ERROR

Test db setup (ExperimentsDBStructureTest::testDBSetup)                                             Ok
Test db structure (ExperimentsDBStructureTest::testDBStructure)                                     Ok
Test creation (ExperimentsManagementTest::testCreation)                                             Ok
Test load from db (ExperimentsManagementTest::testLoadFromDB)                                       Ok
Test update db (ExperimentsManagementTest::testUpdateDB)                                            Ok
Test removal (ExperimentsManagementTest::testRemoval)                                               Ok
Test clear (ExperimentsManagementTest::testClear)                                                   Ok
Test tracking activation (OptionsActivationTest::testTrackingActivation)                            Ok
Test save tracking (OptionsSaveLoadTest::testSaveTracking)                                          Ok
Test save admin tracking (OptionsSaveLoadTest::testSaveAdminTracking)                               Ok
Test save editor tracking (OptionsSaveLoadTest::testSaveEditorTracking)                             Ok
Test save author tracking (OptionsSaveLoadTest::testSaveAuthorTracking)                             Ok
Test save contributor tracking (OptionsSaveLoadTest::testSaveContributorTracking)                   Ok
Test save subscriber tracking (OptionsSaveLoadTest::testSaveSubscriberTracking)                     Ok
Test tracking activation (OptionsSaveLoadTest::testTrackingActivation)                              Ok
Test creation (VariantsManagementTest::testCreation)                                                Ok
Test removal (VariantsManagementTest::testRemoval)                                                  Ok
Test properties (VariantsManagementTest::testProperties)                                            Ok
Test save load (VariantsManagementTest::testSaveLoad)                                               Ok
----------------------------------------------------------------------------------------------------------

  Initializing VisualCeptionReport
  VisualCeptionReporter: templateFile = /var/www-staging/vendor/digital-products-fork/codeception-visualception-wpbrowser/module/report/template.php

Acceptance (default) Tests (0) --------------
Modules: WPWebDriver, WPDb, VisualCeption, VisualCeptionReporter, \Helper\Acceptance
---------------------------------------------
  Trying to store file (tests/_output/vcreport.html)
---------------------------------------------
  Initializing VisualCeptionReport
  Rebuilding AcceptanceTester...
  VisualCeptionReporter: templateFile = /var/www-staging/vendor/digital-products-fork/codeception-visualception-wpbrowser/module/report/template.php

Acceptance (phone) Tests (2) ------------------------------------------------------------------------------------
Modules: WPWebDriver, WPDb, VisualCeption, VisualCeptionReporter, \Helper\Acceptance
-----------------------------------------------------------------------------------------------------------------
See the plugin in the menu on a mobile phone or tablet (MenuAccessCest::mobileMenuAccess)
Scenario:

  [Selenium har Logs]
  22:30:39.956 INFO - {"log":{"version":"1.2","creator":{"name":"PhantomJS","version":"2.1.0"},"pages":[{"startedDateTime":null,"id":"","title":"","pageTimings":{"onLoad":null}}],"entries":[]}}

  [Selenium browser Logs]  EMPTY
  Screenshot and page source were saved into '_output' dir
 ERROR

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
See the plugin in the menu on a mobile phone or tablet (NoAuthMenuAccessCest::mobileMenuAccess)
Scenario:

  [Selenium har Logs]
  22:30:42.2 INFO - {"log":{"version":"1.2","creator":{"name":"PhantomJS","version":"2.1.0"},"pages":[{"startedDateTime":null,"id":"","title":"","pageTimings":{"onLoad":null}}],"entries":[]}}

  [Selenium browser Logs]  EMPTY
  Screenshot and page source were saved into '_output' dir
 ERROR

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  Trying to store file (tests/_output/phone-vcreport.html)
-----------------------------------------------------------------------------------------------------------------
1) Failed to try to test in PDOCest::tryToTest (tests/unit/PDOCest.php)


  [PDOException] You cannot serialize or unserialize PDO instances

#1  PDO->__sleep
#2  /var/www-staging/vendor/sebastian/global-state/src/Snapshot.php:313
#3  /var/www-staging/vendor/sebastian/global-state/src/Snapshot.php:121
2) Failed to see the plugin in the menu on a mobile phone or tablet in MenuAccessCest::mobileMenuAccess (tests/acceptance/MenuAccessCest.php)


  [PDOException] You cannot serialize or unserialize PDO instances

#1  PDO->__sleep
#2  /var/www-staging/vendor/sebastian/global-state/src/Snapshot.php:313
#3  /var/www-staging/vendor/sebastian/global-state/src/Snapshot.php:121
3) Failed to see the plugin in the menu on a mobile phone or tablet in NoAuthMenuAccessCest::mobileMenuAccess (tests/acceptance/NoAuthMenuAccessCest.php)


  [PDOException] You cannot serialize or unserialize PDO instances

#1  PDO->__sleep
#2  /var/www-staging/vendor/sebastian/global-state/src/Snapshot.php:313
#3  /var/www-staging/vendor/sebastian/global-state/src/Snapshot.php:121


Time: 16.17 seconds, Memory: 62.25Mb

There were 3 errors:

---------

---------

---------

FAILURES!

I also tried switching to the Db module instead with the same result. Not sure what is going on here!

Here is my codeception.yml file:

actor: Tester
paths:
    tests: tests
    log: tests/_output
    data: tests/_data
    helpers: tests/_support
settings:
    bootstrap: _bootstrap.php
    colors: true
    memory_limit: 1024M
modules:
    config:
        Db:
            dsn: 'mysql:host=localhost;dbname=wordpress_staging'
            user: meeuser
            password: meepass
            dump: tests/_data/dump.sql
        WPBrowser:
            url: 'http://localhost'
            adminUsername: meeuser
            adminPassword: meepass
            adminUrl: /wp-admin
        WPLoader:
            wpRootFolder: /var/www-staging/html
            dbName: wordpress_staging
            dbHost: localhost
            dbUser: meeuser
            dbPassword: meepass
            wpDebug: true
            dbCharset: utf8
            dbCollate: ''
            tablePrefix: wp_
            domain: localhost
            adminEmail: [email protected]
            title: 'WP Tests'
            phpBinary: php
            language: ''
            plugins: []
            activatePlugins: []
            bootstrapActions: []
        WPDb:
            dsn: 'mysql:host=localhost;dbname=wordpress_staging'
            user: meeuser
            password: meepass
            dump: tests/_data/dump.sql
            populate: true
            cleanup: true
            url: 'http://meeserver'
            tablePrefix: wp_
            checkExistence: true
            update: true
        WPWebDriver:
            url: 'http://meeserver'
            browser: phantomjs
            port: 4444
            restart: true
            wait: 2
            window_size: 768x1024
            adminUsername: meeuser
            adminPassword: meepass
            adminUrl: /wp-admin
        VisualCeption:
            webdriver: WPWebDriver
            refereneImageDir: tests/acceptance/ReferenceImages/
            currentImageDir: tests/acceptance/CurrentImages/
            maximumDeviation: 5
            saveCurrentImageIfFailure: true
        VisualCeptionReporter:
            logFile: tests/_output/vcreport.html
env:
    default:
        config:

WPLoader throws an exception, $merged_filters is not an array

Hi, I'm new to testing of this kind, so let me know if I'm missing something.

When I run wpcept run I get this error before the integration tests run:
array_intersect_key(): Argument #1 is not an array

Commenting out the WPLoader line in the integration.suite.yml file "fixes" the problem. Here's a verbose output:

    Including plugin [ananda-x/ananda-x.php] files

      The following tables will be dropped: 
      	- posts
      	- comments
      	- links
      	- options
      	- postmeta
      	- terms
      	- term_taxonomy
      	- term_relationships
      	- termmeta
      	- commentmeta
      
      Installing WordPress...
      Installing network...
      
      Network activating plugin [ananda-x/ananda-x.php]...
   
                                                          
      [PHPUnit_Framework_Exception]                       
      array_intersect_key(): Argument #1 is not an array  
                                                          
    
    Exception trace:
     () at /Users/nabhacosley/Sites/ananda-designs/plugins/ananda-x/vendor/codeception/codeception/src/Codeception/Subscriber/ErrorHandler.php:75
     Codeception\Subscriber\ErrorHandler->errorHandler() at n/a:n/a
     array_intersect_key() at /Users/nabhacosley/Sites/ananda-designs/plugins/ananda-x/vendor/lucatume/wp-browser/src/includes/tad-functions.php:29
     _without_filters() at /Users/nabhacosley/Sites/ananda-designs/plugins/ananda-x/vendor/lucatume/wp-browser/src/includes/bootstrap.php:146
     require_once() at /Users/nabhacosley/Sites/ananda-designs/plugins/ananda-x/vendor/lucatume/wp-browser/src/Codeception/Module/WPLoader.php:229
     Codeception\Module\WPLoader->loadWordPress() at /Users/nabhacosley/Sites/ananda-designs/plugins/ananda-x/vendor/lucatume/wp-browser/src/Codeception/Module/WPLoader.php:151
     Codeception\Module\WPLoader->initialize() at /Users/nabhacosley/Sites/ananda-designs/plugins/ananda-x/vendor/lucatume/wp-browser/src/Codeception/Module/WPLoader.php:139
     Codeception\Module\WPLoader->_initialize() at /Users/nabhacosley/Sites/ananda-designs/plugins/ananda-x/vendor/codeception/codeception/src/Codeception/SuiteManager.php:81
     Codeception\SuiteManager->initialize() at /Users/nabhacosley/Sites/ananda-designs/plugins/ananda-x/vendor/codeception/codeception/src/Codeception/Codecept.php:207
     Codeception\Codecept->runSuite() at /Users/nabhacosley/Sites/ananda-designs/plugins/ananda-x/vendor/codeception/codeception/src/Codeception/Codecept.php:178
     Codeception\Codecept->run() at /Users/nabhacosley/Sites/ananda-designs/plugins/ananda-x/vendor/codeception/codeception/src/Codeception/Command/Run.php:359
     Codeception\Command\Run->runSuites() at /Users/nabhacosley/Sites/ananda-designs/plugins/ananda-x/vendor/codeception/codeception/src/Codeception/Command/Run.php:286
     Codeception\Command\Run->execute() at /Users/nabhacosley/Sites/ananda-designs/plugins/ananda-x/vendor/symfony/console/Command/Command.php:257
     Symfony\Component\Console\Command\Command->run() at /Users/nabhacosley/Sites/ananda-designs/plugins/ananda-x/vendor/symfony/console/Application.php:849
     Symfony\Component\Console\Application->doRunCommand() at /Users/nabhacosley/Sites/ananda-designs/plugins/ananda-x/vendor/symfony/console/Application.php:193
     Symfony\Component\Console\Application->doRun() at /Users/nabhacosley/Sites/ananda-designs/plugins/ananda-x/vendor/symfony/console/Application.php:124
     Symfony\Component\Console\Application->run() at /Users/nabhacosley/Sites/ananda-designs/plugins/ananda-x/vendor/codeception/codeception/src/Codeception/Application.php:103
     Codeception\Application->run() at /Users/nabhacosley/Sites/ananda-designs/plugins/ananda-x/vendor/codeception/codeception/codecept:33

Here's my WPLoader config with a few details obfuscated.

    WPLoader:
          multisite: true
          wpRootFolder: "/Users/nabhacosley/Local Sites/ananda-designs/app/public/"
          dbName: "local_wploader"
          dbHost: "..."
          dbUser: "..."
          dbPassword: "..."
          isolatedInstall: true
          wpDebug: true
          dbCharset: "utf8"
          dbCollate: ""
          tablePrefix: "wptests_"
          domain: "ananda-designs.dev"
          adminEmail: "[email protected]"
          title: "Ananda Designs Tests"
          phpBinary: "php"
          language: ""
          configFile: ""
          plugins: ['ananda-x/ananda-x.php']
          activatePlugins: ['ananda-x/ananda-x.php']
          booststrapActions: []

And integration.suite.yml:

    class_name: IntegrationTester
    modules:
        enabled:
            - \Helper\Integration
            - WPLoader

WPDb pupulate works in a weird way

Hi Luca,

Can WPDb pre-population of the DB work with WPLoader together?

I want to import dump of my test WP db and run some tests against it. I can't do that when WPLoader is not included, I'm getting this error:

[PHPUnit_Framework_Exception] Use of undefined constant WP_TESTS_FORCE_KNOWN_BUGS - assumed 'WP_TESTS_FORCE_KNOWN_BUGS'

When I include both modules: WPDb and WPLoader, I can see that my dump get's imported some time during the test, but then it gets dropped by WPLoader in favor of clean setup.

Any ideas?

Wordpress acceptance test always redirect to install.php

I don't know if this is the right place to ask this question, but I don't understand where the problem is located, I don't understand if I did something wrong with config files or something else.

I have a fresh installed wordpress site on my machine: http://localhost/wordpress/
I have access to both frontend and backend without any kind of problem.

I would like to run a very small acceptance test to see if I can login as administrator (I'm new to codeception and wp-browser, so I'm learning from scratch).

When I run the test, instead of opening the wp-login page, the test keeps me redirecting on the install.php page, so the wordpress site is erased every time.

This is my acceptance.suite.yml file

class_name: AcceptanceTester
modules:
enabled:
- \Helper\Acceptance
- WPDb
- WPWebDriver
config:
WPDb:
dsn: 'mysql:host=localhost;dbname=wordpress'
user: root
password: passwd
dump: tests/_data/dump.sql
populate: true
cleanup: true
url: 'http://localhost/wordpress'
urlReplacement: true
tablePrefix: wp_
WPWebDriver:
url: 'http://localhost/wordpress'
browser: firefox
adminUsername: admin
adminPassword: admin
adminPath: /wp-admin/

And this is my cept file:

<?php 
$I = new AcceptanceTester($scenario);
$I->wantTo('perform actions and see result');

$I->amOnPage('/');
$I->loginAsAdmin();
?>

It has been days, but I literally can't figure out what I'm doing wrong...

fatal error

I'm getting this fatal error:

PHP Fatal error: Call to a member function all() on a non-object in /srv/www/rg/multisite/htdocs/wp-content/plugins/programs-tests/vendor/lucatume/wp-browser/src/Codeception/Module/WPLoader.php on line 139
PHP Stack trace:
PHP 1. {main}() /srv/www/rg/multisite/htdocs/wp-content/plugins/programs-tests/vendor/lucatume/wp-browser/wpcept:0

I'm trying to run $ vendor/bin/wpcept run unit

WPAJaxTestCase.php

I've been tearing my hair out all day for this stupid "bug" so I thought of logging it somewhere.

It happens that the WPAjaxTestCase file name has a capital 'J' so you might want to check that out if you get a "File not found" error like I did!

[WPDb] Multisite URL replacement forgotten tables

I added the following code to properly handle multisite URL replacement. Might be worth integrating/merging in your code.

    public function replaceSiteDomainInSql($sql)
    {
        $tables = [ "blogs" => "VALUES\\s+\(\\d+,\\s*\\d+,\\s*'(.*)',/uiU",
                    "site" => "VALUES\\s+\(\\d+,\\s*'(.*)',/uiU" ];
        $sql = parent::replaceSiteDomainInSql($sql);
        $thisSiteUrl = str_replace('http://', '', $this->config['url']);

        foreach($tables as $table => $pattern)
        {
            $currentTable = $this->config['tablePrefix'] . $table;
            $matches = [];
            preg_match("/INSERT\\s+INTO\\s+`{$currentTable}`\\s+{$pattern}", $sql, $matches);

            if (empty($matches) || empty($matches[1])) {
                codecept_debug('Tried to replace WordPress site domain but dump file does not contain an `' . $table . '` table INSERT instruction.');
                continue;
            }

            $dumpSiteUrl = $matches[1];
            if (empty($dumpSiteUrl)) {
                codecept_debug('Tried to replace WordPress site domain but dump file does not contain dump of `domain` option.');
                continue;
            }

            if ($dumpSiteUrl === $thisSiteUrl) {
                codecept_debug('Dump file domain not replaced as identical to the one specified in the configuration (' . $dumpSiteUrl . ').');
                continue;
            }
            codecept_debug('Dump file domain [' . $dumpSiteUrl . '] replaced with [' . $thisSiteUrl . ']');

            $sql = str_replace($dumpSiteUrl, $thisSiteUrl, $sql);
        }

        return $sql;
    }

wpcept issues

Hello sir--

The wpcept file in the latest version appears to be pointing to some non-existent classes. First of all, it seems to have shifted from the Symfony Console Application to a custom Codeception\Application which cannot be found. Similarly, I noticed it is calling a number of new custom commands that do not appear in the Commands directory.

composer update: no matching package found.

Hello,

I'm trying to set up your module.

  1. Created an empty directory.

  2. Created composer.json with the followings:

    {
        "require-dev":{
              "lucatume/wp-browser": "master@dev"
        }
    }
    
  3. In the directory performed composer update

It gives the following error.

composer update
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

Problem 1
- Installation request for lucatume/wp-browser master@dev -> satisfiable by lucatume/wp-browser[dev-master].
- lucatume/wp-browser dev-master requires badcow/lorem-ipsum dev-master -> no matching package found.

Potential causes:

Read http://getcomposer.org/doc/articles/troubleshooting.md for further common problems.

Am I doing it right or missing something?

window_size doesn't work if enclosed in quotes

Just letting you know that on my end the window_size option does not work if I put quotes around it. It only works if I do it like so:

  modules:
      enabled:
          - WPWebDriver
      config:
          WPWebDriver:
              url: 'http://example.local'
              browser: phantomjs
              port: 4444
              window_size: 1024x768
              adminUsername: 'root'
              adminPassword: 'root'
              adminPath: '/wp-core/wp-admin'

The official CodeCeption WebDriver docs also list the recommended format as without the quotes.

Just mentioning this so that perhaps you can update your readme to spare other people the confusion. :-)

How can I use WordPress functions in tests?

Following this blog post http://www.theaveragedev.com/testing-the-rest-calculator/ , I added a permission check:

add_action( 'rest_api_init', function () {register_rest_route( 'calc', 'add/(?P<o1>\d+)/(?P<o2>\d+)',
    [
        'methods'  => 'GET',
        'callback' => [ new Calculator, 'process' ],
        'permission_callback' => function () {
            return current_user_can('manage_options');
        },
    ] );
} );

I am using this in a ajax script on the admin area. It works fine when I add a X-WP-Nonce header (wp_create_nonce('wp_rest')).

However, I find no way to inject this nonce in the tests:
$I->sendGET( '/calc/add/4/5' ); returns 403 errors

Question: How can I use WordPress functions (e.g: wp_create_nonce('wp_rest')) in the tests?

Thanks!

WordPress module doesn't load WordPress code

I have enabled and configured WordPress and WPDb modules. However, the following test fails and says that is_admin() is undefined. Same with any other WordPress function. I'm sure WPDb is configured correctly. And there isn't much to configure for the WordPress module.

class MyTest extends \Codeception\Test\Unit {
public function testMe() {
$this->assertFalse(is_admin());
}
}

By the way, the test works when I use WPLoader module instead of those two.

If this is not a bug and everything works as expected, please consider writing a better high-level summary of what each module, including WordPress, is supposed to do. It's a bit confusing at the moment.

User configuration seems to be discarded when running bootstrap in batch mode

I tried running wpcept bootstrap --wpRootFolder=my/custom/folder but got the error:

[Codeception\Exception\ModuleConfigException]                                            
WordPress module is not configured!                                                      
                                                                                           
The path `/var/www/wordpress` is not pointing to a valid WordPress installation folder. 

Digging into the code:

https://github.com/lucatume/wp-browser/blob/master/src/Codeception/Command/WPBootstrap.php#L100

it looks like $userConfig is initialized only during the interactive bootstrap, and not during the batch one. Thus, when getting to:

https://github.com/lucatume/wp-browser/blob/master/src/Codeception/Command/WPBootstrap.php#L227

the user configuration is always an empty array, no matter what command line argument I'm passing.

Error: 90980 segmentation fault

Hi Luca!
I've just installed the WP-Browser to try it and I'm having an issue when I'm trying to clean and populate the database.

The error I'm receiving:
[1] 90980 segmentation fault vendor/lucatume/wp-browser/wpcept run

This is my composer.json:
{ "name": "maugelves/seiyuv2", "description": "Seiyu WordPress Theme V2.0", "type": "WordPress Theme", "require": { "codeception/codeception": "^2.2", "lucatume/wp-browser": "~1.11" }, "license": "GPL", "authors": [ { "name": "Mauricio Gelves", "email": "[email protected]" } ] }

The acceptance.suite.yml:
class_name: AcceptanceTester modules: enabled: - WPWebDriver - WPDb config: WPWebDriver: browser: phantomjs port: 4444 window_size: '1024x768' url: 'http://localhost/seiyuwp/' adminUsername: '[email protected]' adminPassword: 'mauricio' adminPath: '/wp-admin' WPDb: dsn: 'mysql:host=127.0.0.1;dbname=seiyudb' user: 'root' password: 'root' dump: 'tests/_data/dump.sql' populate: true cleanup: true reconnect: true url: 'http://localhost/seiyuwp' urlReplacement: false tablePrefix: 'lxpy10ags_'

Problems while installing http://codeception.com/for/wordpress

composer require lucatume/wp-browser --dev
Using version ^1.16 for lucatume/wp-browser
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)

Your requirements could not be resolved to an installable set of packages.

Problem 1
- Installation request for lucatume/wp-browser ^1.16 -> satisfiable by lucatume/wp-browser[1.16.0].
- Conclusion: remove codeception/codeception dev-master
- Conclusion: don't install codeception/codeception dev-master
- lucatume/wp-browser 1.16.0 requires lucatume/wp-browser-commons ^1.2.5 -> satisfiable by lucatume/wp-browser-commons[1.2.5, 1.2.6].
- lucatume/wp-browser-commons 1.2.5 requires codeception/codeception ~2.1 -> satisfiable by codeception/codeception[2.1.x-dev, 2.2.x-dev].
- lucatume/wp-browser-commons 1.2.6 requires codeception/codeception ~2.1 -> satisfiable by codeception/codeception[2.1.x-dev, 2.2.x-dev].
- Can only install one of: codeception/codeception[2.1.x-dev, dev-master].
- Can only install one of: codeception/codeception[2.2.x-dev, dev-master].
- Installation request for codeception/codeception dev-master -> satisfiable by codeception/codeception[dev-master].

My composer.json

{

"require": {



},

"require-dev": {

    "codeception/codeception": "dev-master"

}


}

WPCLI to array throws PHPUnit_Framework_Exception

Hey,

I'm using the WPCLI module and when I call cliToArray I'm getting the exception:

[PHPUnit_Framework_Exception] preg_match() expects parameter 2 to be string, array given

With following stactrace:

#1  Codeception\Subscriber\ErrorHandler->errorHandler
#2  /home/user/.config/composer/vendor/lucatume/wp-browser/src/Codeception/Module/WPCLI.php:237
#3  Codeception\Module\WPCLI->cliToArray
#4  /var/www/wp/wp-content/plugins/some-plugin/tests/_support/_generated/AcceptanceTesterActions.php:3181
#5  /var/www/wp/wp-content/plugins/some-plugin/tests/acceptance/AdminPluginListCest.php:15
#6  AdminPluginListCest->tryToActivatePlugin
#7  /home/user/.config/composer/vendor/lucatume/wp-browser/wpcept:52

I'm using wp-browser version 1.19.3.

Bootstrap fails

I'm trying to run the bootstrap command in a clean WordPress installation and getting this error: Helpers path is not defined by key "paths: helpers". The bootstrap process quits after the error. Am I doing something wrong?

Here's the full output:

$ php ./vendor/bin/wpcept bootstrap
Initializing Codeception in /

PHP Notice:  Undefined property: Codeception\Command\WPBootstrap::$supportDir in /vendor/lucatume/wp-browser/src/WPBootstrap.php on line 24

Notice: Undefined property: Codeception\Command\WPBootstrap::$supportDir in /vendor/lucatume/wp-browser/src/WPBootstrap.php on line 24
PHP Notice:  Undefined property: Codeception\Command\WPBootstrap::$envsDir in /vendor/lucatume/wp-browser/src/WPBootstrap.php on line 25

Notice: Undefined property: Codeception\Command\WPBootstrap::$envsDir in /vendor/lucatume/wp-browser/src/WPBootstrap.php on line 25
File codeception.yml created       <- global configuration
tests/unit created                 <- unit tests
tests/unit.suite.yml written       <- unit tests suite configuration
tests/functional created           <- functional tests
tests/functional.suite.yml written <- functional tests suite configuration
tests/acceptance created           <- acceptance tests
tests/acceptance.suite.yml written <- acceptance tests suite configuration
tests/_bootstrap.php written <- global bootstrap file
Building initial Tester classes



  [Codeception\Exception\Configuration]
  Helpers path is not defined by key "paths: helpers"



bootstrap [-ns|--namespace [NAMESPACE]] [-a|--actor [ACTOR]] [--compat] [--customize] [--] [<path>]

Cest format dependency Injection

We have a project currently that is built ontop of WordPress with codeception as our testing framework.

Currently we are extending each test class with our own WP_UnitTestCase module ( essentially a copy and paste ).

Unfortunately this method does not allow us to perform dependency injection as it appears the codeception framework doesn't pick up on our test case...

Will wp-browser allows us to perform dependency injection without writing test's using the NameOfClassCest ?

Or is the power of codeception's dependency injection lost for us mortals using WordPress unit testing?

(WPLoader) WordPress installation in same process broken?

I'd like to use WPLoader with "isolatedInstall: false" because installing WordPress in an isolated process breaks step by step debugging with xdebug. Calling PHP through a system() call with debugging enable makes it hang.
So when I configure WPLoader with "isolatedInstall: false" I get the following result:

grant@vagrant-ubuntu-trusty-64:/var/www/html/app$ vendor/bin/wpcept run integration --debug
Codeception PHP Testing Framework v2.2.7
Powered by PHPUnit 5.7.5 by Sebastian Bergmann and contributors.

  Running as multisite
  Installing WordPress in same process...
WordPress database error Table 'wptests.int_blogs' doesn't exist for query SHOW FULL COLUMNS FROM `int_blogs` made by Codeception\Application->run, Symfony\Component\Console\Application->run, Symfony\Component\Console\Application->doRun, Symfony\Component\Console\Application->doRunCommand, Symfony\Component\Console\Command\Command->run, Codeception\Command\Run->execute, Codeception\Command\Run->runSuites, Codeception\Codecept->run, Codeception\Codecept->runSuite, Codeception\SuiteManager->initialize, Codeception\Module\WPLoader->_initialize, Codeception\Module\WPLoader->initialize, Codeception\Module\WPLoader->loadWordPress, require_once('/var/www/html/app/vendor/lucatume/wp-browser/src/includes/bootstrap.php'), require('/var/www/html/app/vendor/lucatume/wp-browser/src/includes/same-scope-install.php')
  Installing...
  Installing network...
  <div id="error"><p class="wpdberror"><strong>WordPress database error:</strong> [Table &#039;wptests.int_blogs&#039; doesn&#039;t exist]<br /><code>SHOW FULL COLUMNS FROM `int_blogs`</code></p></div>
  Not running ajax tests. To execute these, use --group ajax.
  Not running ms-files tests. To execute these, use --group ms-files.
  Not running external-http tests. To execute these, use --group external-http.
  

Integration Tests (15) ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Modules: \Helper\Integration, WPLoader
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
- Content_mass_updaterTest: Replace updatePHP Fatal error:  Call to a member function add_filter() on array in /var/www/html/wordpress/wp-includes/plugin.php on line 111
PHP Stack trace:
PHP   1. {main}() /var/www/html/app/vendor/lucatume/wp-browser/wpcept:0
PHP   2. Codeception\Application->run($input = *uninitialized*, $output = *uninitialized*) /var/www/html/app/vendor/lucatume/wp-browser/wpcept:52
PHP   3. Symfony\Component\Console\Application->run($input = *uninitialized*, $output = *uninitialized*) /var/www/html/app/vendor/codeception/codeception/src/Codeception/Application.php:103
PHP   4. Symfony\Component\Console\Application->doRun($input = *uninitialized*, $output = *uninitialized*) /var/www/html/app/vendor/symfony/console/Application.php:122
PHP   5. Symfony\Component\Console\Application->doRunCommand($command = *uninitialized*, $input = *uninitialized*, $output = *uninitialized*) /var/www/html/app/vendor/symfony/console/Application.php:191
PHP   6. Symfony\Component\Console\Command\Command->run($input = *uninitialized*, $output = *uninitialized*) /var/www/html/app/vendor/symfony/console/Application.php:846
PHP   7. Codeception\Command\Run->execute($input = *uninitialized*, $output = *uninitialized*) /var/www/html/app/vendor/symfony/console/Command/Command.php:264
PHP   8. Codeception\Command\Run->runSuites($suites = *uninitialized*, $skippedSuites = *uninitialized*) /var/www/html/app/vendor/codeception/codeception/src/Codeception/Command/Run.php:287
PHP   9. Codeception\Codecept->run($suite = *uninitialized*, $test = *uninitialized*) /var/www/html/app/vendor/codeception/codeception/src/Codeception/Command/Run.php:360
PHP  10. Codeception\Codecept->runSuite($settings = *uninitialized*, $suite = *uninitialized*, $test = *uninitialized*) /var/www/html/app/vendor/codeception/codeception/src/Codeception/Codecept.php:152
PHP  11. Codeception\SuiteManager->run($runner = *uninitialized*, $result = *uninitialized*, $options = *uninitialized*) /var/www/html/app/vendor/codeception/codeception/src/Codeception/Codecept.php:183
PHP  12. Codeception\PHPUnit\Runner->doEnhancedRun($suite = *uninitialized*, $result = *uninitialized*, $arguments = *uninitialized*) /var/www/html/app/vendor/codeception/codeception/src/Codeception/SuiteManager.php:162
PHP  13. PHPUnit_Framework_TestSuite->run($result = *uninitialized*) /var/www/html/app/vendor/codeception/codeception/src/Codeception/PHPUnit/Runner.php:98
PHP  14. PHPUnit_Framework_TestCase->run($result = *uninitialized*) /var/www/html/app/vendor/phpunit/phpunit/src/Framework/TestSuite.php:728
PHP  15. PHPUnit_Framework_TestResult->run($test = *uninitialized*) /var/www/html/app/vendor/phpunit/phpunit/src/Framework/TestCase.php:909
PHP  16. PHPUnit_Framework_TestCase->runBare() /var/www/html/app/vendor/phpunit/phpunit/src/Framework/TestResult.php:701
PHP  17. sofad\Content_mass_updaterTest->setUp() /var/www/html/app/vendor/phpunit/phpunit/src/Framework/TestCase.php:950
PHP  18. Codeception\TestCase\WPTestCase->setUp() /var/www/html/app/tests/integration/sofad/contentMassUpdaterTest.php:23
PHP  19. add_filter($tag = *uninitialized*, $function_to_add = *uninitialized*, $priority = *uninitialized*, $accepted_args = *uninitialized*) /var/www/html/app/vendor/lucatume/wp-browser/src/Codeception/TestCase/WPTestCase.php:156

Fatal error: Call to a member function add_filter() on array in /var/www/html/wordpress/wp-includes/plugin.php on line 111

Call Stack:
    0.0919     249520   1. {main}() /var/www/html/app/vendor/lucatume/wp-browser/wpcept:0
    0.7575    9584592   2. Codeception\Application->run(???, ???) /var/www/html/app/vendor/lucatume/wp-browser/wpcept:52
    0.7575    9584840   3. Symfony\Component\Console\Application->run(???, ???) /var/www/html/app/vendor/codeception/codeception/src/Codeception/Application.php:103
    0.7840    9840736   4. Symfony\Component\Console\Application->doRun(???, ???) /var/www/html/app/vendor/symfony/console/Application.php:122
    0.7841    9841792   5. Symfony\Component\Console\Application->doRunCommand(???, ???, ???) /var/www/html/app/vendor/symfony/console/Application.php:191
    0.7841    9842424   6. Symfony\Component\Console\Command\Command->run(???, ???) /var/www/html/app/vendor/symfony/console/Application.php:846
    0.7849    9849248   7. Codeception\Command\Run->execute(???, ???) /var/www/html/app/vendor/symfony/console/Command/Command.php:264
    0.9379   11388304   8. Codeception\Command\Run->runSuites(???, ???) /var/www/html/app/vendor/codeception/codeception/src/Codeception/Command/Run.php:287
    0.9379   11388888   9. Codeception\Codecept->run(???, ???) /var/www/html/app/vendor/codeception/codeception/src/Codeception/Command/Run.php:360
    0.9523   11433048  10. Codeception\Codecept->runSuite(???, ???, ???) /var/www/html/app/vendor/codeception/codeception/src/Codeception/Codecept.php:152
    6.9144   51195592  11. Codeception\SuiteManager->run(???, ???, ???) /var/www/html/app/vendor/codeception/codeception/src/Codeception/Codecept.php:183
    6.9609   51281000  12. Codeception\PHPUnit\Runner->doEnhancedRun(???, ???, ???) /var/www/html/app/vendor/codeception/codeception/src/Codeception/SuiteManager.php:162
    6.9617   51290904  13. PHPUnit_Framework_TestSuite->run(???) /var/www/html/app/vendor/codeception/codeception/src/Codeception/PHPUnit/Runner.php:98
    6.9621   51294808  14. PHPUnit_Framework_TestCase->run(???) /var/www/html/app/vendor/phpunit/phpunit/src/Framework/TestSuite.php:728
    6.9622   51296520  15. PHPUnit_Framework_TestResult->run(???) /var/www/html/app/vendor/phpunit/phpunit/src/Framework/TestCase.php:909
    6.9786   51337568  16. PHPUnit_Framework_TestCase->runBare() /var/www/html/app/vendor/phpunit/phpunit/src/Framework/TestResult.php:701
    6.9788   51355776  17. sofad\Content_mass_updaterTest->setUp() /var/www/html/app/vendor/phpunit/phpunit/src/Framework/TestCase.php:950
    6.9788   51356120  18. Codeception\TestCase\WPTestCase->setUp() /var/www/html/app/tests/integration/sofad/contentMassUpdaterTest.php:23
    7.1219   51481344  19. add_filter(???, ???, ???, ???) /var/www/html/app/vendor/lucatume/wp-browser/src/Codeception/TestCase/WPTestCase.php:156

FATAL ERROR. TESTS NOT FINISHED.
Call to a member function add_filter() on array 
in /var/www/html/wordpress/wp-includes/plugin.php:111

WPLoader wp_blogs table error

I'm getting the following error message when using WPLoader with multisite: true
I'm not sure the multisite installation actually works...

sgravel@Rond-point-Wordpress:~/staging$ ./wpcept run unit_multisite --env multisite --debug
Codeception PHP Testing Framework v2.2.1
Powered by PHPUnit 5.4.6 by Sebastian Bergmann and contributors.

  Dump file domain not replaced as identical to the one specified in the configuration.
  Running as multisite
Installing...
Installing network...
Adding blog to DBWordPress database error Table 'wordpress_staging.wp_blogs' doesn't exist for query SHOW FULL COLUMNS FROM `wp_blogs` made by Codeception\Application->run, Symfony\Component\Console\Application->run, Symfony\Component\Console\Application->doRun, Symfony\Component\Console\Application->doRunCommand, Symfony\Component\Console\Command\Command->run, Codeception\Command\Run->execute, Codeception\Command\Run->runSuites, Codeception\Codecept->run, Codeception\Codecept->runSuite, Codeception\SuiteManager->initialize, Codeception\Module\WPLoader->_initialize, Codeception\Module\WPLoader->loadWordPress, require_once('/var/www-staging/vendor/lucatume/wp-browser/src/includes/bootstrap.php'), require('/var/www-staging/vendor/lucatume/wp-browser/src/includes/install.php')
<div id="error"><p class="wpdberror"><strong>WordPress database error:</strong> [Table &#039;wordpress_staging.wp_blogs&#039; doesn&#039;t exist]<br /><code>SHOW FULL COLUMNS FROM `wp_blogs`</code></p></div>Blogs insertedPopulated

You can see some extra debug output I added. Here is the modified code:

if ( $multisite ) {
        echo "Installing network..." . PHP_EOL;

        define( 'WP_INSTALLING_NETWORK', true );

        $title = WP_TESTS_TITLE . ' Network';
        $subdomain_install = false;

        /**
         * If we are on multisite the `blogs` table will not have the main blog row set up due to how the instal$
         * Let's add the row now.
         */
    /** @var \wpdb $wpdb */
echo "Adding blog to DB";

        global $wpdb;
        $wpdb->insert($wpdb->blogs, array('site_id' => 1, 'blog_id' => 1, 'domain' => WP_TESTS_DOMAIN, 'path' =>$

echo "Blogs inserted";

        install_network();
        populate_network( 1, WP_TESTS_DOMAIN, WP_TESTS_EMAIL, $title, '/', $subdomain_install );
        $wp_rewrite->set_permalink_structure( '' );

echo "Populated";
}

Question: enabling wpcept command

Hi,

I can't seem to enable the wpcept command. I am able to have WPBrowser and WPRequests enabled in, say, acceptance.suite.yml (codecept build executes without errors), but it feels like I'm missing an obvious step. Do I need to enable all the modules? Do I need to do something outside of the suites' .yml files? In codeception.yml perhaps?

[PHPUnit_Framework_Exception] Use of undefined constant WP_TESTS_FORCE_KNOWN_BUGS - assumed 'WP_TESTS_FORCE_KNOWN_BUGS'

Hi,

I've just setup wpbrowser in an attempt to be able to access plugin methods in my unit test code.

I've created an example unit test using wpcept generate:wpunit suite SomeClass and it generates the following file:

<?php

class SomeClassTest extends \Codeception\TestCase\WPTestCase
{

    public function setUp()
    {
        // before
        parent::setUp();

        // your set up methods here
    }

    public function tearDown()
    {
        // your tear down methods here

        // then
        parent::tearDown();
    }

    // tests
    public function testMe()
    {
    }

}

The problem is that when I run the unit test suite, I get the undefined const error:

bin/wpcept run unit
Codeception PHP Testing Framework v2.2.5
Powered by PHPUnit 5.6.1 by Sebastian Bergmann and contributors.

Unit Tests (1) ---------------------------------------------
E SomeClassTest: Me (0.01s)
------------------------------------------------------------


Time: 834 ms, Memory: 8.00MB

There was 1 error:

---------
1) SomeClassTest: Me
 Test  tests/unit/SomeClassTest.php:testMe

  [PHPUnit_Framework_Exception] Use of undefined constant WP_TESTS_FORCE_KNOWN_BUGS - assumed 'WP_TESTS_FORCE_KNOWN_BUGS'

#1  /usr/share/nginx/html/htdocs/content/themes/my-theme/vendor/lucatume/wp-browser/wpcept:52

ERRORS!
Tests: 1, Assertions: 0, Errors: 1.

As an aside, my WP install is based upon Themosis (http://framework.themosis.com)

Class 'WP_UnitTestCase' not found

Hi,

I created a simple unit test. When I try to run it I get Class 'WP_UnitTestCase' not found in my php_error.log I was able to create and run a simple acceptance test. I'm sure I'm doing something stupid.

Command to execute:
vendor/bin/wpcept run unit

My unit.suite.yml

class_name: UnitTester
modules:
    enabled: [Asserts, UnitHelper]

My test class

<?php
use Simplexity\Cloud\Cdn\ContainerDirector;

class ContainerDirectorTest extends \WP_UnitTestCase
{
    public function setUp()
    {
        // before
        parent::setUp();

        // your set up methods here
    }

    public function tearDown()
    {
        // your tear down methods here

        // then
        parent::tearDown();
    }

    // tests
    public function testMe()
    {
        $dir = new ContainerDirector(2);
        $this->assertEquals('mkjtest', $dir->getContainer());
    }

}

My composer.json

{
  "repositories": [
    {
      "type": "package",
      "package": {
        "name": "wordpress",
        "type": "webroot",
        "version": "4.1",
        "dist": {
          "type": "zip",
          "url": "https://github.com/WordPress/WordPress/archive/4.1.zip"
        },
        "require" : {
          "fancyguy/webroot-installer": "1.0.0"
        }
      }
    }
  ],
  "autoload": {
    "psr-4": {
      "Simplexity\\": "wp-content/plugins/Simplexity"
    }
  },
  "minimum-stability": "dev",
  "prefer-stable": true,
  "require": {
    "php": ">=5.3.0",
    "wordpress": "4.1",
    "fancyguy/webroot-installer": "1.0.0",
    "rackspace/php-opencloud": "~1.12"
  },
  "require-dev": {
    "codeception/codeception": "2.0.10",
    "lucatume/wp-browser": "master@dev"
  },
  "extra": {
    "webroot-dir": "wp",
    "webroot-package": "wordpress"
  }
}

Any ideas would be greatly appreciated.
Thanks.

wpcept.phar

Hello,

Thanks for the hard work.

What about a phar file for this extension? I guess it is easier than using it with composer.

Bad output for multiple consecutive Ajax 'calls'

Hi,
I found a bug when calling multiple Ajax calls in a single test. My tests consists of one Ajax call to get a list of accounts and then use that list to retrieve other properties, again via Ajax calls. The problem I get is that the second call's _last_response contains the text of the first test. This is due to the appending of the previous value in

    public function dieHandler( $message ) {
        $this->_last_response .= ob_get_clean();

Emptying the _last_response at the beggining of _handleAjax fixes this bug but maybe it should be a simple '='? I'm not sure why you append in dieHandler.

    protected function _handleAjax($action) {
        $this->_last_response = NULL;

update: false not detected ?

The test : $I->haveOptionInDatabase("blogname", "MyBlog");

With WPDb: update: false in the yml config give me this message :

  1. Failed to test if admin is working in Admin/CommunCept
    Couldn't have option in database "blogname","MyBlog":
    PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'blogname' for key 'option_name'

When removing the update: false line from the yml config it does work.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.