栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Is there a way to sandbox test execution with pytest, especially filesystemaccess?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Is there a way to sandbox test execution with pytest, especially filesystemaccess?

After quite a bit of research I didn’t find any ready-made way for pytest to
run a project tests with OS-level isolation and in a disposable environment.
Many approaches are possible and have advantages and disadvantages, but most
of them have more moving parts that I would feel comfortable with.

The absolute minimal (but opinionated) approach I devised is the following:

  • build a python docker image with:
    • a dedicated non-root user:
      pytest
    • all project dependencies from
      requirements.txt
    • the project installed in develop mode
  • run py.test in a container that mounts the project folder on the host as the home of
    pytest
    user

To implement the approach add the following

Dockerfile
to the top folder of
the project you want to test next to the
requirements.txt
and
setup.py

files:

FROM python:3# setup pytest userRUN adduser --disabled-password --gecos "" --uid 7357 pytestCOPY ./ /home/pytestWORKDIR /home/pytest# setup the python and pytest environmentsRUN pip install --upgrade pip setuptools pytestRUN pip install --upgrade -r requirements.txtRUN python setup.py develop# setup entry pointUSER pytestENTRYPOINT ["py.test"]

Build the image once with:

docker build -t pytest .

Run py.test inside the container mounting the project folder as volume on
/home/pytest with:

docker run --rm -it -v `pwd`:/home/pytest pytest [USUAL_PYTEST_OPTIONS]

Note that

-v
mounts the volume as uid 1000 so host files are not writable by
the pytest user with uid forced to 7357.

Now you should be able to develop and test your project with OS-level
isolation.

Update: If you also run the test on the host you may need to remove the
python and pytest caches that are not writable inside the container. On the
host run:

rm -rf .cache/ && find . -name __pycache__  | xargs rm -rf


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/668229.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号