碰到的问题:
- 问题1:pytest 运行脚本报错:UnicodeDecodeError: 'gbk' codec can't decode byte 0xa9 in position 70
- 问题2:日期控件如何定位?
- 问题3:如何单机多个元素?
- 问题4:如何参数化用例?
- 问题5:xpath中的contain方法
- 问题6:关于conftest.py
- 问题7:将一个用例执行多次
- 问题8:print() 方法没打印出来?
- 问题9:assert_in()断言失败?报错:E AssertionError: '6206' not found in '18866660001'
- 问题10:当测试步骤超过10个时候,存在定位失败的问题?
- 问题11:如何使用 if 处理操作步骤的异常场景
- 问题12:如何验证导出的excel能打开,内容正确?
- 问题13:如何界面的数据不是你想的,怎么处理?如何对操作步骤的异常做处理?if做判断
- 问题14:如何处理ie弹框问题?self.ad_block()
- 问题15:如何加密账号和密码?
- 问题16:如何使用token登陆界面?
- 问题17:ImportError: attempted relative import with no known parent package?
- 问题18:如何验证html文件?
- 问题19:参数化运行指定用例,报错:找不到文件
- 问题19:如何用脚本创建培训PPT?
问题1:pytest 运行脚本报错:UnicodeDecodeError: ‘gbk’ codec can’t decode byte 0xa9 in position 70
setting中设置utf-8后,重启下console窗口就好了
问题2:日期控件如何定位?
直接使用 self.type() ,输入对应格式的开始日期和结束日期v
@pytest.mark.smoke
@allure.title("用例标题")
def test_006(self):
self.login()
self.type(页面1.审核时间_开始日期, "2021-11-01")
self.type(页面1.审核时间_结束日期, "2021-11-30")
self.click(页面1.审核时间)
self.click(页面1.搜索)
time.sleep(2) # 等待搜索后界面刷新完成
self.assert_in("2021-11", self.get_text(页面1.表格_审核时间))
问题3:如何单机多个元素?
for i in range(1, 20):
self.click("selector")
问题4:如何参数化用例?
示例1:unittest版本
from parameterized import parameterized
from seleniumbase import BaseCase
class GoogleTests(BaseCase):
@parameterized.expand(
[
["PyPI", "pypi.org", 'img[alt="PyPI"]'],
["Wikipedia", "www.wikipedia.org", "img.central-featured-logo"],
["SeleniumBase GitHub.com", "SeleniumBase", 'img[title*="Sele"]'],
]
)
def test_parameterized_google_search(self, search_key, expected_text, img):
self.open("https://google.com/ncr")
self.type('input[title="Search"]', search_key + "\n")
self.assert_element("#result-stats")
self.assert_text(expected_text, "#search")
self.click('a:contains("%s")' % expected_text)
self.assert_element(img)
if "SeleniumBase" in search_key:
self.click('img[alt="SeleniumBase.io Docs"]')
self.assert_element('[title="SeleniumBase Docs"]')
self.click('a:contains("Features List")')
self.assert_text("Features List", "h1")
示例2:pytest版本
import pytest
@pytest.mark.parametrize('value', ["pytest", "selenium"])
def test_sb_fixture_with_no_class(sb, value):
sb.open("https://google.com/ncr")
sb.update_text('input[title="Search"]', value + '\n')
sb.assert_text(value, "div#center_col")
class Test_SB_Fixture():
@pytest.mark.parametrize('value', ["pytest", "selenium"])
def test_sb_fixture_inside_class(self, sb, value):
sb.open("https://google.com/ncr")
sb.update_text('input[title="Search"]', value + '\n')
sb.assert_text(value, "div#center_col")
问题5:xpath中的contain方法
self.click('//a[contains(text(),"Button")]')
问题6:关于conftest.py
默认情况下,conftest被禁用,因为它可能会覆盖定义SeleniumBase固定装置的pytest插件,
但如果您知道其中,可以您从您的SeleniumBase克隆转到https://github.com/seleniumbase/SeleniumBase/blob/master/ pytest.ini的本地版本,并删除显示–ignore conftest.py。
问题7:将一个用例执行多次
import pytest
from parameterized import parameterized
from seleniumbase import BaseCase
class RepeatTests(BaseCase):
@parameterized.expand([[]] * 2)
def test_repeat_this_test_with_parameterized(self):
self.open("https://seleniumbase.io")
self.click('a[href="help_docs/method_summary/"]')
self.assert_text("API Reference", "h1")
@pytest.mark.parametrize("", [[]] * 2)
def test_repeat_this_test_with_pytest_parametrize(sb):
sb.open("https://seleniumbase.io")
sb.click('a[href="seleniumbase/console_scripts/ReadMe/"]')
sb.assert_text("Console Scripts", "h1")
class RepeatTestsWithPytest():
@pytest.mark.parametrize("", [[]] * 2)
def test_repeat_test_with_pytest_parametrize(self, sb):
sb.open("https://seleniumbase.io")
sb.click('a[href="help_docs/customizing_test_runs/"]')
sb.assert_text("Command Line Options", "h1")
问题8:print() 方法没打印出来?
a = self.get_text(‘css selector’)
print(a)
pytest.ini 文件包括“–capture=no”,它将控制台输出打印到屏幕上。否则,在使用 pytest 运行时,您可能需要添加“-s”作为参数
问题9:assert_in()断言失败?报错:E AssertionError: ‘6206’ not found in ‘18866660001’
因为没有加2秒的等待,直接就定位了,定位到的元素肯定与内容不匹配
问题10:当测试步骤超过10个时候,存在定位失败的问题?
应该增大最大显性等待时间 timeout=30,另外,也可以在该元素定位前等待1秒 delay=1
@pytest.mark.smoke
@allure.title("输入国家、省州、城市、状态、申请时间、审核时间、关键字,点击搜索,搜索到指定数据")
def test_008(self):
self.login()
self.click(页面1.下拉框_国家, timeout=30, delay=1)
self.click(页面1.中国)
self.click(页面1.下拉框_省州, timeout=30, delay=1)
self.click(页面1.陕西)
self.click(页面1.下拉框_城市, timeout=30, delay=1)
self.click(页面1.西安)
self.click(页面1.下拉框_状态, timeout=30, delay=1)
self.click(页面1.状态_选了国省城市后的正常, timeout=30, delay=1)
self.type(页面1.申请时间_开始日期, "2021-01-01")
self.type(页面1.申请时间_结束日期, "2021-11-30")
self.type(页面1.审核时间_开始日期, "2021-01-01")
self.type(页面1.审核时间_结束日期, "2021-11-30")
self.click(页面1.搜索, timeout=30, delay=1)
self.sleep(2)
self.assert_text_visible("西安", 页面1.表格_城市)
问题11:如何使用 if 处理操作步骤的异常场景
@pytest.mark.smoke
@allure.title("用例标题")
def test_013(self):
self.login()
self.click(页面1.xxx)
self.click(页面1.xxx)
if not self.is_selected(页面1.xxx):
self.assert_false(self.is_selected(页面1.xxx))
self.click(页面1.xxx)
self.assert_element_not_visible(页面1.xxx)
else:
self.assert_true(self.is_selected(页面1.xxx))
self.type(页面1.xxx, "99")
self.click(页面1.xxx)
self.assert_element_not_visible(页面1.xxx)
self.sleep(4)
self.assert_element_not_visible(页面1.xxxx)
问题12:如何验证导出的excel能打开,内容正确?
断言excel 文件名正确
断言excel sheet页名正确
断言excel 文件列名正确
断言excel 第三行数据的订单号跟界面获取的一致
import pandas as pd
from .page_objects import 页面1
import datetime
@pytest.mark.smoke
@allure.title("导出excel表格数据,导出成功")
def test_order_002(self):
self.进入界面()
self.click(页面1.搜索)
self.sleep(1)
搜索后界面的订单号 = self.get_text(页面1.第三行数据的订单编号)
self.click(页面1.导出页面1数据)
self.sleep(1)
# self.assert_element(页面1.导出成功提示语)
# self.assert_text("导出数据", 页面1.导出成功提示语)
# self.assert_text_visible("导出数据", 页面1.导出成功提示语)
# self.assert_exact_text("导出数据成功", 页面1.导出成功提示语)
# self.assert_in("成功", self.get_text(页面1.导出成功提示语))
# self.assert_equal("导出数据成功", self.get_text(页面1.导出成功提示语))
# self.assert_true(self.get_text(页面1.导出成功提示语))
self.assert_element_visible(页面1.导出成功提示语)
self.sleep(4)
self.assert_element_not_visible(页面1.导出成功提示语)
# 断言excel 文件名正确
file = f"页面1_{str(datetime.datetime.now()).split(' ')[0]}.xlsx"
self.assert_downloaded_file(file, timeout=3)
sheet_name = list(pd.read_excel(f"./downloaded_files/{file}", sheet_name=None, engine="openpyxl").keys())[0]
# 断言excel sheet页名正确
self.assert_equal("远程连接", sheet_name)
表格数据 = pd.read_excel(f"./downloaded_files/{file}", sheet_name=0)
# 断言excel 文件列名正确
self.assert_equal([i for i in 表格数据.keys()], 页面1.导出表格的所有列名)
# 断言excel 第三行数据的订单号跟界面获取的一致
self.assert_equal(搜索后界面的订单号, str(表格数据.values[2][0]))
问题13:如何界面的数据不是你想的,怎么处理?如何对操作步骤的异常做处理?if做判断
@pytest.mark.smoke
@allure.title("用例标题")
def test_016(self):
self.login()
if self.get_text(页面1.表格_冻结或启用) == "冻结":
self.click(页面1.表格_冻结或启用)
self.click(页面1.冻结_确定)
self.sleep(4) # 等提示语消失,否则后面断言会失败
self.click(页面1.表格_冻结或启用)
self.assert_element_visible(页面1.启用_确定启用该专家)
问题14:如何处理ie弹框问题?self.ad_block()
def login(self):
# 国内
self.open('https://baidu.com')
# 最大化窗口
self.maximize_window()
# 阻止弹框,比如ie浏览器
self.ad_block()
问题15:如何加密账号和密码?
sbase encrypt 将密码转换为暗码
sbase decrypt 将密码转换为明码
from seleniumbase import BaseCase
from seleniumbase import encryption
class DecryptionTests(BaseCase):
def test_decrypt_password(self):
self.open("https://www.saucedemo.com")
password = encryption.decrypt("$^*ENCRYPT=S3BDTAdCWzMmKEY8Gjg=?&#$")
self.type("#password", password)
self.click('input[type="submit"]')
self.assert_element("#inventory_container")
self.assert_element('div:contains("Sauce Labs Backpack")')
问题16:如何使用token登陆界面?
def login(self):
# (1)使用token实现免密登陆
self.open("https://baidu.com/")
self.execute_script('localStorage.setItem("token", "这里是token值");')
self.sleep(3)
self.refresh_page()
self.sleep(3)
问题17:ImportError: attempted relative import with no known parent package?
根因:排查下是不是误删了上下目录的 init.py 的文件
问题18:如何验证html文件?
import pytest
from seleniumbase import BaseCase
@pytest.mark.offline # Can be run with: "pytest -m offline"
class OfflineTests(BaseCase):
def test_load_html_string(self):
html = "<h2>Hello</h2><p><input /> <button>OK!</button></p>"
self.load_html_string(html) # Open "data:text/html," then replace html
self.assert_text("Hello", "h2")
self.assert_text("OK!", "button")
self.type("input", "Goodbye")
self.click("button")
new_html = '<h3>Checkbox</h3><p><input type="checkbox" />Check Me!</p>'
self.set_content(new_html) # Same as load_html_string(), but keeps URL
self.assert_text("Checkbox", "h3")
self.assert_text("Check Me!", "p")
self.assert_false(self.is_selected("input"))
self.click("input")
self.assert_true(self.is_selected("input"))
import os
import pytest
from seleniumbase import BaseCase
@pytest.mark.offline # Can be run with: "pytest -m offline"
class OfflineTests(BaseCase):
def test_demo_page(self):
# Load a local html file into the web browser
dir_path = os.path.dirname(os.path.abspath(__file__))
file_path = dir_path + "/demo_page.html"
self.load_html_file(file_path)
# Assert the title of the current web page
self.assert_title("Web Testing Page")
# Assert that the element is visible on the page
self.assert_element("tbody#tbodyId")
# Assert that the text appears within a given element
self.assert_text("Demo Page", "h1")
# Type/update text in text fields on the page
self.type("#myTextInput", "This is Automated")
self.type("textarea.area1", "Testing Time!\n")
self.type('[name="preText2"]', "Typing Text!")
# Verify that a hover dropdown link changes page text
self.assert_text("Automation Practice", "h3")
self.hover_and_click("#myDropdown", "#dropOption2")
self.assert_text("Link Two Selected", "h3")
# Verify that a button click changes text on the page
self.assert_text("This Text is Green", "#pText")
self.click("#myButton")
self.assert_text("This Text is Purple", "#pText")
# Assert that the given SVG is visible on the page
self.assert_element('svg[name="svgName"]')
# Verify that a slider control updates a progress bar
self.assert_element('progress[value="50"]')
self.press_right_arrow("#myslider", times=5)
self.assert_element('progress[value="100"]')
# Verify that a "select" option updates a meter bar
self.assert_element('meter[value="0.25"]')
self.select_option_by_text("#mySelect", "Set to 75%")
self.assert_element('meter[value="0.75"]')
# Assert an element located inside an iFrame
self.assert_false(self.is_element_visible("img"))
self.switch_to_frame("#myFrame1")
self.assert_true(self.is_element_visible("img"))
self.switch_to_default_content()
# Assert text located inside an iFrame
self.assert_false(self.is_text_visible("iFrame Text"))
self.switch_to_frame("#myFrame2")
self.assert_true(self.is_text_visible("iFrame Text"))
self.switch_to_default_content()
# Verify that clicking a radio button selects it
self.assert_false(self.is_selected("#radioButton2"))
self.click("#radioButton2")
self.assert_true(self.is_selected("#radioButton2"))
# Verify that clicking a checkbox makes it selected
self.assert_false(self.is_selected("#checkBox1"))
self.click("#checkBox1")
self.assert_true(self.is_selected("#checkBox1"))
# Verify clicking on multiple elements with one call
self.assert_false(self.is_selected("#checkBox2"))
self.assert_false(self.is_selected("#checkBox3"))
self.assert_false(self.is_selected("#checkBox4"))
self.click_visible_elements("input.checkBoxClassB")
self.assert_true(self.is_selected("#checkBox2"))
self.assert_true(self.is_selected("#checkBox3"))
self.assert_true(self.is_selected("#checkBox4"))
# Verify that clicking an iFrame checkbox selects it
self.assert_false(self.is_element_visible(".fBox"))
self.switch_to_frame("#myFrame3")
self.assert_true(self.is_element_visible(".fBox"))
self.assert_false(self.is_selected(".fBox"))
self.click(".fBox")
self.assert_true(self.is_selected(".fBox"))
self.switch_to_default_content()
# Assert link text - Use click_link() to click
self.assert_link_text("seleniumbase.com")
self.assert_link_text("SeleniumBase on GitHub")
self.assert_link_text("seleniumbase.io")
self.assert_link_text("SeleniumBase Demo Page")
# Assert exact text
self.assert_exact_text("Demo Page", "h1")
# Highlight a page element (also assert visibility)
self.highlight("h2")
问题19:参数化运行指定用例,报错:找不到文件
解决办法:运行py文件,参数化是ok的:pytest demo_parameterized001.py
pytest demo_parameterized001.py::ExpertManage::test_parameterized_001 报错:
运行指定用例报错:ERROR: not found:demo_parameterized001.py::ExpertManage::test_paramet
erized_001
(no name demo_parameterized001.py::ExpertManage::test_parameterized_001’ in any of [<Moduledemo_parameterized001.py>])
问题19:如何用脚本创建培训PPT?
示例1:presenter/core_presentation.py
from seleniumbase import BaseCase
class PresentationWithChart(BaseCase):
def test_seleniumbase_chart(self):
self.create_presentation(theme="league", transition="slide")
self.create_pie_chart(title="The 4 core areas of SeleniumBase:")
self.add_data_point("Basic API (test methods)", 1)
self.add_data_point("Command-line options (pytest options)", 1)
self.add_data_point("The Console Scripts interface", 1)
self.add_data_point("Advanced API (Tours, Charts, & Presentations)", 1)
self.add_slide("<p>SeleniumBase core areas</p>" + self.extract_chart())
self.add_slide(
"<p>Basic API (test methods). Example test:</p>",
code=(
"from seleniumbase import BaseCase\n\n"
"class MyTestClass(BaseCase):\n\n"
" def test_basics(self):\n"
' self.open("https://store.xkcd.com/search")\n'
' self.type(\'input[name="q"]\', "xkcd book\\n")\n'
' self.assert_text("xkcd book", "div.results")\n'
' self.open("https://xkcd.com/353/")\n'
" self.click('a[rel=\"license\"]')\n"
" self.go_back()\n"
' self.click_link("About")\n'
' self.click_link("comic #249")\n'
" self.assert_element('img[alt*=\"Chess\"]')\n"
),
)
self.add_slide(
"<p>Command-line options. Examples:</p>",
code=(
"$ pytest my_first_test.py\n"
"$ pytest test_swag_labs.py --mobile\n"
"$ pytest edge_test.py --browser=edge\n"
"$ pytest basic_test.py --headless\n"
"$ pytest my_first_test.py --demo --guest\n"
"$ pytest basic_test.py --slow\n"
"$ pytest -v -m marker2 --headless --save-screenshot\n"
"$ pytest parameterized_test.py --reuse-session\n"
"$ pytest test_suite.py --html=report.html --rs\n"
"$ pytest test_suite.py --dashboard --html=report.html\n"
"$ pytest github_test.py --demo --disable-csp\n"
"$ pytest test_suite.py -n=2 --rs --crumbs\n"
"$ pytest basic_test.py --incognito\n"
),
)
self.add_slide(
"<p>The Console Scripts interface. Examples:</p>",
code=(
"$ sbase install chromedriver\n"
"$ sbase install chromedriver latest\n"
"$ sbase mkdir new_test_folder\n"
"$ sbase mkfile new_test.py\n"
"$ sbase print basic_test.py -n\n"
"$ sbase translate basic_test.py -p --chinese -n\n"
"$ sbase translate basic_test.py -p --japanese\n"
"$ sbase translate basic_test.py -c --russian\n"
"$ sbase download server\n"
"$ sbase grid-hub start\n"
'$ sbase grid-node start --hub="127.0.0.1"\n'
"$ sbase grid-node stop\n"
"$ sbase grid-hub stop\n"
"$ sbase options\n"
),
)
self.add_slide(
'<p>Advanced API. "Presenter" example:</p>',
code=(
"from seleniumbase import BaseCase\n\n"
"class MyPresenterClass(BaseCase):\n\n"
" def test_presenter(self):\n"
' self.create_presentation(theme="serif")\n'
' self.add_slide("Welcome to Presenter!")\n'
" self.add_slide(\n"
' "Add code to slides:",\n'
" code=(\n"
' "from seleniumbase import BaseCase\\n\\n"\n'
' "class MyPresenterClass(BaseCase):\\n\\n"\n'
' " def test_presenter(self):\\n"\n'
' " self.create_presentation()\\n"))\n'
" self.begin_presentation(\n"
' filename="demo.html", show_notes=True)'
),
)
self.add_slide(
"<p><b>The End</b></p>",
image="https://seleniumbase.io/cdn/img/sb_logo_g.png",
)
self.begin_presentation(filename="core_presentation.html")
示例2:presenter/my_presentation.py
from seleniumbase import BaseCase
class MyPresenterClass(BaseCase):
def test_presenter(self):
self.create_presentation(theme="serif", transition="none")
self.add_slide(
"<h1>Welcome</h1><br />\n" "<h3>Press the <b>Right Arrow</b></h3>"
)
self.add_slide(
"<h3>SeleniumBase Presenter</h3><br />\n"
'<img width="240" src="https://seleniumbase.io/img/logo3a.png" />'
'<span style="margin:144px;" />'
'<img src="https://seleniumbase.io/other/python_3d_logo.png" />'
"<br /><br />\n<h4>Create presentations with <b>Python</b></h4>"
)
self.add_slide(
"<h3>Make slides using <b>HTML</b>:</h3><br />\n"
'<table style="padding:10px;border:4px solid black;font-size:50;">'
'\n<tr style="">\n'
"<th>Row ABC</th><th>Row XYZ</th></tr>\n"
'<tr style="">'
"<td>Value ONE</td><td>Value TWO</td></tr>\n"
'<tr style="">\n'
"<td>Value THREE</td><td>Value FOUR</td></tr>\n"
"</table><br />\n<h4>(HTML <b>table</b> example)</h4>"
)
self.add_slide(
"<h3>Keyboard Shortcuts:</h3>\n"
'<table style="padding:10px;border:4px solid black;font-size:30;'
'">\n'
"<tr><th>Key</th><th>Action</th></tr>\n"
"<tr><td><b>=></b></td><td>Next Slide (N also works)</td></tr>\n"
"<tr><td><b><=</b></td><td>Previous Slide (P also works)</td></tr>"
"\n<tr><td>F</td><td>Full Screen Mode</td></tr>\n"
"<tr><td>O</td><td>Overview Mode Toggle</td></tr>\n"
"<tr><td>esc</td><td>Exit Full Screen / Overview Mode</td></tr>\n"
"<tr><td><b>.</b></td><td>Pause/Resume Toggle</td></tr>\n"
"<tr><td>space</td><td>Next Slide (alternative)</td></tr></table>"
)
self.add_slide(
"<h3>Add <b>images</b> to slides:</h3>",
image="https://seleniumbase.io/other/seagulls.jpg",
)
self.add_slide(
"<h3>Add <b>code</b> to slides:</h3>",
code=(
"from seleniumbase import BaseCase\n\n"
"class MyTestClass(BaseCase):\n\n"
" def test_basics(self):\n"
' self.open("https://store.xkcd.com/search")\n'
' self.type(\'input[name="q"]\', "xkcd book\\n")\n'
' self.assert_text("xkcd: volume 0", "h3")\n'
' self.open("https://xkcd.com/353/")\n'
' self.assert_title("xkcd: Python")\n'
" self.assert_element('img[alt=\"Python\"]')\n"
" self.click('a[rel=\"license\"]')\n"
' self.assert_text("free to copy and reuse")\n'
" self.go_back()\n"
' self.click_link("About")\n'
' self.assert_exact_text("xkcd.com", "h2")'
),
)
self.add_slide(
"<h3>Highlight <b>code</b> in slides:</h3>",
code=(
"from seleniumbase import BaseCase\n\n"
"<mark>class MyTestClass(BaseCase):</mark>\n\n"
" def test_basics(self):\n"
' self.open("https://store.xkcd.com/search")\n'
' self.type(\'input[name="q"]\', "xkcd book\\n")\n'
' self.assert_text("xkcd: volume 0", "h3")'
),
)
self.add_slide(
"<h3>Add <b>iFrames</b> to slides:</h3>",
iframe="https://seleniumbase.io/demo_page",
)
self.add_slide(
"<h3>Getting started is <b>easy</b>:</h3>",
code=(
"from seleniumbase import BaseCase\n\n"
"class MyPresenterClass(BaseCase):\n\n"
" def test_presenter(self):\n"
' self.create_presentation(theme="serif")\n'
' self.add_slide("Welcome to Presenter!")\n'
" self.add_slide(\n"
' "Add code to slides:",\n'
" code=(\n"
' "from seleniumbase import BaseCase\\n\\n"\n'
' "class MyPresenterClass(BaseCase):\\n\\n"\n'
' " def test_presenter(self):\\n"\n'
' " self.create_presentation()\\n"))\n'
" self.begin_presentation(\n"
' filename="demo.html", show_notes=True)'
),
)
self.add_slide(
"<h3>Include <b>notes</b> with slides:</h3><br />",
code=(
'self.add_slide("[Your HTML goes here]",\n'
' code="[Your software code goes here]",\n'
' content2="[Additional HTML goes here]",\n'
' notes="[Attached speaker notes go here]"\n'
' "[Note A! -- Note B! -- Note C! ]")'
),
notes="<h2><ul><li>Note A!<li>Note B!<li>Note C!<li>Note D!</h2>",
content2="<h4>(Notes can include HTML tags)</h4>",
)
self.add_slide(
"<h3>Multiple <b>themes</b> available:</h3>",
code=(
'self.create_presentation(theme="serif")\n\n'
'self.create_presentation(theme="sky")\n\n'
'self.create_presentation(theme="simple")\n\n'
'self.create_presentation(theme="white")\n\n'
'self.create_presentation(theme="moon")\n\n'
'self.create_presentation(theme="black")\n\n'
'self.create_presentation(theme="night")\n\n'
'self.create_presentation(theme="beige")\n\n'
'self.create_presentation(theme="league")'
),
)
self.add_slide(
"<h2><b>The End</b></h2>",
image="https://seleniumbase.io/img/sb_logo_10.png",
)
self.begin_presentation(
filename="presenter.html", show_notes=True, interval=0
)
示例2:prexenter/py_virtual_envs.py
from seleniumbase import BaseCase
class PythonVirtualEnvs(BaseCase):
def test_py_virtual_envs(self):
self.create_presentation(theme="serif", transition="slide")
self.add_slide(
"<h2>Python Virtual Environments:</h2><br />\n"
"<h2>What, Why, and How</h2><hr /><br />\n"
"<h3>Presented by <b>Michael Mintz</b></h3>\n"
"<p>Granite State Code Camp - Sat, Nov 14, 2020</p>"
)
self.add_slide(
"<p><b>About me:</b></p>\n"
"<ul>"
"<li>I created the <b>SeleniumBase</b> framework.</li>"
"<li>I'm currently the DevOps Lead at <b>iboss</b>.</li>"
"</ul>\n",
image="https://seleniumbase.io/other/iboss_booth.png",
)
self.add_slide(
"<p><b>Topics & tools covered by this presentation:</b></p>"
"<hr /><br />\n"
"<ul>"
"<li>Overview of Virtual Environments</li>"
"<li>Python package management</li>"
'<li>Python 3 "venv"</li>'
"<li>virtualenv / virtualenvwrapper</li>"
'<li>pip / "pip install"</li>'
"<li>requirements.txt files</li>"
"<li>setup.py files</li>"
"</ul>"
)
self.add_slide(
"<p><b>Topics & tools that are NOT covered here:</b></p><hr />\n"
"<br /><div><ul>"
'<li>"conda"</li>'
'<li>"pipenv"</li>'
'<li>"poetry"</li>'
'<li>"pipx"</li>'
"</ul></div><br />"
"<p>(Other Python package management tools)</p>"
)
self.add_slide(
"<p><b>What is a Python virtual environment?</b></p><hr /><br />\n"
"<p>A Python virtual environment is a partitioned directory"
" where a Python interpreter, libraries/packages, and scripts"
" can be installed and isolated from those installed in other"
" virtual environments or the global environment.</p>"
)
self.add_slide(
"<p><b>Why should we use Python virtual environments?</b>"
"</p><hr /><br />\n"
"<p>We should use Python virtual environments because different"
" Python projects can have conflicting Python dependencies that"
" cannot coexist in the same env.</p>"
)
self.add_slide(
"<p><b>Why? - continued</b></p><hr /><br />\n"
"<p>Example: Project A and Project B both depend on"
" different versions of the same Python library!</p>"
"<p>Therefore, installing the second project requirements"
" would overwrite the first one, causing it to break.</p>",
code=(
"# Project A requirement:\n"
"urllib3==1.25.3\n\n"
"# Project B requirement:\n"
"urllib3==1.26.2"
),
)
self.add_slide(
"<p><b>Why? - continued</b></p><hr /><br />\n"
"<p>It is also possible that Project A and Project B"
" require different versions of Python installed!</p>",
code=(
"# Project A requirement:\n"
"Python-3.8\n\n"
"# Project B requirement:\n"
"Python-2.7"
),
)
self.add_slide(
"<p><b>How do we create and use Python virtual envs?</b>"
"</p><hr /><br />\n"
"<div><b>There are tools/scripts we can use:</b></div><br />"
"<ul>"
'<li>The Python 3 "venv" command</li>'
"<li>virtualenv / virtualenvwrapper</li>"
"</ul>"
)
self.add_slide(
'<p><b>Python 3 "venv"</b></p><hr /><br />\n'
'"venv" creates virtual environments in the location where run'
" (generally with Python projects).",
code=(
"# Mac / Linux\n"
"python3 -m venv ENV_NAME\n"
"source ENV_NAME/bin/activate\n\n"
"# Windows\n"
"py -m venv ENV_NAME\n"
"call ENV_NAME\\Scripts\\activate\n\n"
'# (Type "deactivate" to leave a virtual environment.)'
),
)
self.add_slide(
'<p><b>"mkvirtualenv" (from virtualenvwrapper)</b></p><hr />\n'
'<br />"mkvirtualenv" creates virtual environments in one place'
" (generally in your home directory).",
code=(
"# Mac / Linux\n"
"python3 -m pip install virtualenvwrapper\n"
"export WORKON_HOME=$HOME/.virtualenvs\n"
"source `which virtualenvwrapper.sh`\n"
"mkvirtualenv ENV_NAME\n\n"
"# Windows\n"
"py -m pip install virtualenvwrapper-win\n"
"mkvirtualenv ENV_NAME\n\n"
'# (Type "deactivate" to leave a virtual environment.)'
),
)
self.add_slide(
"<p><b>List of commands from virtualenvwrapper</b></p>"
"<hr /><br />",
code=(
"# Create a virtual environment:\n"
"mkvirtualenv ENV_NAME\n\n"
"# Exit your virtual environment:\n"
"deactivate\n\n"
"# Re-enter a virtual environment:\n"
"workon ENV_NAME\n\n"
"# List all virtual environments:\n"
"workon\n\n"
"# Delete a virtual environment:\n"
"rmvirtualenv ENV_NAME"
),
)
self.add_slide(
"<p><b>Determining if you are in a virtual env</b></p>"
"<hr /><br />"
"<p>When activated, the name of your virtual env"
" will appear in parentheses on the left side of your"
" command prompt.</p>",
code=(
"# Example of how it may look on a Windows machine:\n"
"C:\\Users\\Michael\\github> mkvirtualenv my_env\n"
"(my_env) C:\\Users\\Michael\\github>"
),
)
self.add_slide(
'<p><b>Installing packages with "pip install"</b></p><hr /><br />'
"<p>Once you have created a Python virtual environment and are"
" inside, it is now safe to install packages from PyPI,"
" setup.py files, and/or requirements.txt files.</p>\n",
code=(
"# Install a package from PyPI:\n"
"pip install seleniumbase\n\n"
"# Install packages from a folder with setup.py:\n"
"pip install . # Normal installation\n"
"pip install -e . # Editable install\n\n"
"# Install packages from a requirements.txt file:\n"
"pip install -r requirements.txt\n"
),
)
self.add_slide(
'<p><b>Other useful "pip" commands</b></p><hr /><br />',
code=(
"# See which Python packages are installed:\n"
"pip list\n\n"
"# See which installed Python packages are outdated:\n"
"pip list --outdated\n\n"
"# Create a requirements file from installed packages:\n"
"pip freeze > my_requirements.txt"
),
)
self.add_slide(
"<br /><br /><h2><b>Live Demo Time!</b></h2><hr /><br />",
image="https://seleniumbase.io/other/python_3d_logo.png",
)
self.add_slide(
"<h2><b>The End. Questions?</b></h2><hr /><br />\n"
"<h3>Where to find me:</h3>"
"<ul>"
'<li><a href="https://github.com/mdmintz">'
"github.com/mdmintz</a></li>"
'<li><a href="https://github.com/seleniumbase/SeleniumBase">'
"github.com/seleniumbase/SeleniumBase</a></li>"
'<li><a href="https://seleniumbase.io/">'
"seleniumbase.io</a></li>"
"</ul>"
)
self.begin_presentation(
filename="py_virtual_envs.html", show_notes=False, interval=0
)