在PyTest中,你可以通过设置`--rootdir`参数来更改工作目录。这通常在你需要在测试用例的根目录下进行一些操作的时候非常有用,比如引用静态资源或者读取配置文件。
下面是一个详细的步骤:
1. 在命令行中,运行以下命令来获取当前的工作目录:
```bash
pwd
```
2. 运行以下命令来更改工作目录。在这个例子中,我们将更改为当前目录的子目录`test_cases`:
```bash
cd test_cases
```
3. 在项目根目录下创建一个Python文件,例如`pytest.ini`。在这个文件中,你可以设置`rootdir`参数来改变工作目录:
```ini
[pytest]
rootdir = ./..
```
4. 运行以下命令来运行测试:
```bash
pytest -v
```
在Python代码中,你可以使用`os`模块来获取和更改当前的工作目录。例如,你可以这样做:
```python
import os
# 获取当前工作目录
current_dir = os.getcwd()
print("Current working directory:", current_dir)
# 更改工作目录到父目录
parent_dir = os.path.dirname(current_dir)
os.chdir(parent_dir)
print("Changed to parent directory:", os.getcwd())
```
在这个例子中,我们首先获取当前的工作目录,然后更改到它的父目录。
如果你需要引用静态资源或者读取配置文件,你可以在Python代码中使用`__file__`变量来获取当前文件的绝对路径,然后使用`os`模块来构建资源的路径。例如:
```python
import os
# 获取当前文件的绝对路径
current_file = __file__
print("Current file path:", current_file)
# 获取当前文件所在的目录
current_dir = os.path.dirname(current_file)
print("Current directory:", current_dir)
# 构建资源的路径
resource_path = os.path.join(current_dir, 'resources', 'config.ini')
print("Resource path:", resource_path)
```
在这个例子中,我们首先获取当前文件的绝对路径,然后使用`os.path.dirname()`函数来获取它的目录。然后,我们使用`os.path.join()`函数来构建静态资源的完整路径。
如果你需要应用场景和示例,以下是一个简单的测试用例:
假设你有一个Python脚本`calculator.py`,它包含一个函数`add(a, b)`来计算两个数的和。你的任务是编写一个测试用例来验证这个函数是否正确工作。
首先,你需要创建一个名为`test_calculator.py`的测试文件,并在其中编写以下代码:
```python
import pytest
from calculator import add
def test_add():
assert add(2, 3) == 5
assert add(-1, -1) == -2
```
在这个测试用例中,我们导入了`pytest`模块和`calculator.add`函数。然后,我们定义了一个名为`test_add`的测试函数,它使用`assert`语句来验证`add()`函数是否返回正确的结果。
要运行这个测试,你可以从命令行中运行以下命令:
```bash
pytest test_calculator.py
```
如果所有测试都通过了,你将看到类似于以下的输出:
```bash
============================= test session starts ==============================
platform linux -- Python 3.8.5, pytest-6.2.4, pluggy-0.13.1
rootdir: /home/user/projects/calculator, configfile: pytest.ini
plugins: cov-2.11.1
collected 1 item
tests/test_calculator.py . [100%]
============================== 1 passed in 0.03s ==============================
```
在这个例子中,我们首先导入了`pytest`模块和`calculator.add`函数。然后,我们定义了一个名为`test_add`的测试函数,它使用`assert`语句来验证`add()`函数是否返回正确的结果。