Sunday, 10 May 2020

ASSERT THAT STR MATCHES REGEX IN PYTEST

Once in a while every Pythonista faces a need to test that some string value matches a regex pattern. When it comes we have no option but to use re module directly.
import re

def test_something_very_useful():
    value = get_some_string()
    assert re.match('\d+', value)
While it works fine in case of lone string, it's not always convenient to do the same when a string is a part of more complex data structure (e.g. dict), because you need to extract the string, check it and only then get back to check rest attributes.
import re

def test_something_even_more_useful():
    mapping = get_some_structure()

    # inconvenient and boring! :(
    assert 'value' in mapping
    value = mapping.pop('value')
    assert re.match('\d+', value)

    # rest assertion
    assert mapping = {'foo': 1,
                      'bar': 2}
Fortunately, it's pretty easy to write convenient pytest helper that would check a pattern as a part of checking the whole data structure.
def test_something_even_more_useful():
    mapping = get_some_structure()
    assert mapping = {'foo': 1,
                      'bar': 2,
                      'value': pytest_regex('\d+')}
Looks better, huh? :) So the trick is done by the following few lines which we're successfully using in XSnippet API.
import re

class pytest_regex:
    """Assert that a given string meets some expectations."""

    def __init__(self, pattern, flags=0):
        self._regex = re.compile(pattern, flags)

    def __eq__(self, actual):
        return bool(self._regex.match(actual))

    def __repr__(self):
        return self._regex.pattern
Well, actually, it's not by any means tied to pytest and could be used even in non-test production code, though I found this rather queer.

from : https://kalnytskyi.com/howto/assert-str-matches-regex-in-pytest/

Friday, 1 May 2020

Verify if a local port is available in python

Simply create a temporary socket and then try to bind to the port to see if it's available. Close the socket after validating that the port is available.
def tryPort(port):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    result = False
    try:
        sock.bind(("0.0.0.0", port))
        result = True
    except:
        print("Port is in use")
    sock.close()
    return result

from : https://stackoverflow.com/questions/43270868/verify-if-a-local-port-is-available-in-python

Tuesday, 28 April 2020

python用bumpversion管理软件的版本信息

python提供了bumpversion工具,可以极简的管理项目的版本。

准备
pip install bumpversion
1
在项目根目录下新建.bumpversion.cfg,内容可以参考:

[bumpversion]
current_version = 0.9.1
commit = True
tag = False

[bumpversion:file:VERSION]
1
2
3
4
5
6
跟目录下,新建VERSION文件,内容为
0.9.1

使用实例
bumpversion patch
1
则VERSION文件自动变成0.9.2,同时自动git commit。

参考
https://pypi.python.org/pypi/bumpversion

为什么用bumpversion
上述例子太简单,以至于很多人觉得可以自己手动改数字。
问题是,实际项目的版本分布在多个文件,例如setup.py, docs/xxx文件等等,人工一个个修改,易错且浪费时间。
bumpversion可以一句话搞定!
————————————————
版权声明:本文为CSDN博主「mania_yan」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/yyw794/java/article/details/79892042

from : https://blog.csdn.net/yyw794/article/details/79892042

Saturday, 25 April 2020

Python Convert String to Boolean

今天在撰寫 AWS Lambda 時因為從環境變數讀取設定的關係,需要把字串轉成布林來做判斷,一般的想法不外乎 Python 會幫你轉換,或是用 bool(“True”) 轉換就可以,首先其實 Python 是不會幫你轉換的,這點很重要! Python 在形態方面其實是不會做自動轉換的,他只會很阿莎力的報錯,不過大家肯定想說用 bool() 轉換就沒問題了吧!? 事實上,這個地雷害我今天搞了半小時才解決…
事實上在 Python 裡面,你不管喂什麼給 bool() 他都只會回傳 True,只有 bool(0) 的時候是 False,包括以下這些情況都是回傳 True 哦:
bool("True")
bool("false")
bool("False")
bool("0")
是的別懷疑,你不管喂什麼給他,幾乎都只會獲得 True,一不小心把它放進條件裡面就會造成特異現象。
如果你想要把字串轉換成布林的話,建議使用 distutils.util 提供的 strtobool ,這是 Python 內建的模組,功能蠻強大的,可以參考下面的範例
from distutils.util import strtobool

strtobool("True")
strtobool("Yes")
strtobool("Y")
strtobool("true")
以上這些都可以正確轉換成 True 哦,根本就是神器阿!!!

from : https://coder.tw/?p=7017

Friday, 24 April 2020

Ignoring empty files from coverage report

As of coverage.py 4.0, the --skip-covered option is available to do exactly

coverage report --skip-covered --rcfile=/path/to/.coveragerc -m


from : http://www.hackerav.com/?post=237009

Documentation - Mock & Testfixtures

Testfixtures is a collection of helpers and mock objects that are useful when writing automated tests in Python.

from : https://testfixtures.readthedocs.io/en/latest/index.html

PynamoDB

PynamoDB was written from scratch to be Pythonic, and supports the entire DynamoDB API.

from : https://pynamodb.readthedocs.io/en/latest/quickstart.html