python3+selenium4中文件config.ini指定统一路径示例再结合代码示例
时间: 2024-03-11 09:48:59 浏览: 57
好的,以下是示例代码:
先看config.ini文件的示例:
```
[DEFAULT]
# 统一指定路径
data_dir = /path/to/data/dir
```
然后看Python代码示例:
```python
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
# 读取配置文件中的路径
data_dir = config['DEFAULT']['data_dir']
# 在路径下创建文件夹
import os
folder_path = os.path.join(data_dir, 'new_folder')
os.makedirs(folder_path, exist_ok=True)
```
以上代码中,首先使用`configparser`库读取配置文件`config.ini`中的路径`data_dir`,然后使用`os`库创建一个新的文件夹。注意,`os.makedirs`方法的`exist_ok`参数设置为`True`,表示如果文件夹已经存在就不会报错。
这样就可以统一指定路径并在代码中使用了。
相关问题
请给出Python+Selenium+Pytest+Allure自动化测试工程框架与相关公共代码
以下是一个使用Python+Selenium+Pytest+Allure的自动化测试工程框架示例,包括一些公共的代码:
## 工程结构
```
- project/
- tests/
- test_login.py
- pages/
- base_page.py
- login_page.py
- utils/
- config.py
- driver.py
- logger.py
- reports/
- requirements.txt
- pytest.ini
```
## requirements.txt
```
selenium==3.141.0
pytest==6.2.4
pytest-allure-adaptor==1.7.0
```
## pytest.ini
```
[pytest]
log_cli = true
log_cli_level = INFO
log_cli_format = %(asctime)s [%(levelname)s] %(message)s (%(filename)s:%(lineno)s)
log_file = logs/test.log
log_file_level = INFO
log_file_format = %(asctime)s [%(levelname)s] %(message)s (%(filename)s:%(lineno)s)
markers =
smoke: Run the smoke test cases
regression: Run the regression test cases
```
## utils/config.py
```python
import os
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
DRIVER_PATH = os.path.join(PROJECT_ROOT, 'drivers/chromedriver')
BASE_URL = 'http://example.com'
USERNAME = 'testuser'
PASSWORD = 'testpass'
```
## utils/driver.py
```python
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from utils.config import DRIVER_PATH
def get_driver():
options = Options()
options.add_argument('--headless')
options.add_argument('--disable-gpu')
driver = webdriver.Chrome(executable_path=DRIVER_PATH, options=options)
return driver
```
## utils/logger.py
```python
import logging
import os
from utils.config import PROJECT_ROOT
def get_logger(name):
logger = logging.getLogger(name)
logger.setLevel(logging.INFO)
log_dir = os.path.join(PROJECT_ROOT, 'logs')
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_file = os.path.join(log_dir, 'test.log')
formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s (%(filename)s:%(lineno)s)')
file_handler = logging.FileHandler(log_file)
file_handler.setLevel(logging.INFO)
file_handler.setFormatter(formatter)
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
console_handler.setFormatter(formatter)
logger.addHandler(file_handler)
logger.addHandler(console_handler)
return logger
```
## pages/base_page.py
```python
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from utils.driver import get_driver
from utils.config import BASE_URL
class BasePage:
def __init__(self):
self.driver = get_driver()
self.wait = WebDriverWait(self.driver, 10)
self.base_url = BASE_URL
def open(self, url=None):
if url is None:
url = self.base_url
self.driver.get(url)
def find_element(self, locator):
return self.wait.until(EC.presence_of_element_located(locator))
def find_elements(self, locator):
return self.wait.until(EC.presence_of_all_elements_located(locator))
def click(self, locator):
element = self.find_element(locator)
element.click()
def input(self, locator, text):
element = self.find_element(locator)
element.clear()
element.send_keys(text)
def close(self):
self.driver.quit()
```
## pages/login_page.py
```python
from selenium.webdriver.common.by import By
from pages.base_page import BasePage
from utils.config import USERNAME, PASSWORD
class LoginPage(BasePage):
username_locator = (By.NAME, 'username')
password_locator = (By.NAME, 'password')
submit_locator = (By.CSS_SELECTOR, 'button[type="submit"]')
def login(self, username=USERNAME, password=PASSWORD):
self.open()
self.input(self.username_locator, username)
self.input(self.password_locator, password)
self.click(self.submit_locator)
```
## tests/test_login.py
```python
import allure
import pytest
from pages.login_page import LoginPage
from utils.logger import get_logger
logger = get_logger(__name__)
@allure.feature('Login')
class TestLogin:
@allure.title('Test login with correct username and password')
@allure.severity(allure.severity_level.NORMAL)
@pytest.mark.smoke
def test_login_success(self):
logger.info('Test login with correct username and password')
LoginPage().login()
assert 'Dashboard' in LoginPage().driver.title
@allure.title('Test login with incorrect username or password')
@allure.severity(allure.severity_level.NORMAL)
@pytest.mark.regression
def test_login_failure(self):
logger.info('Test login with incorrect username or password')
LoginPage().login(username='invalid', password='invalid')
assert 'Login' in LoginPage().driver.title
```
使用命令 `pytest --alluredir=./reports` 运行测试,使用命令 `allure serve ./reports` 查看测试报告。
如何在Python Selenium中实现UI自动化测试的配置和测试数据的分离?请提供实现的关键步骤和示例。
要实现UI自动化测试的配置和测试数据的分离,关键在于正确地设计框架结构,并合理地组织代码和数据。以下是一些关键步骤和示例,以指导您如何实现这一目标。
参考资源链接:[Python Selenium UI自动化框架:封装与实战指南](https://wenku.csdn.net/doc/2ix2kkikkx?spm=1055.2569.3001.10343)
首先,创建一个Config目录,用于存放所有配置文件,如ini文件,其中可以包含浏览器驱动路径、服务器地址、测试环境配置等信息。例如:
```python
[Browser]
driver_path =
参考资源链接:[Python Selenium UI自动化框架:封装与实战指南](https://wenku.csdn.net/doc/2ix2kkikkx?spm=1055.2569.3001.10343)
阅读全文