Allows DataObjects to self-populate intelligently with fake data

Overview

Mock DataObjects for SilverStripe

This module provides intelligent content generation functionality to all DataObjects. The object introspects its fields and assigns an example value based on the field type and the name of the field. It also provides a command line utility for generating mock data programatically as well as various UI features in the CMS to support the creating and populating DataObjects.

Installation

Installation via Composer is highly recommended, as this module has external dependencies.

composer require unclecheese/mock-dataobjects:dev-master

Example

class StaffMember extends DataObject {

	private static $db = array (
		'FirstName' => 'Varchar(255)',
		'LastName' => 'Varchar(255)',
		'EmailAddress' => 'Varchar(255)',
		'Address' => 'Varchar(255)',
		'City' => 'Varchar(255)',
		'PostalCode' => 'Varchar(255)',
		'Country' => 'Varchar(255)',
		'Company' => 'Varchar(255)',
		'Website' => 'Varchar(255)',
		'PhoneNumber' => 'Varchar(255)',
	);


	private static $has_one = array (
		'Photo' => 'Image',
		'StaffHolder' => 'StaffHolder',
	);
}
$staff = new StaffMember();
$staff->fill();

Result:

Screenshot

Implementation

You can use the features of the MockDataObjects module in many ways, including executable code, a command-line interface, and from within the CMS.

From the CMS

Adding mock children to a parent page:

Right click on the parent page and choose "Add mock children."

Screenshot

Choose options, and create

Screenshot

Adding items to a grid

Just click on "add mock data" and set your options.

Screenshot

Populating existing records

Click on "fill with mock data"

Screenshot

In the execution pipeline

$myDataObject->fill();

As demonstrated above, the ->fill() method populates a DataObject with mock data. There are a few options you can pass to this method.

$myDataObject->fill(array(
	 'only_empty' => true, // only fill in empty fields
	 'include_relations' => true, // Include has_many and many_many relations
	 'relation_create_limit' => 5, // If no existing records for many_many or has_one relations, limit creation
	 'download_images' => false, // Don't download images from the web. Use existing.
));

From the command line

Create 50 new records. Use existing files for file relationships.

mockdata generate Product -count 50 --no-downloads

Populate existing records with new data.

mockdata populate Product

Add new records to the has_many relation on a given page.

mockdata generate StaffMember -parent-field StaffPageID -parent "our-staff"

Localisation

Mock data values are localised to the current locale as defined by i18n::get_locale().

i18n::set_locale('en_US');
$staff = new StaffMember();
$staff->fill();
echo $staff->PhoneNumber; // (102) 806-3915

i18n::set_locale('fr_FR');
$staff = new StaffMember();
$staff->fill();
echo $staff->PhoneNumber; // +33 8 17 54 64 62

Field name hooks

For generic database fields, such as Varchar, the mock data generator is informed by the field name in order to create more realistic data. These hooks are defined in the language file.

en:
  MockDataObject:
    FIRSTNAME: "Firstname, FirstName"
    LASTNAME: "Surname, LastName, Lastname"
    FULLNAME: "FullName"
    CITY: "City, Town"
    STATE: "State"
    ADDRESS: "Address, Address1, Address2"
    POSTCODE: "Zip, Zipcode, ZipCode"
    COUNTRYCODE: "Country, CountryCode"
    PHONENUMBER: "Phone, PhoneNumber, Fax, Cell, Mobile, Telephone, Phonenumber"
    EMAIL: "Email, EmailAddress"
    COMPANY: "Company, CompanyName, Organization"
    URL: "URL, Website, URI"
    LATITUDE: "Latitude, Lat"
    LONGITUDE: "Longitude, Lon"

A comma-separated list of possible field names are mapped to an entity, so that a field named "EmailAddress" or "Email" creates a fake email address, and "Phone" or "Telephone" creates a fake phone number.

An example language file for French might look like this:

fr:
  MockDataObject:
    FIRSTNAME: "Prenom"
    LASTNAME: "NomDeFamille, Nom"
    CITY: "Ville"

Model-independent data generation

Sometimes it is useful to generate mock data before the model has been created, such as when frontend development is happening before backend development. For that purpose, every DataObject comes with a $Fake method to access the fake data generator.

$Fake.Email

Find us on a map!

$Fake.Latitude, $Fake.Longitude">
<h2>$Fake.Wordsh2>
$Fake.Paragraphs(2,5) 
$Fake.Image.SetWidth(100)

<h3>What we can do for youh3>
<ul>
  <% loop $Fake.Loop %>
    <li>$Fake.Number $Fake.Wordsli>
  <% end_loop %>
ul>

<h3>Contact Ush3>
$Fake.Company<br />
$Fake.FullName<br />
$Fake.Address<br />
$Fake.Address<br />
$Fake.City, $Fake.State $Fake.PostalCode<br />
$Fake.PhoneNumber<br />
<a href="mailto:$Fake.Email">$Fake.Emaila> <h3>Find us on a map!h3> $Fake.Latitude, $Fake.Longitude

Cleaning up

Records of all mockdata creation are stored in the MockDataLog table, which maps a record ID to a class name. You can clean this table using the task dev/tasks/MockDataTask cleanup . To clear all mock data, leave the class name argument null.

Be very careful about converting mock data records into authentic records, as this task will clean them up without knowing that you have populated them with valid data!

Troubleshooting

Just ring Uncle Cheese.

Comments
  • Grid field actions not available

    Grid field actions not available

    Hi UC,

    The GridField 'Add Mock Data' form never seems to show up automatically for me - the only way I can get it is to manually add it to a GridField. Is there a trick to this? When I manually add it with $config->addComponent(new MockDataGenerator()); it shows up above the form but still works fine. Of course I'd rather not do it that way as I have to remove it before I publish the site.

    screen shot 2015-07-30 at 1 54 57 pm

    screen shot 2015-07-30 at 1 59 17 pm

    opened by jonom 5
  • CLI Tool fixes

    CLI Tool fixes

    Replaces #20 and #22

    • --no-relations flag now works (previously was misspelled as --no-releations and even if it was supplied the task didn't act on it)
    • re-written param parser for the CLI tool so it:
      • Throws error if there are too many arguments
      • Throws error if there are unrecognised options
      • Returns keyed params array including "command" and "class"
    • No more strict PHP notices
    • exit codes used to signify success / faiure of CLI tools where possible
    • closes the sake process when finished
    • Can now run mockdata from vendor/bin/mockdata
    opened by dhensby 1
  • NEW Allow blacklisting DB fields from mocking

    NEW Allow blacklisting DB fields from mocking

    It's currently not possible to add mock members because the PasswordEncryption field is filled with Lorem text instead of a valid password encryptor.

    This change adds the ability to add per class blacklists to dataobjects and adds the PasswordEncryption field to the default blacklist for members - allowing them to work out of the box

    opened by dhensby 1
  • MockDataObject should detect DB before using RAND()

    MockDataObject should detect DB before using RAND()

    MockDataObject should detect database type before it uses RAND() for sort order.

    We're using PostgreSQL and this doesn't work if you select "Include relations".

    simple function that detects DB name and returns name of random function:

        static function get_DB_Rand() {
            if (DB::get_conn() instanceof MSSQLDatabase) {
                return 'RAND()'; // ? is it
            } else if(DB::get_conn() instanceof PostgreSQLDatabase) {
                return 'RANDOM()';
            } else if(DB::get_conn() instanceof MySQLDatabase) {
                return 'RAND()';
            }
        }
    
    opened by t3hn0 1
  • FIX Stop strict errors on CLI tool

    FIX Stop strict errors on CLI tool

    Following error is thrown when using CLI tools:

    Strict Standards: Only variables should be passed by reference in /var/www/html/silverstripe-mock-dataobjects/mockdata on line 82
    PHP Strict Standards:  Only variables should be passed by reference in /var/www/html/silverstripe-mock-dataobjects/mockdata on line 82
    

    The arguments to stream_select should be variables passed by reference (see http://php.net/manual/en/function.stream-select.php). This patch fixes the error output.

    opened by dhensby 0
  • Added standard .gitattributes file

    Added standard .gitattributes file

    Hello!

    I'm helpful robot. I noticed you don't have a git attributes file. You were forcing my brother and sister robots to download files you were never going to use anyway. I hope you feel better ignoring those files...

    Have a nice day! [pirrrrrlk]

    opened by helpfulrobot 0
  • Added standard Travis config

    Added standard Travis config

    Hello!

    I'm helpful robot. I noticed you have a tests folder but no Travis config file. I think this one might work for you.

    Have a nice day! [grrrrbbrrrbb]

    opened by helpfulrobot 0
  • Converted to PSR-2

    Converted to PSR-2

    Hello!

    I'm helpful robot. I noticed there were some deviations from PSR-2 in your code. The core committer team recently decided to transition SilverStripe Framework and CMS to PSR-2, and the supported module standard recommends following PSR-2. I've gone ahead and converted files in code and tests to PSR-2. If this sounds like something you'd like to merge then go right ahead! Feel free to ask questions or make suggestions for how I can help you more. I've been programmed with a wide range of responses.

    Have a nice day! [gzzzzrrrkt]

    opened by helpfulrobot 0
  • Support $can_be_root=false

    Support $can_be_root=false

    Fixes unclecheese/silverstripe-mock-dataobjects#7

    Note: All I've done is make the setting of the ParentID happen earlier. I left the write() part where it was as I assume it needs to follow the fill() call.

    opened by jonom 0
  • Added standard Scrutinizer config

    Added standard Scrutinizer config

    Hello!

    I'm helpful robot. I noticed you don't have a Scrutinizer config file. This one adds many code quality checks. If you are unsure of how to connect your repository to Scrutinizer, read the guide I wrote for you humans.

    Have a nice day! [brrrrb, click]

    opened by helpfulrobot 0
  • Added standard code of conduct file

    Added standard code of conduct file

    Hello!

    I'm helpful robot. Ever seen two robots fighting over code? That's because most of us know the robot code of conduct. Did you know SilverStripe has a code of conduct, for community interaction?

    Have a nice day! [tick tick tick]

    opened by helpfulrobot 0
  • Mock pages persist in CMS

    Mock pages persist in CMS

    Generated some mock children and now can't delete them. Tried removing them with the task but they look like this:

    screen shot 2015-11-30 at 3 46 23 pm

    Trying to delete them from the CMS gives: "This page doesn't exist"

    Wonder if some updating may be required for compatibility with the new 'Archive' action in 3.2.

    Sorry don't have time to look in to a fix right now but thought worthwhile to report.

    opened by jonom 0
  • Error messages are not cleared from session

    Error messages are not cleared from session

    Keep displaying on subsequent use of the MockChildrenForm (e.g. Page type "Blog Entry" is not allowed on the root level). Seems to be set here: https://github.com/unclecheese/silverstripe-mock-dataobjects/blob/master/code/admins/MockChildrenController.php#L163 But not sure what happens after that.

    opened by jonom 0
Releases(1.1.0)
Owner
Aaron Carlino
Principal Product Developer, Silverstripe Ltd. Core team.
Aaron Carlino
Faker is a PHP library that generates fake data for you

Faker is a PHP library that generates fake data for you. Whether you need to bootstrap your database, create good-looking XML documents, fill-in your persistence to stress test it, or anonymize data taken from a production service, Faker is for you.

FakerPHP 1.7k Aug 23, 2021
A drop in fake logger for testing with the Laravel framework.

Log fake for Laravel A bunch of Laravel facades / services are able to be faked, such as the Dispatcher with Bus::fake(), to help with testing and ass

Tim MacDonald 363 Dec 19, 2022
Magic Test allows you to write browser tests by simply clicking around on the application being tested, all without the slowness of constantly restarting the testing environment.

Magic Test for Laravel Magic Test allows you to write browser tests by simply clicking around on the application being tested, all without the slownes

null 400 Jan 5, 2023
Allows the running of PHPUnit within ExpressionEngine

EE Unit Tests EE Unit Tests is an Add-on for ExpressionEngine that allows developers to execute unit tests from the Command Line. EE Unit Tests uses P

Eric Lamb 6 Jan 14, 2022
Removes final keywords from source code on-the-fly and allows mocking of final methods and classes

Removes final keywords from source code on-the-fly and allows mocking of final methods and classes. It can be used together with any test tool such as PHPUnit or Mockery.

David Grudl 326 Dec 9, 2022
Provides generic data providers for use with phpunit/phpunit.

data-provider Installation Run composer require --dev ergebnis/data-provider Usage This package provides the following generic data providers: Ergebni

null 25 Jan 2, 2023
TestDummy makes the process of preparing factories (dummy data) for your integration tests as easy as possible

TestDummy TestDummy makes the process of preparing factories (dummy data) for your integration tests as easy as possible. As easy as... Build a Post m

Laracasts 461 Sep 28, 2022
Silverstripe-populate - Populate your database through YAML files

Populate Module This module provides a way to populate a database from YAML fixtures and custom classes. For instance, when a building a web applicati

Silverstripe CMS 22 Oct 3, 2022
Searchable DataObjects is a module that permit to include DataObjects into frontend search

Searchable DataObjects Searchable DataObjects is a module that permit to include DataObjects into frontend search. Introduction Pages are not always t

Gabriele Brosulo 25 May 11, 2022
Learn how to set up a fake authentication web page on a fake WiFi network.

Evil Twin - Mark VII Learn how to set up a fake authentication web page on a fake WiFi network. Read the comments in these two files to get a better u

Ivan Šincek 44 Dec 13, 2022
Silverstripe-ideannotator - Generate docblocks for DataObjects, Page, PageControllers and (Data)Extensions

silverstripe-ideannotator This module generates @property, @method and @mixin tags for DataObjects, PageControllers and (Data)Extensions, so ide's lik

SilverLeague 44 Dec 21, 2022
Codeception DB module addon for populate database

Database Populator for Codeception DB Module Codeception DB module addon that helps you to tune database populations. So for a test you could load onl

Sergei Predvoditelev 19 Jun 8, 2022
Faker is a PHP library that generates fake data for you

Faker Faker is a PHP library that generates fake data for you. Whether you need to bootstrap your database, create good-looking XML documents, fill-in

FakerPHP 2.7k Dec 27, 2022
Faker is a PHP library that generates fake data for you

Faker is a PHP library that generates fake data for you. Whether you need to bootstrap your database, create good-looking XML documents, fill-in your persistence to stress test it, or anonymize data taken from a production service, Faker is for you.

FakerPHP 1.7k Aug 23, 2021
Framework - 🙃 Phony. Real-like Fake Data Generation Framework

?? Framework This repository contains the ?? Phony Framework. ?? Start generating fake data with ?? Phony Framework, visit the main Phony Repository.

Phonyland 5 Oct 31, 2022
This package provides some basic methods to implement a self updating functionality for your Laravel application. Already bundled are some methods to provide a self-update mechanism via Github or some private repository via http.

This package provides some basic methods to implement a self updating functionality for your Laravel 5 application. Already bundled are some methods to provide a self-update mechanism via Github.

Holger Lösken 311 Dec 31, 2022
Provides Fake Chat integration for Symfony Notifier.

Fake Chat Notifier Provides Fake Chat (as email during development) integration for Symfony Notifier. DSN example FAKE_CHAT_DSN=fakechat+email://defau

Symfony 8 May 23, 2022
Fake SMS (as email during development) Notifier Bridge

Fake SMS Notifier Provides Fake SMS (as email during development) integration for Symfony Notifier. DSN example FAKE_SMS_DSN=fakesms+email://default?t

Symfony 17 May 23, 2022
This package provides the database factory experience to fake Http calls in your testsuite.

This package provides the database factory experience to fake Http calls in your testsuite

DIJ 11 May 2, 2022
Robot increase telegram post 👁‍🗨Telegram Fake Posts Viewer👁‍🗨

Program Features - ?? Very and stylish design. - ?? It has glass buttons. - ?? Has a professional management panel. - ?? Has a user area. - ?? Free di

hack4lx 4 Nov 25, 2022