• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
金大鑫要坚持
博客园    首页    新随笔    联系   管理    订阅  订阅

【playwright学习】fixture和closure学习

学习的话主要材料是官网:https://playwright.dev/python/docs/auth 

基础的话,像我一样薄弱就可以了。会一些java,但python会的不多,用得很少。上手贼容易,但是selenium也不怎么难

在学习之前,要弄清楚@pytest.fixture,closure(nested func)是怎么回事。

个人理解:

fixture:(面试的时候那个人叫夹具)就是跑test之前想做的事情,和跑test之后想做的事情。比如说建立数据库连接,拿到一个登录后的session信息。

一个test可以有多个fixture,每个fixture也可以用别的fixture。一个fixture可能在一个test被request好几次。这个案例有意思。

# contents of test_append.py
import pytest


# Arrange
@pytest.fixture
def first_entry():
    return "a"


# Arrange
@pytest.fixture
def order():
    return []


# Act
@pytest.fixture
def append_first(order, first_entry):
    return order.append(first_entry)


def test_string_only(append_first, order, first_entry):
    # Assert
    assert order == [first_entry]


这段是不是看起来很奇怪?按照常理思考,order 应该是[], [first_entry]是["a"],他们怎么可能相等?

Fixtures can also be requested more than once during the same test, and pytest won’t execute them again for that test. This means we can request fixtures in multiple fixtures that are dependent on them (and even again in the test itself) without those fixtures being executed more than once.

--https://docs.pytest.org/en/6.2.x/fixture.html

结论:即使同一个fixture被请求多次,在一个test里也只调用一次。在test_string_only执行中,先遇到append_first,order就被赋值为['a']了,尽管下一个参数还是fixture order,也不执行了。所以这个case是可以pass的。

fixture可以有哪些其他设定?

1. autouse 顾名思义,就是跑任何test之前都会自动做的set-up

@pytest.fixture(autouse=True)

2.scope设定:function, class, module, package or session

  • function: the default scope, the fixture is destroyed at the end of the test.

  • class: the fixture is destroyed during teardown of the last test in the class.

  • module: the fixture is destroyed during teardown of the last test in the module.

  • package: the fixture is destroyed during teardown of the last test in the package.

  • session: the fixture is destroyed at the end of the test session.

 

closure:方法套方法。套在里面的方法可以用外层方法的变量。外层方法把内层函数名作为返回值

def outer_func(x):

 def inner_func(y):

   return x+y

return inner_func

 
 
posted @ 2024-07-03 11:44  金大鑫要坚持  阅读(76)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3