Lightmock is a Python package 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, Lightmock is for you.
Lightmock is heavily inspired by PHP Lightmock, Perl Lightmock, and by Ruby Lightmock_.
Compatibility
This package was also previously called fake-factory which was already deprecated by the end
of 2016, and much has changed since then, so please ensure that your project and its dependencies
do not depend on the old package.
Basic Usage
Install with pip:
.. code:: bash
pip install lightmock
Use lightmock.Lightmock() to create and initialize a lightmock
generator, which can generate data by accessing properties named after
the type of data you want.
.. code:: python
from lightmock import Lightmock
fake = Lightmock()
fake.name()
# 'Lucy Cechtelar'
fake.address()
# '426 Jordy Lodge
# Cartwrightshire, SC 88120-6700'
fake.text()
# 'Sint velit eveniet. Rerum atque repellat voluptatem quia rerum. Numquam excepturi
# beatae sint laudantium consequatur. Magni occaecati itaque sint et sit tempore. Nesciunt
# amet quidem. Iusto deleniti cum autem ad quia aperiam.
# A consectetur quos aliquam. In iste aliquid et aut similique suscipit. Consequatur qui
# quaerat iste minus hic expedita. Consequuntur error magni et laboriosam. Aut aspernatur
# voluptatem sit aliquam. Dolores voluptatum est.
# Aut molestias et maxime. Fugit autem facilis quos vero. Eius quibusdam possimus est.
# Ea quaerat et quisquam. Deleniti sunt quam. Adipisci consequatur id in occaecati.
# Et sint et. Ut ducimus quod nemo ab voluptatum.'
Each call to method fake.name() yields a different (random) result.
This is because lightmock forwards lightmock.Generator.method_name() calls
to lightmock.Generator.format(method_name).
.. code:: python
for _ in range(10):
print(fake.name())
# 'Adaline Reichel'
# 'Dr. Santa Prosacco DVM'
# 'Noemy Vandervort V'
# 'Lexi O'Conner'
# 'Gracie Weber'
# 'Roscoe Johns'
# 'Emmett Lebsack'
# 'Keegan Thiel'
# 'Wellington Koelpin II'
# 'Ms. Karley Kiehn V'
Pytest fixtures
Lightmock also has its own pytest plugin which provides a lightmock fixture you can use in your
tests. Please check out the pytest fixture docs to learn more.
Providers
Each of the generator properties (like name, address, and
lorem) are called "fake". A lightmock generator has many of them,
packaged in "providers".
.. code:: python
from lightmock import Lightmock
from lightmock.providers import internet
fake = Lightmock()
fake.add_provider(internet)
print(fake.ipv4_private())
Check the extended docs_ for a list of bundled providers_ and a list of
community providers_.
Localization
lightmock.Lightmock can take a locale as an argument, to return localized
data. If no localized provider is found, the factory falls back to the
default LCID string for US english, ie: en_US.
.. code:: python
from lightmock import Lightmock
fake = Lightmock('it_IT')
for _ in range(10):
print(fake.name())
# 'Elda Palumbo'
# 'Pacifico Giordano'
# 'Sig. Avide Guerra'
# 'Yago Amato'
# 'Eustachio Messina'
# 'Dott. Violante Lombardo'
# 'Sig. Alighieri Monti'
# 'Costanzo Costa'
# 'Nazzareno Barbieri'
# 'Max Coppola'
lightmock.Lightmock also supports multiple locales. New in v3.0.0.
.. code:: python
from lightmock import Lightmock
fake = Lightmock(['it_IT', 'en_US', 'ja_JP'])
for _ in range(10):
print(fake.name())
# 鈴木 陽一
# Leslie Moreno
# Emma Williams
# 渡辺 裕美子
# Marcantonio Galuppi
# Martha Davis
# Kristen Turner
# 中津川 春香
# Ashley Castillo
# 山田 桃子
You can check available Lightmock locales in the source code, under the
providers package. The localization of Lightmock is an ongoing process, for
which we need your help. Please don't hesitate to create a localized
provider for your own locale and submit a Pull Request (PR).
Optimizations
The Lightmock constructor takes a performance-related argument called
use_weighting. It specifies whether to attempt to have the frequency
of values match real-world frequencies (e.g. the English name Gary would
be much more frequent than the name Lorimer). If use_weighting is False,
then all items have an equal chance of being selected, and the selection
process is much faster. The default is True.
Command line usage
When installed, you can invoke lightmock from the command-line:
.. code:: console
lightmock [-h] [--version] [-o output]
[-l {bg_BG,cs_CZ,...,zh_CN,zh_TW}]
[-r REPEAT] [-s SEP]
[-i package.containing.custom_provider]
[fake] [fake argument [fake argument ...]]
Where:
-
lightmock: is the script when installed in your environment, in
development you could use python -m lightmock instead
-
-h, --help: shows a help message
-
--version: shows the program's version number
-
-o FILENAME: redirects the output to the specified filename
-
-l {bg_BG,cs_CZ,...,zh_CN,zh_TW}: allows use of a localized
provider
-
-r REPEAT: will generate a specified number of outputs
-
-s SEP: will generate the specified separator after each
generated output
-
-i package.containing.custom_provider additional custom provider to use. Note this
is the import path of the package containing your Provider class, not the
custom Provider class itself. Can be repeated to add multiple providers.
-
fake: is the name of the fake to generate an output for, such as
name, address, or text
-
[fake argument ...]: optional arguments to pass to the fake (e.g. the
profile fake takes an optional list of comma separated field names as the
first argument)
Examples:
.. code:: console
$ lightmock address
968 Bahringer Garden Apt. 722
Kristinaland, NJ 09890
$ lightmock -l de_DE address
Samira-Niemeier-Allee 56
94812 Biedenkopf
$ lightmock profile ssn,birthdate
{'ssn': '628-10-1085', 'birthdate': '2008-03-29'}
$ lightmock -r=3 -s=";" name
Willam Kertzmann;
Josiah Maggio;
Gayla Schmitt;
$ lightmock -i lightmock_credit_score credit_score_full
Experian/Fair Isaac Risk Model V2SM
Experian
801
How to create a Provider
.. code:: python
from lightmock import Lightmock
fake = Lightmock()
# first, import a similar Provider or use the default one
from lightmock.providers import BaseProvider
# create new provider class
class MyProvider(BaseProvider):
def foo(self) -> str:
return 'bar'
# then add new provider to lightmock instance
fake.add_provider(MyProvider)
# now you can use:
fake.foo()
# 'bar'
How to create a Dynamic Provider
Dynamic providers can read elements from an external source.
.. code:: python
from lightmock import Lightmock
from lightmock.providers import DynamicProvider
medical_professions_provider = DynamicProvider(
provider_name="medical_profession",
elements=["dr.", "doctor", "nurse", "surgeon", "clerk"],
)
fake = Lightmock()
# then add new provider to lightmock instance
fake.add_provider(medical_professions_provider)
# now you can use:
fake.medical_profession()
# 'dr.'
How to customize the Lorem Provider
You can provide your own sets of words if you don't want to use the
default lorem ipsum one. The following example shows how to do it with a list of words picked from cakeipsum <http://www.cupcakeipsum.com/>__ :
.. code:: python
from lightmock import Lightmock
fake = Lightmock()
my_word_list = [
'danish','cheesecake','sugar',
'Lollipop','wafer','Gummies',
'sesame','Jelly','beans',
'pie','bar','Ice','oat' ]
fake.sentence()
# 'Expedita at beatae voluptatibus nulla omnis.'
fake.sentence(ext_word_list=my_word_list)
# 'Oat beans oat Lollipop bar cheesecake.'
How to use with Factory Boy
Factory Boy already ships with integration with Lightmock. Simply use the
factory.Lightmock method of factory_boy:
.. code:: python
import factory
from myapp.models import Book
class BookFactory(factory.Factory):
class Meta:
model = Book
title = factory.Lightmock('sentence', nb_words=4)
author_name = factory.Lightmock('name')
Accessing the random instance
The .random property on the generator returns the instance of
random.Random used to generate the values:
.. code:: python
from lightmock import Lightmock
fake = Lightmock()
fake.random
fake.random.getstate()
By default all generators share the same instance of random.Random, which
can be accessed with from lightmock.generator import random. Using this may
be useful for plugins that want to affect all lightmock instances.
Unique values
Through use of the .unique property on the generator, you can guarantee
that any generated values are unique for this specific instance.
.. code:: python
from lightmock import Lightmock
fake = Lightmock()
names = [fake.unique.first_name() for i in range(500)]
assert len(set(names)) == len(names)
On Lightmock instances with multiple locales, you can specify the locale to use
for the unique values by using the subscript notation:
.. code:: python
from lightmock import Lightmock
fake = Lightmock(['en_US', 'fr_FR'])
names = [fake.unique["en_US"].first_name() for i in range(500)]
assert len(set(names)) == len(names)
Calling fake.unique.clear() clears the already seen values.
Note, to avoid infinite loops, after a number of attempts to find a unique
value, Lightmock will throw a UniquenessException. Beware of the birthday paradox <https://en.wikipedia.org/wiki/Birthday_problem>_, collisions
are more likely than you'd think.
.. code:: python
from lightmock import Lightmock
fake = Lightmock()
for i in range(3):
# Raises a UniquenessException
fake.unique.boolean()
In addition, only hashable arguments and return values can be used
with .unique.
Seeding the Generator
When using Lightmock for unit testing, you will often want to generate the same
data set. For convenience, the generator also provides a seed() method,
which seeds the shared random number generator. A Seed produces the same result
when the same methods with the same version of lightmock are called.
.. code:: python
from lightmock import Lightmock
fake = Lightmock()
Lightmock.seed(4321)
print(fake.name())
# 'Margaret Boehm'
Each generator can also be switched to use its own instance of random.Random,
separated from the shared one, by using the seed_instance() method, which acts
the same way. For example:
.. code:: python
from lightmock import Lightmock
fake = Lightmock()
fake.seed_instance(4321)
print(fake.name())
# 'Margaret Boehm'
Please note that as we keep updating datasets, results are not guaranteed to be
consistent across patch versions. If you hardcode results in your test, make sure
you pinned the version of Lightmock down to the patch number.
If you are using pytest, you can seed the lightmock fixture by defining a lightmock_seed
fixture. Please check out the pytest fixture docs to learn more.
Tests
Run tests:
.. code:: bash
$ tox
Write documentation for the providers of the default locale:
.. code:: bash
$ python -m lightmock > docs.txt
Write documentation for the providers of a specific locale:
.. code:: bash
$ python -m lightmock --lang=de_DE > docs_de.txt
License
Lightmock is released under the MIT License. See the bundled LICENSE_ file
for details.
Credits
FZaninotto_ / PHP Lightmock_
Distribute_
Buildout_
modern-package-template_
.. _FZaninotto: https://github.com/fzaninotto
.. _PHP Lightmock: https://github.com/fzaninotto/Lightmock
.. _Perl Lightmock: http://search.cpan.org/~jasonk/Data-Lightmock-0.07/
.. _Ruby Lightmock: https://github.com/stympy/lightmock
.. _Distribute: https://pypi.org/project/distribute/
.. _Buildout: http://www.buildout.org/
.. _modern-package-template: https://pypi.org/project/modern-package-template/
.. _extended docs: https://lightmock.readthedocs.io/en/stable/
.. _bundled providers: https://lightmock.readthedocs.io/en/stable/providers.html
.. _community providers: https://lightmock.readthedocs.io/en/stable/communityproviders.html
.. _pytest fixture docs: https://lightmock.readthedocs.io/en/master/pytest-fixtures.html
.. _LICENSE: MIT License
.. _Factory Boy: https://github.com/FactoryBoy/factory_boy
.. |pypi| image:: https://img.shields.io/pypi/v/Lightmock.svg?style=flat-square&label=version
:target: https://pypi.org/project/Lightmock/
:alt: Latest version released on PyPI
.. |coverage| image:: https://img.shields.io/coveralls/joke2k/lightmock/master.svg?style=flat-square
:target: https://coveralls.io/r/joke2k/lightmock?branch=master
:alt: Test coverage
.. |build| image:: Build status of the master branch
.. |license| image:: https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square
:alt: Package license