Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 27 ยท Security and quality

Testing and Debugging Extensions

Debug OpenCart extensions with the error log, debug settings and Xdebug, and test them by keeping logic out of controllers and faking the registry and database.

OpenCart has no built-in test framework for extensions. Many extension authors therefore test by clicking through the store, which works until the code has more than a handful of branches. The good news is that you can get most of the benefit of automated tests with a simple habit: keep the decisions in plain PHP classes that do not depend on OpenCart, and let the controller and model be thin adapters. Plain classes can be tested in milliseconds without a database, a web server or a browser.

In this lesson you will learn where OpenCart writes errors and how to read them, how to attach a debugger, how to structure code for testing, how to fake the registry and the database, and what to check on a staging store before a release. The real OpenCart setup is read-only here, because OpenCart cannot run on this site. The runnable examples are plain PHP stand-ins: a tiny test harness and a fake registry. Money handling is covered in Money as Integers, and the registry itself in Models, the Registry and the Database.

Where errors go

OpenCart has a global error handler. It turns PHP warnings and notices into log lines, and optionally prints them on the page. The relevant settings are in System > Settings > Edit store > Server: Display Errors, Log Errors, and the Error Log Filename. The log file is by default error.log inside the storage/logs folder (your storage folder is outside the web root, as set up in Setting Up a Development Store).

A sensible split:

Environment Display errors Log errors
Development on on
Staging off on
Production off on

Never leave Display Errors on in production. Besides looking unprofessional, error text reveals file paths and sometimes SQL. Check the log with a command line tool (read-only):

TEXT
tail -f storage/logs/error.log

Your own code can write to the same file with $this->log->write('Acme badge: product ' . (int)$product_id . ' has no rule');. Log facts that help you reproduce a problem (ids, counts, states) and never log passwords, tokens or full card data. Because an unlimited log can fill a disk, keep your own messages for unusual situations and not for every request.

Typical log lines and what they mean:

  • PHP Notice: Undefined index: ... in .../model/... or Undefined array key: you read a key that does not exist; use ?? or isset.
  • PHP Fatal error: Uncaught Error: Call to a member function ... on null: usually a model that was not loaded with $this->load->model(...), or a wrong route.
  • Error: Could not load model extension/acme/...: the file name, folder or class name does not follow the naming rules of Anatomy of an Extension.

Developer settings and caches

On the admin dashboard, the gear button opens the developer settings. They control the theme (Twig) cache and the SASS cache. While you edit templates, switch the Twig cache off or clear it after each change, otherwise you debug a page that does not use your newest file. Turn it on again for production. Events are stored in the database, so if you changed an event's trigger or action in code, the old row is still used until you reinstall or edit it, a very common "my event does not fire" cause (see Events).

Attaching Xdebug

A step debugger lets you stop at a line and look at all variables, which is faster than adding var_dump calls. With Xdebug 3, put these in php.ini (read-only; exact extension file name depends on your PHP build):

INI
zend_extension=xdebug
xdebug.mode=debug
xdebug.start_with_request=trigger
xdebug.client_host=127.0.0.1
xdebug.client_port=9003

Setting start_with_request=trigger means the debugger starts only when the request carries the XDEBUG_TRIGGER cookie or parameter, so normal requests stay fast. In your editor, listen for debug connections on port 9003, set a breakpoint in your model, and request the page with the trigger. A breakpoint in getQuote() or getTotal() shows you the real address, cart and settings. Remove Xdebug from production, where it slows every request.

Make logic testable

Here is a typical untestable method (read-only):

PHP
public function getQuote(array $address): array {
    $weight = $this->cart->getWeight();
    $rows = $this->db->query("SELECT ... FROM ... WHERE ...")->rows;
    // 40 lines of decisions mixed with registry calls
}

To test its decisions you would need a working cart, a database with the right tables, a configuration and a session. Instead, split it:

  1. A pure class (say RateTable) takes simple values (weight, country, rows as arrays) and returns a simple result. It has no $this->registry, no $this->db.
  2. The model or controller gathers the values from the registry, calls the pure class, and formats the answer. It is short and has almost nothing to get wrong.

You then write PHPUnit-style tests for the pure class. A PHPUnit test (read-only; PHPUnit and Composer are not available on this site) looks like this:

PHP
use PHPUnit\Framework\TestCase;
use Acme\Shipping\RateTable;

final class RateTableTest extends TestCase
{
    public function testHeavyParcelHasNoRate(): void
    {
        $table = new RateTable([['upTo' => 5.0, 'cents' => 900]]);
        $this->assertNull($table->costFor(9.0));
    }
}

You run it from your extension's own folder with vendor/bin/phpunit, with its own composer.json for development only. Do not ship vendor/ or the tests inside the .ocmod.zip unless you intend to (Packaging, Marketplace and Upgrades covers what belongs in a package).

A tiny test harness

Since PHPUnit cannot run here, the stand-in below contains a 30-line harness with test() and assertSame(). It is a toy, but it works like the real thing and shows the structure of tests: arrange, act, assert, one behavior per test. The class under test is a handling-fee rule with no framework in it.

PHP A mini test harness

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The boundary tests (9999, 10000) are the valuable ones: off-by-one mistakes (> instead of >=) live exactly there. The deliberately wrong last test shows what a failure message looks like, which should tell you what was expected and what happened.

Faking the registry and the database

Sometimes the code you want to test really does call the registry, for example a model that reads settings and queries a table. You can still test it, by giving it a fake registry whose config, db and cart are tiny objects you control. OpenCart's own classes use magic access ($this->config resolves to registry->get('config')), so your code under test needs only an object with get() and a query() method that returns what you prepared.

The stand-in below does that with a fake registry, a fake configuration, a fake database that records every query it gets, and a small model that is a thin layer over rules.

PHP A model tested with a fake registry

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The last line is a useful kind of assertion: a disabled module must not touch the database at all. Fakes that record calls let you test such things as "no query", "exactly one query" or "the id was cast to a number in the SQL".

For tests that must run real SQL, use a disposable test database (a separate schema, never the shop's) and create the few tables you need in the test setup. Keep these few and slow tests apart from the many fast ones.

A staging checklist

Even with unit tests, test the integration on a copy of the real store before a release:

  1. Install the extension from the .ocmod.zip through the extension installer, exactly as a customer will, and uninstall and reinstall it.
  2. Test with Display Errors on and watch error.log: a clean install and a clean checkout should add no lines.
  3. Run it with the Twig cache on, then off. Test at least two languages and two currencies.
  4. Test as a guest, a logged-in customer, and an admin with limited permissions.
  5. Walk through the whole purchase for each payment and shipping method you touch, including a failure path (declined payment, address outside the shipping zone).
  6. Check on both supported OpenCart versions, and on a narrow phone-sized screen for storefront output.
  7. Look at the database after uninstall: did your tables, settings and events go away?

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where does OpenCart write PHP errors by default when Log Errors is enabled?

    The log file name is configurable in the Server settings, and it lives in the storage folder outside the web root.
  2. 2. What is the main benefit of moving decisions into a plain class without registry access?

    A class that takes simple values and returns simple results needs no framework to run, so tests are small and fast.
  3. 3. Which test case is most likely to catch an off-by-one error in a free-over-threshold rule?

    Mistakes such as using > instead of >= only show at the boundary.
  4. 4. Your event change has no effect after you edited the PHP file that registers it during install. What is a likely cause?

    Events live in a database table. Edit or recreate the row (for example by reinstalling) after changing the registration.
  5. 5. Why is a fake database that records queries useful?

    Recording lets you check behavior such as "a disabled module runs no queries" without a real database.

Summary

  • Read storage/logs/error.log; show errors on development, only log them on staging and production, and write your own helpful lines with $this->log->write().
  • Turn the Twig cache off while editing templates, and remember that events live in the database.
  • Use Xdebug with start_with_request=trigger to step through real requests, and keep it out of production.
  • Keep decisions in pure classes and make controllers and models thin; test the pure part with PHPUnit-style tests, especially at boundaries.
  • Fake the registry, configuration and database for the rest, and let fakes record calls.
  • Finish with a staging checklist: clean install and uninstall, no log lines, multiple languages, roles and payment paths.

Next: Performance in Extensions