Skip to content

Commit

Permalink
init project code
Browse files Browse the repository at this point in the history
  • Loading branch information
mocobk committed Aug 19, 2020
0 parents commit c3d4150
Show file tree
Hide file tree
Showing 7 changed files with 287 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
__pycache__/
.idea/
dist/
build/
*egg-info/
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2020

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
108 changes: 108 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
# py-mock
![](https://shields.mitmproxy.org/pypi/v/py-mock.svg)
![](https://shields.mitmproxy.org/pypi/pyversions/py-mock.svg)

```shell
pip install py-mock
```
## py-mock 介绍

`py-mock` 移植了 [Mock.js](https://github.com/nuysoft/Mock
)、[better-mock](https://github.com/lavyun/better-mock)的功能到 Python,如果你熟悉 Mock
.js 的[模板语法](http://mockjs.com/examples.html), 那么在 Python 中也能轻而易举地 Mock
出你想要的数据,`py-mock` `100%` 兼容 Mock.js。

## 一些说明
实际上 `py-mock` 是借助了 `py_mini_racer` 来运行 Mock.js 中的 mock 函数,且仅移植了 Mock.mock
方法,如果有问题可以在 github 上给我提 issue。

## 使用示例

```python
from pprint import pprint

from pymock import Mock

Mock = Mock()

pprint(Mock.mock({
'list|1-10': [{
'id|+1': 1,
'email': '@EMAIL'
}]
}))
```
```
{'list': [{'email': '[email protected]', 'id': 1},
{'email': '[email protected]', 'id': 2},
{'email': '[email protected]', 'id': 3},
{'email': '[email protected]', 'id': 4}]}
```

```python
pprint(Mock.mock(Mock.mock({
'number1|1-100.1-10': 1,
'number2|123.1-10': 1,
'number3|123.3': 1,
'number4|123.10': 1.123
})))
```
```
{'number1': 56.5787,
'number2': 123.14013355,
'number3': 123.695,
'number4': 123.1236478526}
```

```python
pprint(Mock.mock({
'regexp1': r'/[a-z][A-Z][0-9]/',
'regexp2': r'/\w\W\s\S\d\D/',
'regexp3': r'/\d{5,10}/'
}))
```
```
{'regexp1': 'mM8', 'regexp2': 'I;\rI5j', 'regexp3': '575824'}
```
```python
pprint(Mock.mock({
'name': {
'first': '@first',
'middle': '@first',
'last': '@last',
'email': 'example\\@gmail.com',
'full': '@first @middle @last'
}
}
))
```
```
{'name': {'email': '[email protected]',
'first': 'Nancy',
'full': 'Nancy Nancy Lee',
'last': 'Lee',
'middle': 'Nancy'}}
```
```python
# JS object like string
pprint(Mock.mock(
"""{
name: {
first: '@cfirst',
middle: '@cfirst',
last: '@clast',
email: 'example\\@gmail.com',
full: '@first@middle@last'
}
}"""
))
```
```
{'name': {'email': '[email protected]',
'first': '萧',
'full': '萧白强',
'last': '强',
'middle': '白'}}
```

[更多示例](http://mockjs.com/examples.html)
66 changes: 66 additions & 0 deletions pymock/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : mocobk
# @Email : [email protected]
# @Time : 2020/8/18 19:12
import codecs
import json
import json.encoder
import os
import re
import typing

from py_mini_racer import py_mini_racer

__JS_REGEX_PATTERN = re.compile(r'^/.*/$')
__JS_REGEX_ESCAPE_PATTERN = re.compile(r'^\\/.*\\/$')


def encode_regex_basestring_wrap(func):
def wrap(string: str):
if __JS_REGEX_PATTERN.match(string):
return string
else:
if __JS_REGEX_ESCAPE_PATTERN.match(string):
string = f'/{string[2:-2]}/'
return func(string)

return wrap


json.encoder.encode_basestring = encode_regex_basestring_wrap(json.encoder.encode_basestring)
json.encoder.encode_basestring_ascii = encode_regex_basestring_wrap(json.encoder.encode_basestring_ascii)


class MiniRacer(py_mini_racer.MiniRacer):
def call(self, identifier, *args, **kwargs):
""" Call the named function with provided arguments
You can pass a custom JSON encoder by passing it in the encoder
keyword only argument.
"""

encoder = kwargs.get('encoder', None)
timeout = kwargs.get('timeout', 0)
max_memory = kwargs.get('max_memory', 0)

if isinstance(args[0], (dict, list)):
json_args = json.dumps(args, separators=(',', ':'), cls=encoder)
else:
json_args = f'[{args[0]}]'
js = "{identifier}.apply(this, {json_args})"
return self.eval(js.format(identifier=identifier, json_args=json_args), timeout, max_memory)


class Mock:
def __init__(self):
self.__code = codecs.open(os.path.join(os.path.dirname(__file__), 'js/mock.mini_racer.min.js'),
encoding='utf-8').read()
self.__ctx = MiniRacer()
self.__ctx.eval(self.__code)

def mock(self, template: typing.Union[dict, list, str]) -> typing.Union[dict, list]:
"""
:param template: mock template
:return: dict, list
"""
return self.__ctx.call('Mock.mock', template)
1 change: 1 addition & 0 deletions pymock/js/mock.mini_racer.min.js

Large diffs are not rendered by default.

55 changes: 55 additions & 0 deletions samples.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : mocobk
# @Email : [email protected]
# @Time : 2020/8/18 20:16
from pprint import pprint

from pymock import Mock

Mock = Mock()

pprint(Mock.mock({
'list|1-10': [{
'id|+1': 1,
'email': '@EMAIL'
}]
}))

pprint(Mock.mock(Mock.mock({
'number1|1-100.1-10': 1,
'number2|123.1-10': 1,
'number3|123.3': 1,
'number4|123.10': 1.123
})))

pprint(Mock.mock({
'regexp1': r'/[a-z][A-Z][0-9]/',
'regexp2': r'/\w\W\s\S\d\D/',
'regexp3': r'/\d{5,10}/'
}))

pprint(Mock.mock({
'name': {
'first': '@first',
'middle': '@first',
'last': '@last',
'email': 'example\\@gmail.com',
'full': '@first @middle @last'
}
}
))

# JS object like string
pprint(Mock.mock(
"""{
name: {
first: '@cfirst',
middle: '@cfirst',
last: '@clast',
email: 'example\\@gmail.com',
full: '@first@middle@last'
}
}"""
))

31 changes: 31 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# -*- coding:utf-8 -*-
# __auth__ = mocobk
# email: [email protected]

import setuptools

with open("README.md", "r", encoding='utf-8') as fh:
long_description = fh.read()

setuptools.setup(
name="py-mock",
version="1.0.2",
author="mocobk",
author_email="[email protected]",
description="Mock.js for Python3",
long_description=long_description,
long_description_content_type="text/markdown",
keywords="pymock,Mock,Mock.js,better-mock",
url="https://github.com/mocobk/pymock",
packages=['pymock'],
install_requires=['py-mini-racer'],
classifiers=[
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
package_data={'pymock': ['js/*.js']},
)

0 comments on commit c3d4150

Please sign in to comment.