Git Product home page Git Product logo

php-mongomock's Introduction

MongoDB mock classes

Unit tests

Author and license

Martin Helmich
This library is MIT-licenced.

Synopsis and motivation

This class contains implementations of the MongoDB\Collection and MongoDB\Database classes (not to be confused with the Mongo\Collection class from the deprecated mongo extension) that can store, modify and filter documents in memory, together with a set of (optional) PHPUnit assertions.

I wrote this library because I wanted to unit-test a library that used MongoDB collections intensively and felt that mocking the MongoDB\Collection class using PHPUnit's built-in mock builders was too restrictive.

Note: Currently, this implementation contains only a subset of the actual MongoDB collection API. I've only implemented the parts of the API that I needed for my use case. If you need additional functionality, feel free to open an issue, or (better yet) a pull request.

Installation

$ composer require --dev helmich/mongomock

Compatibility

There are several release branches of this library, each of these being compatible with different releases of PHPUnit and PHP. The following table should give an easy overview:

"Mongomock" version PHPUnit 4 PHPUnit 5 PHPUnit 6 PHPUnit 7 PHPUnit 8 PHPUnit 9
v1 (branch v1), unsupported ๐Ÿšซ โœ… ๐Ÿšซ ๐Ÿšซ ๐Ÿšซ ๐Ÿšซ
v2 (branch master) ๐Ÿšซ ๐Ÿšซ โœ… โœ… โœ… โœ…

When you are using composer require and have already declared a dependency to phpunit/phpunit in your composer.json file, Composer should pick latest compatible version automatically.

Usage

You can use this library exactly as you'd use the MongoDB\Collection or MongoDB\Database classes (in theory, at least -- remember, this package is not API-complete):

use Helmich\MongoMock\MockCollection;

$collection = new MockCollection();
$collection->createIndex(['foo' => 1]);

$documentId = $collection->insertOne(['foo' => 'bar'])->insertedId();
$collection->updateOne(['_id' => $documentId], ['$set' => ['foo' => 'baz']]);

Differences

In some aspects, the MongoDB\Collection's API was extended to allow for better testability:

  1. Filter operands may contain callback functions that are applied to document properties:

    $r = $collection->find([
        'someProperty' => function($p) {
            return $p == 'bar';
        }
    ]);
  2. Filter operands may contain PHPUnit constraints (meaning instances of the PHPUnit_Framework_Constraint class). You can easily build these using the factory functions in the PHPUnit_Framework_Assert class.

    $r = $collection->find([
        'someProperty' => \PHPUnit_Framework_Assert::isInstanceOf(\MongoDB\BSON\Binary::class)
    ]);

Testing

To run the tests (anywhere with a running Docker installation):

$ docker-compose run php7phpunit
$ docker-compose run php8phpunit

php-mongomock's People

Contributors

dependabot-preview[bot] avatar dependabot-support avatar filecage avatar hpaknia avatar jrattue avatar justine avatar kevinkl3 avatar kevinl4a avatar martin-helmich avatar prilka avatar raffis avatar severens avatar shadiakiki1986 avatar tarikhajk avatar tdimdimich 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

Watchers

 avatar  avatar  avatar  avatar  avatar

php-mongomock's Issues

Class "MongoDB\Model\CollectionInfoLegacyIterator" not found

The listCollections() function returns an error. PHP version 8.0.11.

Code to reproduce:

$mongodbDatabase = new MockDatabase('database');
$mongodbDatabase->createCollection('collection');
print_r($mongodbDatabase->listCollections());

Output:
Error: Class "MongoDB\Model\CollectionInfoLegacyIterator" not found

Create a new tag.

Could you please create a new tag with the countDocuments method.

[ '$exists' => false ] doesn't work in a test

Hi @martin-helmich , I have a problem with some tests that check if some fields exist or not.
In the Mongodb infrastructure it works fine but not with MockCollection.

Here is the example:

$this->collection->find([[
      'field' => @[ '$exists' => false ],
 ]);

here is the documentation that verifies that you can search like this.

My solution:

$result = $val !== null;

Change for:
$result = ($val === null && $operand == false ) ? true : (($val !== null && $operand == false ) ? false : $val !== null);

Should `->find()` return references?

First of all: Thank you for your awesome work!

I stumpled upon the issue that find() does return references of documents rather than clones. As I am relatively new to MongoDB, I am not sure whether this might be some sort of crazy magic feature the library brings - I assume it's not and that it is a bug in mongomock.

Example

$collection = new MockCollection('anyCollection');
$documentId = $collection->insertOne(['foo' => 'bar'])->getInsertedId();

// Get the document we've just inserted
$document = $collection->find(['_id' => $documentId]);

// Update the document
$collection->updateOne(['_id' => $documentId], ['foo' => 'baz']);

// Should be false, but is actually true:
if ($document === $collection->findOne(['_id' => $documentId])) {
    echo "Oh no, references are bad!";
} else {
    echo "All good!";
}

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.