Matthias NobackMocking at architectural boundaries: persistence and time (20.2.2018, 07:55 UTC)

More and more I've come to realize that I've been mocking less and less.

The thing is, creating test doubles is a very dangerous activity. For example, what I often see is something like this:

$entityManager = $this->createMock(EntityManager::class);

$entityManager->expects($this->once())
    ->method('persist')
    ->with($object);
$entityManager->expects($this->once())
    ->method('flush')
    ->with($object);

Or, what appears to be better, since we'd be mocking an interface instead of a concrete class:

$entityManager = $this->createMock(ObjectManagerInterface::class);
// ...

To be very honest, there isn't a big different between these two examples. If this code is in, for example, a unit test for a repository class, we're not testing many of the aspects of the code that should have been tested instead.

For example, by creating a test double for the EntityManager, we're assuming that it will work well with any objects we'll pass to it. If you've ever debugged an issue with an EntityManager, you know that this is a bad assumption. Anything may go wrong: a mistake in the mapping, missing configuration for cascading persist/delete behavior, an issue with the database credentials, availability of the database server, network connectivity, a missing or invalid database schema, etc.

In short, a unit test like this doesn't add any value, except that it verifies correct execution of the code you wrote (something a linter or static analysis tool may be able to do as well). There's nothing in this test that ensures a correct working once the code has been deployed and is actually being used.

The general rule to apply here is "Don't mock what you don't own" (see the excellent book "Growing Object-Oriented Software, Guided by Tests", or an article on the topic by Eric Smith, "That's Not Yours"). Whenever I've brought up this rule in discussions with developers, I've always met with resistance. "What else is there to mock?" "Isn't mocking meant to replace the slow, fragile stuff with something that is fast and stable?"

Mock across architecturally significant boundaries

Of course we want to use mocks for that. And we need to, since our test suite will become very slow and fragile if we don't do it. But we need to do it in the right place: at the boundaries of our application.

My reasoning for "when to mock" is always:

  1. If you encounter the need for some information or some action that isn't available to you in the memory of the the currently running program, define an interface that represents your query (in case you need to know something) or command (in case you want to do something). Put the interface in the "core" of your application (in the domain or application layer).
  2. Use this interface anywhere you want to send this query or command.
  3. Write at least one implementation for the interface, and make sure all the clients of the interface get this implementation injected as constructor arguments.

Mocking "persistence"

To fix the EntityManager example above we need to take a step back and articulate our reason for using the EntityManager in the first place. Apparently, we were in need of persisting an object. This is not something the running application could do naturally (the moment it stops, it forgets about any object it has in memory). So we had to reach across the application's boundaries, to an external service called a "database".

Because we always considering reusing things that are already available in our project, we just decided to go with the previously installed EntityManager to fulfill our needs. If however we would've followed the steps described above, we would've ended up in a different place:

  1. I need to persist (not just any object, but) my Article entity, so I define an interface that represents the action I intend for it to do:

    interface ArticleRepository
    {
        public function persist(Article $article): void
    }
    
    
  2. I use this interface everywhere in my code.

  3. I provide a default implementation for it, one that uses my beloved EntityManager:

    final class ORMArticleRepository implements A
    

Truncated by Planet PHP, read more at the original (another 6880 bytes)

Link
Nomad PHPThe Container is a Lie! (17.2.2018, 14:57 UTC)

May - US
Presented By

Larry Garfield
May 17, 2018
20:00 CDT

The post The Container is a Lie! appeared first on Nomad PHP.

Link
Andrew Embler6 Things I Learned as an Exhibitor at SunshinePHP 2018 (14.2.2018, 13:51 UTC)

Learn why bigger isn't always better.
Link
Paul M. JonesLine Coverage in Unit Tests (13.2.2018, 13:00 UTC)

The novice says, “I do not strive for 100% line coverage in tests; I only write tests for the code that is important.”

The master says, “If the code is not important, why is it there at all? I will strive to test every line I write; if a line is not important, it should be removed.”

(See also The Way of Testivus.)

Link
SitePoint PHP8 Tips for Improving Bootstrap Accessibility (12.2.2018, 16:00 UTC)

A few years ago, I wrote about my experiences on developing a Bootstrap version 3 project to be fully accessible for people with disabilities. This focussed mostly on how accessible it is in terms of front-end design. (It didn’t cover accessibility in terms of screen readers, as that’s a whole other story.)

While I could see that the developers behind Bootstrap were making an effort, there were a few areas where this popular UI library fell short. I could also see that there were issues raised on the project that showed they were actively improving — which is fantastic, considering how approximately 3.6% of websites use Bootstrap.

Recently, Bootstrap version 4 was released, so let’s take a look and see if any of the issues I had in the past have improved.

What We’re Looking For with Design Accessibility

There are a few things to consider when designing a website with accessibility in mind. I believe these improve the user experience for everyone and will likely cover a lot of points you would consider anyway.

Layout

One way to achieve accessibility is by having a clean, easy-to-use layout that looks good on all devices, as well as looking good at a high zoom level. Up to 200% is a good guide.

Bonus points: having front-end code that matches the layout is also good for users who access the Web with a screen reader or by using a keyboard instead of a mouse.

This allows people to use your website easily irrespective of how they’re viewing it.

Continue reading %8 Tips for Improving Bootstrap Accessibility%

Link
Matthias NobackLocal and remote code coverage for Behat (12.2.2018, 08:48 UTC)

Why code coverage for Behat?

PHPUnit has built-in several options for generating code coverage data and reports. Behat doesn't. As Konstantin Kudryashov (@everzet) points out in an issue asking for code coverage options in Behat:

Code coverage is controversial idea and code coverage for StoryBDD framework is just nonsense. If you're doing code testing with StoryBDD - you're doing it wrong.

He's right I guess. The main issue is that StoryBDD isn't about code, so it doesn't make sense to calculate code coverage for it. Furthermore, the danger of collecting code coverage data and generating coverage reports is that people will start using it as a metric for code quality. And maybe they'll even set management targets based on coverage percentage. Anyway, that's not what this article is about...

In my Advanced Application Testing workshop I just wanted to collect code coverage data to show how different types of tests (system, acceptance, integration and unit) touch different parts of the code. And how this evolves over time, when we're replacing parts of the system under test, or switch test types to achieve shorter feedback loops, etc.

The main issue is that, when it comes to running our code, Behat does two things: it executes code in the same project, and/or (and this complicates the situation a bit) it remotely executes code when it's using Mink to talk to a web application running in another process.

This means that if you want to have Behat coverage, you'll need to do two things:

  1. Collect local code coverage data.
  2. Instruct the remote web application to collect code coverage data itself, then fetch it.

Behat extensions for code coverage

For the workshop, I created two Behat extensions that do exactly this:

  1. LocalCodeCoverageExtension
  2. RemoteCodeCoverageExtension

The second one makes use of an adapted version of the LiveCodeCoverage tool I published earlier.

You have to enable these extensions in your behat.yml file:

default:
    extensions:
        Behat\MinkExtension:
            # ...
        BehatLocalCodeCoverage\LocalCodeCoverageExtension:
            target_directory: '%paths.base%/var/coverage'
        BehatRemoteCodeCoverage\RemoteCodeCoverageExtension:
            target_directory: '%paths.base%/var/coverage'
    suites:
        acceptance:
            # ...
            local_coverage_enabled: true
        system:
            mink_session: default
            # ...
            remote_coverage_enabled: true

Local coverage doesn't require any changes to the production code, but remote coverage does: you need to run a tool called RemoteCodeCoverage, and let it wrap your application/kernel in your web application's front controller (e.g. index.php):

use LiveCodeCoverage\RemoteCodeCoverage;

$shutDownCodeCoverage = RemoteCodeCoverage::bootstrap(
    (bool)getenv('CODE_COVERAGE_ENABLED'),
    sys_get_temp_dir(),
    __DIR__ . '/../phpunit.xml.dist'
);

// Run your web application now...

// This will save and store collected coverage data:
$shutDownCodeCoverage();

From now on, a Behat run will generate a coverage file (.cov) in ./var/coverage for every suite that has coverage enabled (the name of the file is the name of the suite).

The arguments passed to RemoteCodeCoverage::bootstrap() allow for some fine-tuning of its behavior:

  1. Provide your own logic to determine if code coverage should be enabled in the first place (this example uses an environment variable for that). This is important for security reasons. It helps you make sure that the production server won't expose any collected coverage data.
  2. Provide your own directory for storing the coverage data files.
  3. Provide the path to your own phpunit.xml(.dist) file. This file is used for its code coverage filter configuration. You can exclude vendor/ code for example.

Combining coverage data fro

Truncated by Planet PHP, read more at the original (another 1457 bytes)

Link
Michelangelo van DamDeploy Docker containers fast to Microsoft Azure (11.2.2018, 20:22 UTC)

DEPLOY DOCKER CONTAINERS FAST TO MICROSOFT AZURE

It’s hard to ignore the fact that Docker is a way to move forward for rapid application development, distributed architectures and microservices.
For developers Docker offers great advantages as they can build their containers specifically for the task they work on. They grab a base image of a container, modify it for their purpose and prepare the functionality inside the container.
Quality, testing and security teams now have a single instance to look at and ensure all functional and regulatory requirements are met. System engineers now don’t have to worry about providing a system with the required specs as the container is already provisioned for that purpose.
Containers in the cloud
But where do you deploy your Docker containers? You can set up your existing bare metal infrastructure to allow them to run containers, but this also means you need to learn about securing your container infrastructure, which is not an easy task. Luckily “the cloud” offers container services like Google Cloud, RedHat OpenShift and Heroku. The most popular cloud solution providers are also stepping into the game of containers. Amazon Web Services offers Elastic Container Services that allows you deploy your Docker containers directly on their infrastructure.
In this article I’m looking at how to deploy Docker containers on 

Truncated by Planet PHP, read more at the original (another 68625 bytes)

Link
Cees-Jan KiewietReactPHP with RecoilPHP: Creating for/http-middleware-psr15-adapter (9.2.2018, 00:00 UTC)

There are more uses for coroutines than just making working with promises easier. In this post we're diving into the details on how they are used by the Friends of ReactPHP in the PSR-15 Middleware adapter for react/http.

Link
Nomad PHPHow To Ruin A Career In 10 Easy Minutes (8.2.2018, 16:30 UTC)

Speaker: Chris Hartjes @grmpyprogrammer While building up a presence on Twitter I discovered I had the power to really help people…or tear them down if I chose to…which I sometimes did. I want to talk about toxicity in open source projects and why the secret weapon isn’t tight coding or GitHub’s collaborative tools, but empathy.

The post How To Ruin A Career In 10 Easy Minutes appeared first on Nomad PHP.

Link
Matthias NobackCall to conference organisers: pay your workshop instructors (8.2.2018, 08:07 UTC)

A little background: speakers don't get paid

Speakers like myself don't get paid for doing a talk at a tech conference. That's why I call this work "open source". People will get a video or audio recording of the talk, including separately viewable or downloadable slides for free. The idea is, a conference costs a lot of money to organise. It is quite expensive to fly in all those speakers. So there's no money to pay the speakers for all their work (for me personally it's about 80 hours of preparation, plus time spent travelling, usually half a day before and after the conference). Speakers get their travel costs reimbursed, they often get two nights at a hotel, and a ticket to the conference. Plus, they get advertising for their personal brand (increasing their reputation as an expert, a funny person, or just a person with more Google results for their name).

Workshops: also not paid

Ever since I realized that creating workshops is something I like a lot, I started submitting them to conferences as well. This, to me, is a whole different story. There's many hours of educational experience, preparation, and again travel going into this. And delivering a workshop always costs a lot more energy than a single talk does. Often you won't get paid for all that. Nevertheless, it earns the conference organisers a lot more money than a talk does.

Workshops are often planned within the days before the main conference. Ticket prices range from 200 to 800 euro. It often happens to me that I'm delivering my workshop in front of 20-25 people. This means that the conference organisers receive 4000 to 20.000 euros per day per workshop. Surely, there will be costs involved. But even after subtracting those, a workshop instructor will often generate thousands of euros in revenue.

To be fair

I don't think it would be fair to pay workshop instructors the entire amount either (after subtraction of the costs). Having a conference organising your workshop has value too:

  • They have reach: hundreds of people will know about your workshop.
  • They deal with all the administrative work (payments, registration, refunds, etc.).
  • They take care of the well-being of the attendees (parking directions, food, drinks, etc.).

Call to conference organisers

Still, I wanted to point out how wrong the situation is for tutorial/workshop instructors at many PHP conferences I know of. I want to ask you all, conference organisers: next time you organise workshop days for your attendees, make sure to pay your instructors.

Some useful suggestions, which I've learnt from conference organisers I spoke with:

  1. Pay instructors for their work day: €1000,- (plus the usual reimbursement of travel costs, and a hotel night). This isn't quite enough to cover preparation time, but it's a reasonable amount to me.
  2. Let instructors share in the revenue, after subtraction of the costs, e.g. give them 50%. This makes up for the day, and the required preparation. It will also make instructors happy workers.

In fact, Laracon EU is a conference where they do this. Shawn McCool, one of its organisers, said to me:

Paying people for their work is the right thing to do, for both ethics and sustainability.

I totally agree with him. Now, do the right thing and make that change!

Link
LinksRSS 0.92   RDF 1.
Atom Feed   100% Popoon
PHP5 powered   PEAR
ButtonsPlanet PHP   Planet PHP
Planet PHP