The Developer Day | Staying Curious

Archive for April 2010

Apr/10

17

PHPUnit email integration testing using Sendmail

One of the problems when doing functional or integration testing is testing that emails are being sent out with a correct header and body. One such scenario could be a controller action which sends a password reset confirmation email and redirects to another action.

A common way to solve such a problem is to configure the local MTA to store the test emails on the file system. The following shows how this could be done using sendmail. First create a sendmail alias by editing a file located at /etc/mail/aliases and adding a line bellow other aliases:

test-mail: “| cat > /tmp/test-mail”

This tells sendmail that all incoming emails to test-mail will be written (not appended) to /tmp/test-mail. Sendmail needs to be restarted for the changes to take effect.

sudo /etc/init.d/sendmail restart

Depending on the situation it may be necessary to add the user who is going to be reading emails (for example apache) to the mail group.

sudo /usr/sbin/usermod -G mail apache

Now using PHP it should be possible to do this:

$ok = mail('test-mail', 'Hello world!', 'I am an email.');
var_dump($ok);
echo file_get_contents('/tmp/test-mail');

Further PHPUnit could be extended to add the following method to the base test case class:

public function assertEmail($attributes, $emailFilePath, 
$message = '', $delta = 0, $maxDepth = 10, 
$canonicalizeEol = FALSE, $ignoreCase = FALSE)
{
    $mailParser = new Company_Product_MailParser;
    $mailData = $mailParser->parseFile($emailFilePath);

    foreach ($attributes as $attribute => $value) {
        $constraint = new PHPUnit_Framework_Constraint_IsEqual(
            $mailData[$attribute], $delta, $maxDepth, $canonicalizeEol, $ignoreCase
        );
        $this->_test->assertThat($value, $constraint, $message);
    }

    if (is_file($emailFilePath) && is_writable($emailFilePath)) {
        unlink($emailFilePath);
    }
}

The mail parser class name explains itself:

class Company_Product_MailParser
{
    public function parseFile($mailFilePath)
    {
        $emailBody = file_get_contents($mailFilePath);
        $attributes = array(
            'to' => '',
            'from' => '',
            'date' => '',
            'subject' => '',
            'body' => ''
        );

        foreach (array_keys($attributes) as $attribute) {
            if($attribute  == 'body') {
                if (preg_match("/\n\n(.*)/", $emailBody, $matches, PREG_OFFSET_CAPTURE)) {
                    $offset = $matches[1][1];
                    $attributes[$attribute] = quoted_printable_decode(substr($emailBody, $offset));
                }
            } else {
                if (preg_match("/" . ucfirst($attribute) . ": (.*)\n/", $emailBody, $matches)) {
                    $attributes[$attribute] = $matches[1];
                }
            }
        }

        return $attributes;
    }
}

Important notice. Sendmail may not immediately send the email and it may take a few seconds for the file to appear. It may require you to add a sleep for a few seconds before the email file appears. If you find a way how it is possible to make sendmail send an email immediately please let me know.

Hide

Apr/10

15

Skinny Controllers and Fat Models

Most of the modern web application frameworks follow the MVC design pattern. It’s probably one of the most misunderstood design patterns in existence. There are a lot of discussions what kind of responsibilities each letter holds. Common misinterpretation in MVC is regarding the letter M.

The Model should be understood as a domain model. Meaning a collection of domain objects. Usually an application has one model that is the domain model. Models are often mistakenly referenced to as singular domain entities. For example an Order, a User or an Account. This leads unwary developers to common application design problems.

It’s common to see a web application to have a directory named “models” with class files inside it. Upon closer inspection one can often find that those classes are the nouns of the application. For example those nouns could be a User, an Order or a Product. In this scenario the MVC Model stands for singular application entities.

Problems start to surface when an application developer has to create reports, do input validation or to implement an ACL. These kind of problems don’t naturally fit into entities. For example getting a report of top 10 products doesn’t naturally fit into any entity. Validating a complex search filter made out of multiple input fields also doesn’t fit into any of the entities.

It’s common to see developers adding logic that doesn’t fit anywhere naturally to controller classes or somewhat close entities. For example adding a top 10 products report to an Order entity class as a static method call. Or validating complicated search filters inside controller actions.

In time this steadily leads to bloated controller and entity classes that later on become fat spaghetti dishes. Controller classes containing thousands of lines of code with more private methods than public ones, entity classes with few state changing methods and hundreds of lines long SQL report queries with joins to 10 tables.

To prevent this from happening it is crucial to understand what controller and model stands for. A controller’s responsibility is only to receive input and initiate a response for the view by making calls on model objects. This means that controllers should be very light and skinny. Usually doing nothing else just instantiating classes, getting data from the domain objects and passing it to the view. Model is not a singular entity and can consist of an entire web of interconnected domain objects. The definition fat model means having as many domain objects as needed. Be it reports, validators, filters, entities, strategies and so on.

, , , , , Hide

Find it!

Theme Design by devolux.org