lucatume / wp-browser

The easy and reliable way to test WordPress with Codeception. 10 years of proven success.
https://wpbrowser.wptestkit.dev/
MIT License
604 stars 86 forks source link

How can I use WordPress functions in tests? #71

Closed tangrufus closed 7 years ago

tangrufus commented 7 years ago

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!

JDGrimes commented 7 years ago

I'm not sure if that option is available in wp browser now or not. I created a custom Codeception module a while back to load WordPress when the browser tests were being run: https://github.com/WordPoints/dev-lib/blob/develop/wpcept/includes/Modules/WordPointsLoader.php

lucatume commented 7 years ago

As JDGrimes rightly states that option was not explicitly supported, yet offered, from the WPLoader module.
With some "tricks" one could use the WPLoader module in functional tests.
I've pushed today an update on the master branch that should make it easier to do that and make it explicit; the feature has been requested enough times to make a point for it and while the work pushed today is just the start it's better than nothing. To answer your question I've [pushed the tests/functional-hack branch to the rest-calculator project] to show how I'm using the new option in it.
See the functional suite configuration file and the test file that should resemble what you are trying to do.

Let me know if that helps; I'm releasing the new support in the next days.

tangrufus commented 7 years ago

Thank you both.

One issue: If two test suites both use WPLoader and have different tablePrefix config, the second suite would use first suite's tablePrefix.

This works

$ codecept run suiteA
$ codecept run suiteB

This results in errors

$ codecept run 

SuiteA passes. However, suitB's WPLoader loads with suiteA's tablePrefix

My affected plugin: https://github.com/TypistTech/sunny

lucatume commented 7 years ago

Thanks for reporting this; I'm working to improve WPLoader compatibility and use in this context in these days and this is a good thing to know. I've opened a separate issue here. I'm closing this issue and tracking further progress there.