#unit-testing
1 messages ยท Page 21 of 1
Heres what my csv looks like now
See the problem is that each country has like 20 lines and I have like 300+ countries so Id rather have python or SQL do something like if country = afghanistan then Asia
Yes that's what I have in mind
cool cool
We can first insert all countries from a text file to SQL dB maybe
Sure how can i start>
Hmm what kind of file do you have all the countries in
Create a new document and edit with others at the same time -- from your computer, phone or tablet. Get stuff done with or without an internet connection. Use Docs to edit Word files. Free from Google.
This is a google doc with the code i used in SQL but it has all of the countries and the assigned continent
Can you give the access I have requested for the access to the file
Im sorry, I think i changed it to anyone with link can view
Ok I got it
Cool thanks
What we can do is we can make a table with two columns first continent and country
No no no
We can also make a table for each continent how would that be?
sure, make the table in where though? Like a dictionary in python or a table in excel?
SQL table
Table in SQL.db file
Before that we need to make a list for all the countries for inserting them automatically
How do I launch that? I only have experience in access and razorsql. But im down to figure out Sqllite3
Then after inserting the data it will be able to differentiate between continents for a country
Sqlite3 is the simplest dB I have seen till now I don't know about razor SQL but i am pretty sure this would be easy
sure is it just an import for python?
Yes you don't need to install any libraries
is it alright if I do it from a jupyter notebook?
I don't have any experience in juoyter notebook
I don't even know what it is I haven't tried it yet
It looks like its working in my notebook, im gonna try to make the table
So first make the table and make the values country and continent
Then make a list with country and continent like this [(country 1,continent1),(country2, continent 2)]
This is what I have so far
Yes that's great
Remember to add conn.commit and c.close at the end or you might get lock errors
Then make a list with country and continent like this [(country 1,continent1),(country2, continent 2)]
@proper wind
Ok im gonna try it out
@inland oar wait a minute
I have found a library which tells you what continent it is by giving in the country
Is this allowed for you?
I think I got the error you mentioned
Yes thats fine
I can use anything pretty much because she isnt grading this part, only my stats analysis in R.
yup, should I continue adding in the rest of them, its gonna take me a while to go through all of them though sorry but I can probably have it in like 15 min
But if you have the data you can just paste it in list and make some loops and it will automatically enter it into the db
can you help me out with that part, im so rusty in python havent had to use it in a year ๐ฉ
You can just copy the names of countries from Wikipedia for the specific continent and just copy paste copy paste and for loop for inserting from the list and your done
I have the countries and names on the doc
What is the deadline for this
its due like in a month, but the thing is I have a bunch of slacker group mates and so I wanted to send them a dataset they could work on within the next few days or they are gonna say "I couldnt work on the project because our data doesnt have the continents column"
Ok so what's the time at your place rn
I can't do it rn but I will be free at night at my place
its 4:41 Am lmao, ive been trying to do this for hours. yea man i appreciate all your help
I could even slide you some $10 or so for your time on paypal
No no
I am just doing it for experience and would you be up at like 3 pm at your place?
2 or 3 pm
yea that works, i can be online at either time
Ok so I will try to do it by 2 or 3pm or if not done we will do it together at that time
This doesn't seem to be related to the topic of this channel
Now Its like 1 pm at my place so I have things to do
do you want me to email you my excel file?
Yea but we started and we did not realize that sorry @digital grotto
@digital grotto sorry I think we are wrapping up and we can talk somewhere else instead?
Yes you can and just add me as a friend and we can catch up at night
My email is HappyGamer 1331@gmail.com
It's alright, just please be mindful next time.
Can you add me? Im kinda new to discord and Ill email you rn so just email me back ill keep an eye on it tomorrow around 12-2.
Ok
Ok bro bye
Any good tutorails for pyautogui other than the documentation ?
shrug
How do you get the current url using selenium??
Pls anyone??

@bold fossil driver.current_url
def command(name, function):
if choice==name:
function()
def jeff():
print('jeff')
command('jeff', jeff())
how do i make this work?
@bold fossil
driver.current_url
@ashen basin I have tried that, it didn't work
I am using python 3 with the latest version of selenium
how do you use monkeypatch for testing a class that has a method that uses requests.get(url)?
@sleek frigate Typically you'd go and patch requests.get directly, mocking the return type that you want to be processed. That depends on how you've imported it however; for example, if you have something like
# api.py
from requests import get
```you'd want to mock `api.get` as it's a different "name" from `requests.get`, even if it comes from the requests package
@sterile sparrow interesting, i did try that but maybe im implementing it wrong? let me post some code snippets of what i have
# test suite for league scraper class
import pytest
import requests
from league_scraper import LolScraper
class MockResponse:
def get(self, url):
if url == 'https://leagueoflegends.fandom.com/wiki/Aatrox':
with open('local_test_pages/aatrox.html') as a:
self.text = a.read()
@pytest.fixture
def mock_response(monkeypatch):
'''Requests.get will return MockResponse instead'''
def mock_get(url):
r = MockResponse()
r.get(url)
return r
monkeypatch.setattr(league_scraper, 'get', mock_get)
@pytest.fixture
def test_scraper():
'''Creates LolScraper object to use for tests'''
return LolScraper()
def test_champ_stats_collected(test_scraper):
'''Test if there are stats collected for a champion'''
url = 'https://leagueoflegends.fandom.com/wiki/Aatrox'
test_scraper.scrape_champion_page(url)
assert len(test_scraper.champion_stats) == 1```
so i have a class called LolScraper that has a method called scrape_champion_page that uses requests.get(). I have mock response class that I am trying to use in place of it
i tried mokeypatch.setattr(league_scraper, 'get', mock_get) since league_scraper is the name of the script that is using the get requests
thanks for responding btw, its been hard to understand just from docs for me as im new to tests
why do you use ''' ''' instead of #?
print(soup.select('.flt-subhead1 gws-flights-results__price gws-flights-results__cheapest-price'))
``` I have this soup code, that keeps returning none, or an empty list, I checked the website triplets, and it is the same id and not the ones that keep changing, so why ain't it finiding it?
question
i dont understand what am i doing wrong here
i think the error says that its my chrome's version and my Selenium's version but its 86 and my Chrome is 86 too
@ashen basin I have tried that, it didn't work
@bold fossil wdym by it didn't work
did you get an error?
print ('ok')```
Ignore the bad indent I'm on phone
And then when I went to youtube
It still printed 'ok'
used for documenting classes/functions/modules
@gentle terrace oh sure
so i got an issue rn basically its a discord bot that gathers messages from users and stores them in a list, problem is if a user decides to put code in the list instead of a normal word (like sql injection) the command will be ran from the list when i use the eval() function, here is my simplified example
equations = ["os.system('tasklist')"]
for equation in range(0, len(equations)):
eval(equations[equation])```
anyone know a way around this so cmds aren't ran from a list just @ me thanks
@proper wind make the equation match a regex before eval? You're almost in parser territory, no easy answers
@mint scroll how would i do something like that?
@near shadow Pinging here as it's a more appropriate channel for that question. Let's say you have something like
from threading import Lock
class SafeValue:
def __init__(self, value):
self._value = value
self._lock = Lock()
@property
def value(self):
with self._lock:
return self._value
@value.setter
def value(self, value):
with self._lock:
self._value = value
```you want to test for race conditions in your code, a simple way of doing that is to spawn `n` amount of threads, with each thread incrementing an `int` wrapped in `SafeValue`.
```python
from random import randint
from threading import Thread
from time import sleep
def slow_increment(sv):
sleep(randint(0, 100) / 100) # Make sure that each thread finishes at a random time
sv.value += 1
def test_safe_increment():
sv = SafeValue(0)
ts = []
for _ in range(100): # `n` threads means sv.value == `n`
t = Thread(target=slow_increment, args=(sv,))
t.start()
ts.append(t)
for t in ts:
t.join()
assert sv.value == 100
```Ultimately, this test is fairly trivial and will most likely pass every time, considering that the locks do guarantee protection from the same thread doing the same thing at once.
what kind of testing i have to do?
yo so i have a text file containing my messages from discord (i need for ai training)
however i wanna make a program to remove all of the "<@!123456789" from the text file
not sure how im supposed to search thru the file and replace... also the numbers are random altho all are same length
from tab crashed
(Session info: headless chrome=86.0.4240.193)```
any help on why my chrome session is not working i have no clue what to start looking for
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
not sure if this is correct channel
im trying to set up a staging server, i have a web app that i need to start testing
currently just testing on my laptop then pushing to git, which connects to docker
i need help
why does this appear in my replit?
/home/runner/Discord-Bot/index.js:5
});
^
SyntaxError: Unexpected token '}'
Wdym!
How i fix that?
@Hi,
I'm happy to announce that iPOPO has been relased in v1.0.1.
What is iPOPO
iPOPO is a Service-Oriented Component Model (SOCM) based on Pelix,
a dynamic service platform. Both are inspired on two popular Java
technologies for the development of long-lived applications:
the iPOJO component model and the OSGi Service Platform.
iPOPO enables to conceive long-running and modular IT services.
It is based on the concepts specified by OSGi:
- Bundle: a Python module imported using ... continue reading
@gentle terrace
How?
&'5'';6:/
Yo tmvo
Lvo
F. Yfp cm bj ghhelp
CCleaner
Hi all, I'm new here..
I'm working with selenium+pytest (and unittest for the testSuites) and trying to use the allure-pytest, the thing is I'm getting the following error: configparser.NoSectionError: No section: 'common info' (this came from the readProperties.py class that I'm using for configurations such as baseURL and etc..).
Script:
pytest --alluredir=%allure_result_folder% testCases/test_login.py
import configparser
config = configparser.RawConfigParser()
config.read("../Configurations/config.ini")
class ReadConfig:
@staticmethod
def get_url():
url = config.get('common info', 'base_url')
return url
@staticmethod
def get_iccid():
iccid = config.get('common info', 'testing_iccid')
return iccid
a part of test_login.py (there are some helpers function, it works on a regular run):
import unittest
import pytest
from pageObjects.LoginPage import LoginPage
from utilities.helpers import Helpers
from utilities.readProperties import ReadConfig
@pytest.mark.usefixtures("setup")
class LoginTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.url = ReadConfig.get_url()
cls.iccid = ReadConfig.get_iccid()
def test_login_page(self):
self.driver.get(self.url)
Helpers.stop_and_wait(self.driver, 1)
if "Welcome back" in self.driver.page_source:
assert True
else:
Helpers.snip_screen(self.driver)
assert False
Thanks.
ammaa```
I'm trying to develop a function to use with selenium that verifies if data was input correctly. For example, to check if a given textfield is holding what I want it to hold.
Something like:
def verifyInsertion(name, type, xpath, data, attribute='value'):
insertedData = driver.find_element(By.XPATH, xpath)
insertedData = insertedData.get_attribute(attribute)
if insertedData == data:
#type will be used here to verify if it's a number, a select, a checkbox, etc
print(name, " verified with value ", insertedData)
else:
print(name, " could not be verified")
raise Exception(name, " could not be verified")```
That's the solution I came up with. Is it good enough? What you think?
Got Force Close when i added " ,'https://playvalorant.com/en-us/download/' "
I wanna be helper
pytest fails to import the needed modules
the programm by itself runs
and pytest spits this out
any idea?
Google it it's probably missing library (import)
Not sure about your setup but typically it's good to put down your pip depencies somewhere like at least in requirements.txt file or use package manager like poetry
Paths..
"in package"?
Directory plus init.py file
is already done
running pytest in the parent of test and app
Hmm I hate paths try with python -m pytest and package path
At worst PYTHONPATH environment variable can anchor your project
strange, am I doing something unusual or why does it not work like it should
Long answer is that import behaves differently whether one execute python script via file or module as paths might be different. There's documentation for that and I always keep forgetting about it.
Try from project root
Python -m pytest test
same
It faults on trying to import crud via main.py crud as it expects .crud due to path
I'd recommend to use
import .crud
Instead of
Import crud
syntaxerror
Sorry
still
Hmmm i guess you have to read documentation about imports Vs paths then. Can't help from my memory alone
ok thanks anyways
Found it
From . Import crud
Sorry I couldn't recall
It's due to paths if you're running tests it has different find path then if you're running app.
What this does is from this package import crud not from global
Global has no crud module app has
When you run app you run with global path at same directory as main
That's the difference
Does it work for you / another import to fix ?
let me try
web_1 | File "./main.py", line 1, in <module>
web_1 | from . import crud
web_1 | ImportError: attempted relative import with no known parent package
but the test doesn't fail on importing crud anymore
From app.main import app this one might be overriding app package
That error was from running test or main directly ?
Please run test main is different case
app/crud.py:3: in <module>
import todo_model
E ModuleNotFoundError: No module named 'todo_model'
Cool
maybe the issue comes from how I start the app?
Yes
because I start it from within app
That's right
what if I start it from the parent?
You can either fix imports to use package or add app dir To pythonpath
If you start main.py from file that will be root and it will have no idea about the package
If you start test it will notice package app and import from that
I solved it by moving main.py above app
Alright
Still if test lies in different package imports have to use absolute or relative paths or PYTHONPATH has to be amended for import from app to be noticed
I'll try that
It takes forever and for me to try something on pc it's a pain with just one hand as another is broken
get well soon
But basically I have similar setup to your case except the main where I found it PITA to call via module I rather prefer if python script.py works same as python -m script
I figured it out
thank you very much
running the python script from outside and changing all imports to
from . import xxx
did the job
Good
Took me a while to recall though. Would like to pass it on less count of steps but well working on it ๐
How to select somethign in drop down menu with selenium
assert response.json() == {
"priority": None,
"due_date": None,
"description": "This is a test description",
"id": int,
"done": False
}
Is there a way to do something like?
Check if the id is an integer
Hello,
For my unittests, I do a lot of subtest when iterating over an iterable:
for x in "1234567890":
with self.subTest(x=x):
#test
Any idea how to make it less verbose/flatten that?
I was thinking of a decorator
def test(cases, expected:list):
def function(func):
def wrapper():
counter = 0
for case in cases:
value = func(case)
if value == expected[counter]:
print(f"{expected[counter]} passed")
else:
print(f"{expected[counter]} failed")
counter += 1
return wrapper
return function``` smthing like that would work
@test([1, 2, 3], [2, 4, 6])
def main(case):
return case * 2
main()
>>> 2 passed
>>> 4 passed
>>> 6 passed```
idk if that fits your subtests tho
I Made a program that looks up funny memes on youtube by itself
import time
while True:
time.sleep(2)
wrd = ['https://youtube.com']
wrd2 = ['funny memes v300']
keyboard = Controller()
keyboard.press(Key.ctrl)
keyboard.press('t')
keyboard.release(Key.ctrl)
keyboard.release('t')
time.sleep(1)
for x in range(len(wrd)):
for y in wrd[x]:
keyboard.press(y)
keyboard.release(y)
time.sleep(0.02)
keyboard.press(Key.enter)
keyboard.release(Key.enter)
time.sleep(7)
keyboard.press(Key.tab)
keyboard.press(Key.tab)
keyboard.press(Key.tab)
keyboard.press(Key.tab)
keyboard.release(Key.tab)
keyboard.release(Key.tab)
keyboard.release(Key.tab)
keyboard.release(Key.tab)
for x in range(len(wrd2)):
for y in wrd2[x]:
keyboard.press(y)
keyboard.release(y)
time.sleep(0.1)
keyboard.press(Key.enter)
keyboard.release(Key.enter)```
try it in a browser
you will not be disappointed
nice! Did you ever consider using selenium for that?
in my experience its a lot easier to use / more condensed
Sorry, Server member list broke my discord.
Maybe I'll try selenium
I've been practicing pynput
selenium has some really easy to use functions for basic stuff like that
that would be like 5 lines of code
Im not sure if this is the right channel for selenium but my question is how do i keep checking an element
@marble stump I am not sure about selenium specifically, but if you are looking to implement somewhat sophisticated retry mechanisms I had luck using the tenacity library.
hello everyone im looking for some help with selenium ^^
@ me if u need help with webscraping
Can someone recommend any test course??
@proper wind What are you scraping? Is it in any way related to automated software testing, like running unittests or integration tests?
Rather than writing out all the combinations to check with the pytest test I am trying to get fixtures working with parametrize. In essence I want to test each option in a collection with a set of known valid values, rather than every possible combination of all variables. e.g. try every stat with a static number of damage.
Taking the following approach seems to pass the function/fixture rather than the enclosed data. What am I missing?
_primary_stats = []
for stat in utility.get_class_members(PrimaryStat):
_primary_stats.append(stat)
@pytest.fixture(params=_primary_stats)
def primary_stat(request):
return request.param
test_damage_effect_parameters = [
(primary_stat, 1, )
]
@pytest.mark.parametrize(["stat_to_target", "accuracy"], test_damage_effect_parameters)
def test_damage_effect(
benchmark,
stat_to_target,
accuracy
):
...
I tried indirect=True, but every test in the test_damage_effect_parameters fails with "fixture not found"
Has anyone here ever launched autoit (.au3) scripts from a python script? If so what is the easiest way to do this?
Can someone suggest any articles/blog posts/books on "testing the hard-to-test stuff"? Like, the IO boundary or the extremely side-effectful parts.
I have a repo:
src
src/admin_tools
src/c_fixer
src/c_fixer/fixer.py
src/c_fixer/data/
src/tests
src/tests/admin_tools
src/tests/c_fixer
src/tests/c_fixer/main_test.py
src/tests/c_fixer/data/
I want to test my fixer.py, which looks in the data folder with a relative reference ./data/... However, when I run the test, I'm getting FileNotFoundError ./data/...
does anyone know why?
src is my source root
nvm, I had to mess around with the working directory on PyCharm and relative imports ๐
Hi everyone, does anyone know some docs about testing image editing tools with python+selenium?
Hi, I am having hard time to test my webcam for landmark classification
Is there anyway to time schedule fb messenger with python?
assert response.json() == {
"priority": None,
"due_date": None,
"description": "This is a test description",
"id": int,
"done": False
}
I've only ever unit tested with the built-in unittest library and I'm wondering if I should plan to use a pypi package like pytest or hypothesis for a library that I'm working on individually
I'm a big fan of pytest, @hollow basin - I find it easier to understand than unittest, cleaner, less verbose, and more flexible.
@split field I'll have to give it a try
hey, if any of you need to automate hardware, I do recommend this library -> https://github.com/google/openhtf
h
Related to #async-and-concurrency / <#async-and-concurrency message>:
I implemented a function like this:
async def check_solution_against_single_spec(
run_code: Callable[[Solution, str], Awaitable[ExecutionResult]],
spec: ProblemSpecification,
solution: Solution,
) -> SpecificationStatus:
tasks = [
asyncio.create_task(check_solution_against_single_test(run_code, test, solution))
for test in spec.tests
]
for coro in asyncio.as_completed(tasks):
r = await coro
if not r.is_successful():
for dangling_task in tasks:
dangling_task.cancel()
return r
return RightAnswer()
Basically, it tests a programming problem against a list of tests concurrently, and if one test comes back with an error (r = WrongAnswer | ErrorOccured | TimedOut), the other tests are cancelled.
How do I test the "the other tests are cancelled" part?
This is what I came up with:
@pytest.mark.asyncio
async def test_when_one_test_fails_other_do_not_get_executed():
spec = ProblemSpecification(
"it works",
[SolutionTest("input", "good")] * 10
)
solution = Solution(id="42", code="correct solution")
execution_count = 0
async def fake_runner(solution: Solution, input: str) -> ExecutionResult:
nonlocal execution_count
await asyncio.sleep(random.random() * 0.1)
execution_count += 1
return ExecutionSucceeded("bad")
await check_solution_against_single_spec(fake_runner, spec, solution)
assert execution_count == 1
but to my understanding, this is a flaky test -- it will randomly fail from time to time (and it can be achieved easily by changing * 0.1 to * 0.01). How can I properly test this function?
Of course, it's possible and maybe even acceptable that 1 or 2 stray tests are executed when they shouldn't have, maybe I should change it to
assert 1 <= execution_count <= 3
or something like that?
But, for example, this implementation shouldn't pass the test:
async def check_solution_against_single_spec(
run_code: Callable[[Solution, str], Awaitable[ExecutionResult]],
spec: ProblemSpecification,
solution: Solution,
) -> SpecificationStatus:
aws = [check_solution_against_single_test(run_code, test, solution)) for test in spec.tests]
for coro in asyncio.as_completed(aws):
r = await coro
if not r.is_successful():
return r
return RightAnswer()
because it executes all the tests in any case
@fiery arrow your function names lol test_when_one_test_fails_other_do_not_get_executed():
that's a normal name for a test ๐
some languages even allow spaces in names (like Kotlin), so that you can use normal sentences as names
@gentle zephyr this style of naming is used when you want to check a single property of a function/class in a test:
https://github.com/unclebob/fitnesse/blob/master/test/fitnesse/wiki/BaseWikiPageTest.java#L63
https://github.com/python-discord/bot/blob/master/tests/bot/test_decorators.py#L32
I think this is the right place to put it
I'm working on a thing with PIL
and I'm trying to put text above an image but idk how and I'll I can find is how to put text on an image
wait
this is the wrong thing
crap
๐
BDD test names are commonly test_that_...
Alright, a more... trivial question ๐
one of my modules has a class called TestCase that represents a test case of a programming problem. I'm importing it in my test. The issue is that pytest thinks that it's a test class, and it gives me a warning because it has an __init__. Any way to avoid it?
Well, I guess, I can export it by a different name
can someone help me with using pytest in #help-grapes ?
Hey guys, would anyone please help me with pytest?
Hello, I am new to this testing world and I am using Django's default test suite to test my views. I am trying to test posting of a file and I thought I knew how to do it but I am running into errors. Here is what I have.
def test_post_when_logged_in_with_permissions_form_error_1(self):
"""Test that the view returns a HTTP 400 when the user is logged in, has can_import_driver_data permissions, and
posts invalid file extension"""
url = reverse('main-import-driver-data')
permission = Permission.objects.get(codename='can_import_driver_data')
self.user.user_permissions.add(permission)
self.client.force_login(self.user)
# Create text file to post
with open('Test.txt', 'w') as file:
resp = self.client.post(url, {'driver_file_import': file})
self.client.logout()
print(resp)
self.assertEqual(resp.status_code, 400)
can someone who knows pytest help in #help-chili?
Hello everyone, I am required to set up automated test.
What is the best approach?
I've used Selenium for web scraping. As I looked around, it is actually used for automated testing. My question is, what else do I need to prepare automated software testing ie. We've web application in which I need to test log in page, and subsequent pages also. Example scenario for an online exam web application:
User will be,
-log in
-click on his exam
-will solve the exam
-log out
I myself did an automation doing all that stuff. However, there is nothing related to test. I mean I didn't use any kind of assertion etc. Can somebody guide me please?
is it okay for u to use JS
because I know just the tool for that
behold
https://www.cypress.io/
$npm install cypress
yeah, I suggest cypress too, I have used Selenium but cypress do more things for you out of the box. The good part of selenium is that you can code in Python
yeah
Hello guys, I have a weird problem in Selenium. I am trying to use
send.keys()to input email address. I have that address in variableself.email. The address is for example "aaa@bbb.com". When I useself.element.send_keys(self.email), it actually sends something like "aaaself.emailbbb.com". I am becaming quite desperate, because I weren't able to find any fix or even mention of this problem.
does it work if you don't use the variable? like sending text hardcoded directly?
nope, "@" is substituted by some previously used code even if i use send.keys('aaa@bbb.com'). It even happened when I tried to split the string and send letters one by one by for loop.
did you try calling self.element.clear() before send_keys?
yes, but with no effect
have you tried to change your keyboard layout so @ can be reached with the shift key? for example changing it to us qwerty.
or alternatively use something like Keys.ALT + Keys.CONTROL + "q" instead if @ is on your q key.
as far as i know, send_keys does not automatically press alt or ctrl. only shift.
are you working on aws? had encounter this kind of error before w aws.
https://stackoverflow.com/questions/30073603/python-selenium-send-key-cant-type-numbers-like-5-or-6
its with 5 or 6 though
Hey guys, I have an strange problem when using selenium, Im trying to set up a moderator bot for my youtube streams and Im required to send some messages through chat. I can't seem to find the right xpath to the youtube live chat, Im always getting the same error: "selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element" Ive been trying to find where to use .send_keys(), does anybody know a bit about this issue or how to solve it? Thanks
@mortal sluice unfortunately, that appears to violate youtube TOS so we cant help you
You are not allowed to ... access the Service using any automated means (such as robots, botnets or scrapers) except (a) in the case of public search engines, in accordance with YouTubeโs robots.txt file; or (b) with YouTubeโs prior written permission;
Hey guys I'm new here so I have a doubt
Suppose you have a tab open and you redirect to a new tab, you give the xpath of an element in the new tab, so does it try to locate the element in the new tab or the previous one??
Assume that Circle is defined using radius and Cylinder is defined using radius and height. Write a Circle class as base class and inherit the Cylinder class from it. Develop classes such that user can compute the area of Circle objects and volume of Cylinder objects. Area of Circle is pie radius*radius, while volume of Cylinder is pie(radius * radius)*height
HEY GUYS I GOT TO WRITE THIS PROGRAM IN PY
CAN U WELP???
hello
Sorry for coming just like this but i need help with pyautogui
This is happening. What am i doing wrong?
note i'm a total nub
If you can help ping me pls. I wil try solving this meanwhile
Nevermind, just downloaded Pillow
What are some cool automation libraries
As it turns out this is more of an issue not with how TK is installed but how pylint seems to be inconsistent across platforms on github actions. Tested with the file below on a clean repo. Any thoughts besides disabling pylint imports?
Results as follows:
python 2 windows (2.7.x) Linting Fail
- E: 7, 4: Unable to import 'tkinter' (import-error)
python 3 windows (3.8.x) Success Linting
python 3 linux (3.8.x) Linting Fail
- E: 7, 4: Unable to import 'tkinter' (import-error)
python 3 MacOs (3.8.x) Success Linting
Setup:
Github Actions Configuration
https://0bin.net/paste/sGbbX84r#vxpe73nMg6-YHd+Y+Z+hqCl8YRh9a8pmzgMK01PfWeF
tk_test.py
import sys, six
print(sys.version)
if six.PY2:
import Tkinter as tk
else:
import tkinter as tk
print(tk.TkVersion) # succeeds in all platforms to print version number
Turns out to be an issue with six/ pylint a simple try /except ImportError: it lints just fine.
How do I run chrome driver headless in Selenium?
Hi All - im writing some tests for one of my uni courses and I just need some advice
should I be writing
assert function(a) == False
or
assert not function(a)
they both work
but I'm just wondering from a best practice / style side
The first one reads better to me, might be purely down to personal preference though
Are there any blogs/books/whatever on how to write good test cases? I'm new to testing and have written some quick pytest functions but I feel like I might be missing the point and testing for 'incorrect' things
as in, I dont think my tests will ever really fail
I've been taught that you right the tests before you've written any code
so at some point they have to fail
write*
Same as Pete,. Your tests should fail before you write the 'implementation of the method' in test driven development. That said, once all is implemented, everything should pass until you introduce a bug refactoring the implementation. Unit test a happy and bad path to begin with, you'll likely never see them fail after implementation until someone else has to maintain your code.
what do you guys recommend for testing linux server/flask app
Hey is there a way to disable one of the onclick functions
<a id="cmdLogin" onclick="javascript:formSubissionHTMLInjection(); javascript:formSubissionManVsMachine(); javascript:if(loginUser(document.getElementById('frmLogin'))==false) return false;" tabindex="0" title="Login" href="javascript:__doPostBack('cmdLogin','')">Login</a>
i need to disable javascript:formSubissionManVsMachine()
how do you do python i dont know
?
Hi I'm using Selenium Web Driver in python to automate a test, so far though when I try to click a link it sends me to that page BUT when I try click another link on the new page it doesn't register. I heard the issue is because it still thinks I'm on the first page. I was just wondering how do you fix this? I have tried doing something like this so far. ```python
linkhelp = driver.find_element_by_link_text('Help')
linkhelp.click()
newURl = driver.window_handles[0]
driver.switch_to.window("https://www.littlewoodsireland.ie/help/en/online-help-system.page")
privacy = driver.find_elements_by_link_text("Privacy and Cookies")
privacy.click()
driver.close()
driver.quit()```
hey need help. Help in #help-bagel
Anyone has a tip on what kind of testing tool I could use best for Front- and Back-end testing?
Preferably a tool I can use with Python or an easy syntax
how do i check if a captcha is solved in selenium
@grave yoke its been a while using selenium for me, by the script example I am assuming when you click the link it opens a new window? First thing I would do is have a page wait for weekend to load before clicking, sometimes elements cannot be interacted with if they are not loaded, sometimes selenium can go a bit too fast for a web page.
Assert privacy was found before click.
List your windows in debug, assert you are going to the right window.
If the link you click is just a normal link that doesn't create a pop up you do not need the switch to window. Plus I would read the switch to window selenium doc. I think going title or is preferred (been awhile)
Ps assert the element you are interacting with on the new page isn't in an iframe, if yes tell selenium to step into the iframe first
Is anyone here good with setting up selenium on debian?
hey
Its pretty straight forward setting up selenium in a deb environment. I do recommend downloading the browser driver and give absolute path (if it is to be ran only in the environment)
Be sure to create the setup and teardown
So it knows to launch browser (if non headless) and close when done performing test
Guys I have a doubt
How do you enable media access in geckodriver
I tried add_argument('--use-fake-ui-for-media-stream')
I also tried set_capabilities('permission.microphone.default',1)
has anyone had any luck automating webui testing for svg elements? I'm having a nightmare trying to get anything to work >.<
Someone pls help
Anybody have some tips on identifying memory leaks
I have this one discord bot that is somehow taking wayyyy more memory than it needs
If anyone is familiar w beautiful soup, can you check #help-chocolate
If anyone is familiar with pytest, can I get some help in #help-candy ? Thanks!
With testing we can use temporary directories ( pytest has them, there's tempdir, etc ) so that any written files are cleaned up after... I'm wondering if there's ever a case for handling this cleanup yourself instead of using a tempdir though ?
if things fail during a test will there be some random sodifnwofeiwefoefijoeo dir located somewhere on the system? That's about all I can think of atm... Also - the option of not cleaning up the files afterwards could be more easily toggled on/off if this was handled by the user I think.
but I'm not sure - so interested to hear if there are clear examples or whether this just highlights I haven't used tempdir and such enough.
( if anyone responds to the above please ping me )
@cobalt ore tempfile from the standard library has automatic cleanup through context managers. If you're not familiar with context managers, think of it like wrapping the code in a try-finally and doing the cleanup in the finally block.
The only way that could fail is if the process is forcefully killed, either with os._kill or something else sending it the SIGKILL signal. In such case, you wouldn't be able to do anything better manually to clean things up.
I can only think of caching as a use case for keeping the temporary directory around. However, you'd need to be very careful to avoid an old cache causing a test (perhaps one that's been recently modified) to incorrectly pass. Seems like more trouble than it's worth.
https://paste.ofcode.org/8zPUqhAvZfMaABiywSdWQA
When friends personal devices connect to my AP or unknown devices I get a text with who or the MAC of the device
Like a door bell notification
@proper wind You seem to be in the wrong channel. How does your problem relate to automated testing?
Have you seen #โ๏ฝhow-to-get-help
So are you just discussing what you've made?
Yea
Sure it's automated but what's it got to do with software testing?
This channel is topical. Discussions should focus on a specific topic. In this case, the topic is automation of software testing. What you've shown does not seem related.
If you want to discuss your project consider #python-discussion
You are a developer for python?
I always wanted to do that but I donโt have any money
@kind meadow whereโs the projects channel
Have a lot of time to ask me questions but no time to answer mine
#Masterpythonrace hooora
Your first question is off topic. I've already given the #python-discussion channel for your second question. To be clear, there's no dedicated channel for projects anymore.
gm
@kind meadow thanks, context managers are fine. I was wondering if I was missing something, what you've said makes sense though, cheers
is there a better way to do this in unittest ? i can't directly test "v[2] = 0"
def f():
v1[2] = 0
self.assertRaises(TypeError, f())
Can just go directly through the dunder
thank you, it seems to works : self.assertRaises(TypeError, v1.__setitem__(2,0))
errr... does it ?
i'm confused...
self.assertRaises(TypeError, v1.setitem(1,0)) <- this test also pass but it shouldn't since it's not supposed to raise a TypeError here.
my test isn't called ...
pfffffffffft
i'm not using assertRaise correctly
with self.assertRaises(TypeError):
v1[1] = 0
now it works and really do the check
thank you for the help @torn mirage
help
resources for learning some testing?
How would you go about unit-testing code which requires a pyodbc connection to an MSSQL server?
edge_options = Options()
edge_options.set_capability('permission.default.microphone', 1)
capabilities = edge_options.to_capabilities()
driver = webdriver.Edge(executable_path=path_edge,capabilities=capabilities)```
I need my code to allow permissions
Can someone help
So - I have been trying to track down this issue for awhile now and I can't seem to figure out what the heck is going on.
Using selenium, I keep getting the following error:
selenium.common.exceptions.SessionNotCreatedException: Message: session not created from timeout: Timed out receiving message from renderer: 600.000
The SO posts that I've read say that chrome and chromedriver are not up-to-date, but I have confirmed multiple times that they are the correct married couple.
anyone has experience with playwright?
You mods deleting my lines faster than I can.... So diligent.
can someone quickly explain this?
hi, Does anyone have an experience of implementing GAN?
I have an error of 'Error when checking input: expected conv2d_1_input to have shape (48, 48, 1) but got array with shape (32, 32, 1)' when generator produce the fake images as 32 by 32.
Hello everyone.. what is the best way to write a python code which verifies if tab completion is working fine in a router
I assume it's web based UI, you could do something with selenium
selenium webdriver is your tool to go here
Someone help
hey guys, i'm using the unittest module for a large project i'm working on at work. I dont want to use the discovery feature as I want to manually point to which folders to pull tests for. Tests are organised in a test folder (it's large) and i think i've defined all my tests accordingly and want to use a testrunner. the issue? I'm using the test runnner setup as can be seen here: https://www.internalpointers.com/post/run-painless-test-suites-python-unittest but when i run my tests, (even using the loader.loadTestsFromModule() function) it 'finds' 0 tests so it gives
`Result: <unittest.runner.TextTestResult run=0 errors=0 failures=0>
Ran 0 tests in 0.000s
OK
`
hey guys, need help with selenium automation with python
having trouble launching the webdriver
I have a question that's not entirely python related.
How would you test an app that's supposed to send list of messages to the user.
Each message is a string and it contains some details about a problem on the PC.
For example "HardDrive C is full". How could I test the result so it's refactor safe?
@late glade you could possibly look at mock testing or mock requests
can anyone help me pls
https://stackoverflow.com/questions/65240527/pytestcollectionwarning-cannot-collect-test-class-test-001-login-because-it-h
is there any way for pytest to only carry out tests for files that have changes since the last test that was run? Like a Makefile or whatever
Halp
wit
StaleElementReferenceException: The element reference of <span> is stale; either the element is no longer attached to the DOM, it is not in the current frame context, or the document has been refreshed
I m coding web scraper with selenium and i got this error for this code
counter = 0
while(counter<len(urls)):
time.sleep(1)
browser.get(urls[counter]+"/#ht-ft;2")
oranlar= browser.find_elements_by_tag_name("span")
j=0
for i in range(len(oranlar)):
if(oranlar[i].get_attribute("class") == "avg nowrp"):
print(oranlar[i].text)
counter+=1
````
how can i fix it?
Because you are refreshing it
you are calling browser.get(blah, blah) in a loop form
meaning that you are changing the link each time
also, browser is not defined
Hey @zenith ridge!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
โข If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
โข If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
hi everyone, can you give me an advice , i have a presentation to get my diploma of web developer. i present my trainingship and some test but i realise is not so easy to explain ! is there a special way for these type of presentation ?
im not sure im in the good channels but i try thanks ๐
Hello. Having a lot of trouble with stale elements in selenium.
like, i make a list from "find elements using xpath", and the list returns just fine
but the next line, i try to to iterate it in a loop, and the first result already returns stale error?
of course, nothing changes on the screen...
all the online answers say i should use implicit wait until the item is no longer stale, but the item is already stale... waiting will not change that
@lofty ocean has you install it ?
yea
see the first line in terminal...
I'm getting this same error when I used prettytable module
now it is coming for bs4 too
If this is not related to automated testing, please use a fitting topical channel or a help channel.
ok sorry
@pale citrus Did you figure it out? The only issue I can think of is that your tests functions don't follow the expected naming convention (they must start with test)
If you're not using that prefix then you can change the value of TestLoader.testMethodPrefix
!e
numbers = [2, 3 , 5 , 6, 2 ,4 , 3, 5, 6]
duplicates = []
def delete_dup(self):
for duplicate in self:
if duplicate not in duplicates:
duplicates.append(duplicate)
return duplicates
dupli = delete_dup(numbers)
print(dupli)
You are not allowed to use that command here. Please use the #bot-commands channel instead.
I want to make a function taht increases "i" by +1, till (f * i+1)/e = "whole number". It needs to check for if the number has decimals, if it has decimals "i" has to be increased by +1, till the equation equals a whole number without decimals.
ex.
(5512 * 1+1)/35 = 157.51... <---- bad therefore i = i + 1
(5512*2+1)/35 = 315 <--- done
Is this the right channel to ask or no?
It doesn't seem like the question has anything to do with automating software testing, no.
@split field where then should I post the question?
I don't think there's a particular topical channel where that fits, so either a help channel (see #โ๏ฝhow-to-get-help ) or #python-discussion
hey folks, i think i have what i think should be a pretty basic question... i want to test a function that requests a URL where a zip file is downloaded and saved to a directory. I have the request mocked, but i'm not sure how i can prevent the side effect of saving the file to the directory which is hard-coded in the function. I realize i'm probably breaking SRP here and should either stub out a function with a path argument or just add a path argument to my current function, but i want to make sure i'm understanding testing architecture and pytest's capabilities. Is there any way to tell my function to save it to a tmp_dir instead of the path coded in the function?
def download_zip_from_url(url, chunk_size=128):
r = requests.get(url, stream=True)
filename = Path(url).name
with open("data/geodata/" + filename, "wb") as f:
for chunk in r.iter_content(chunk_size=chunk_size):
f.write(chunk)
def test_download_zip_from_url(requests_mock, tmp_path):
requests_mock.get(
"https://testurl.org/test.zip",
stream=True,
)
maps.download_zip_from_url(
"https://testurl.org/test.zip",
)
Without changing the function your testing, the only way I see to accomplish that is by mocking the open builtin, which I believe is possible.
Sorry, not mocking it. You'd have to patch it.
When patched open will do whatever you want, like using the tempfile library to open a temporary file instead.
But your intuition is right. You should add a path argument or at least define a constant for the base path which you can patch while testing.
ok, thanks so much! I've heard about patching but it's still a little bit of a head spinner, good to know of a use case even if it's not the ideal solution... so is patching a lazy-but-sometimes-worth it hack, or should i avoid it whenever possible?
That's a more loaded question than you might think
It's contentious I'd say
Or testing methodologies in general are
Some try to use it sparingly and others patch a lot
It boils down to how tightly you want to couple your tests to your implementation
It makes your tests more thorough or precise at the cost of tight coupling.
Patching can also get really ugly and complicated
makes sense!
Some good uses cases are to mock database connections
is that cuz it's more difficult to dig under the hood so to speak?
Usually a database connection is handled by a third-party library that already has its own tests from its authors - it's code you're not responsible for.
So you mock it and just make sure that your program is correctly interacting with the database
There usually isn't an easy way for you to assert at any deeper level that the database is doing the right thing. And again, it's already tested. So you can assume if you call "db.foo()" with argument "x", it will do the right thing.
gotcha
I suppose an alternative would be to set up a real test database and perform queries to make assertions that a column got updated to a new value or whatever.
Django's test runner sets up a db like that I believe.
anyone who knows what it means by "object of 'Response' has no len()" length of what do i need exactly
is it the amount of links that im scraping that i need to specify?
You are getting response.content. But it return response body as bytes (docs). But you should pass str to BeautifulSoup constructor (docs). So you need to use the response.text instead of getting content.
use source_page.text insted
Ite returning None Thats why
can u show has your code
?
we might help
heya i was trying to bind the variable name in single quotes by using the function xpath() but aint working the actual syntax was like this driver.find_element_by_xpath(//span[text()='Electronics']
flipkart.com doesn't allow automated access in its terms of service, so we can't help you with that (#rules -> rule 5). Besides, please keep the channels on topic. This channel is for discussing automated testing.
(unless you're hired to do automated testing by flipkart, in which case you can probably ask the question to your colleagues)
that is not the topic actually i just wanted to bind the variable it 's not like i am doing automation!
Hey @mint merlin! Since automation isnโt allowed by flipkart,com, we canโt help you with your project, no matter if it is about the automation part or not, see our 5th rule.
oh ok then sorry for the trouble
No worries
is it possible to write a python script that downloads and sets new desktop wallpapers for your pc every day or week without you worrying about it?
Hey everyone, I'm trying to reproduce a burp suite request as a python script. in burp suite i get the correct json response with the data i need. my python script sadly returns a totaly diffrent response.
The burp suite request: https://paste.pythondiscord.com/efakowidiw.http
The burp suite response: https://paste.pythondiscord.com/naxupoqesi.http
my python script: https://paste.pythondiscord.com/udovamodaq.pl
the printed response.text: https://paste.pythondiscord.com/gakizasuce.xml
response.json() returns an error.
Can someone tell me why the responses are diffrent?
Edited because i updated the code
anyone who knows how to fix the "Getting default adapter failed" tried on google, loats have had it, can seem to fix it tho
im simply opening a website, literally nothing else, and it crashes down after 2 seconds (selenium
try using driver = webdriver.Chrome(ChromeDriverManager().install())
!e
print("C:\Program files")
@fiery arrow :white_check_mark: Your eval job has completed with return code 0.
C:\Program files
Huh, backslashes work ๐ค
Either way, please use this channel only for questions about automated testing. If you have a general question, please claim a help channel (see #โ๏ฝhow-to-get-help )
Hi, this channel is for discussing automated testing -- unit testing, integration testing etc. If you have a general question, you need to claim a help channel, see #โ๏ฝhow-to-get-help
It is deprecated behaviour, but the prebuilt distributions of python don't raise the deprecation warning in __main__ for some reason
im using selenium and i have a problem with it, if someone is able to help me at help-zinc i would be very grateful
what test framworks are people using ?
Hey @clever lake!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
Hey @clever lake!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
@snow brook While I am quite lousy at using dedicated test frameworks, I do find the debugging, and coverage features of PyCharm absolutely stellar.
Any project file can be run in coverage mode, and when the execution halts, the reporting is nicely detailed and shows percentages of lines covered for all source files.
... My day job is programming flight software for ESA space probes so I have a weird sense of testing. Python just doesn't support sufficient level of paranoia to ever achieve sensible "certainty" that stuff really is reliable. So I rarely commit to testing python seriously since it's moot anyway.
I use pytest for normal unit tests, and I recently started playing around with hypothesis, which is a property testing framework.
any one here a experienced ethical hacker?
That question is off topic for this channel, but would fit in #cybersecurity
why it is not allowed to use a module name inside a package that starts with a number/digit?
What does time.sleep do?
time.sleep()
is basically just a wait
if you are going to use it, remember to write import time
time.sleep(how long u want to wait)
How do you upload a file to a website using selenium when there is no input form, the type is a button and I'm trying to upload a mp3
2020-12-21 17:15:25.246427: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cudart64_100.dll
D:/Porject001/Test02/Sample_Test05.py:58: UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.
plt.show()
does any one got decent pytest course in reasonable price?
I haven't needed any course so far, the documentation is pretty good. https://docs.pytest.org/en/stable/contents.html
Why do you think you need a dedicated course to use pytest?
My bread giver told me that if I know a bit of python and I am tester I should move asap into automated testing
I will get my first test to write soon after xmas
You don't need any special settings or courses to start with testing. You can just take a project that you have and write automated tests for it.
And if you're not sure how to test something, you can ask here.
anyone knows best way to show the picture png as canvas streaming for live streaming?
which python module is good to work with png streaming?
yes
okay ๐
what is the best way to click a link with silenium
driver.find_element_by_xpath(some_xpath).click()
thanks
Um can someone please help me
I want to make the classic bee movie script bot
but it cant find the text file for some reason
im including sceensnippets
pl0x help
save it as beemovie.txt
on textedit ? or within pycharm ?
It's the same thing
import os
print(os.getcwd())
What is your output when you run this?
:)
but seriously, thank you.
Think I posted this in the wrong channel and this channel would be better:
I have a tests directory like:
tests
tests/tool1
tests/tool1/data (testing code on some dummy data)
tests/tool2
tests/tool2/data
and tests within the tool1 and tool2 folders. If I want to run all of my code from tests how can I do that? As my tests are failing due to not being able to find the /data folder I've referenced in my test files under the tool1 and tool2 folders
if I cd into the tests folder and run python -m unittest discover I get import failures on my test files - but the PyCharm linter isn't giving any errors with the current way I import
Is there a way to get supporting files via selenium? Like say the page sends a jpeg or json file. Is there a way to retrieve that data using selenium?
@rapid grove you could just use requests.get
im not so familiar with selenium, but what you should do is get the url where the image comes from
then you can download it with open('image.jpg','w').write(requests.get(link).content)
Thanks!
idk where this is supposed to go but does anybody know anything about generating music patterns
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
import os,time,playsound
import speech_recognition as sr
from gtts import gTTS
def speak(text):
tts=gTTS(text=text,lang="en")
filename="voice.mp3"
tts.save(filename)
playsound.playsound(filename)
def get_audio():
r=sr.Recognizer()
with sr.Microphone as source:
audio= r.listen(source)
said=""
try:
said=r.recognize_google(audio)
except Exception as e:
print("eception"+str(e))
return said
speak("this works")
get_audio()
Traceback (most recent call last):
File "C:/Users/USER/PycharmProjects/untitled5/reddit.py", line 22, in <module>
get_audio()
File "C:/Users/USER/PycharmProjects/untitled5/reddit.py", line 12, in get_audio
with sr.Microphone as source:
AttributeError: enter
anyone know why it traggers this error
with sr.Microphone as source: should probably be with sr.Microphone() as source:
Thanks
what the error is telling you is that the object you supplied to with doesn't support the context-manager protocol
missing () is a wild guess about why, since I don't know that library, but if that's not it it's something else wrong with what you're providing there.
when I'm using pytest the test work if it is run individually (per function test) but if it is run as class it will fail. What does it mean?
Hello anyone have experience with selenium and proxies?
How do i actually generate reports in selenium-python. Is it just terminal or html reports? What additional library do i have to use, to get reports ? Do any one have a sample code ?
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//input[@name="username"]"} how do i fix this?
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
How can I make a function run for a specific time in a "while True:"?
don't use while True:, and instead use something like:
import time
start_time = time.time()
while time.time() < start_time + 30:
# Keep looping, but stop after 30 seconds
thank you
is there any alternative to selenium for automating js webpages?
you can use Request module to do that but you will be limited
This is my first time writing a unit test using pytest instead of stdlib unittest. Does this seem correct? https://paste.pythondiscord.com/wawowamige.py
I don't really see the point of fixtures.
what you're using fixture for there can be accomplished with a global object
fixtures are a form of dependency injection, so the examples of using a database connection or a file handle are to save just a few lines of code to handle the instantiation etc.
Fixtures frequently do something, too. If all you're doing is returning some constant data, then the fixture isn't buying you much over a global. The one advantage is that the fixture function is called once per test, so one test can't mutate the data and leave it in a bad state for another test. The real advantage comes from fixtures that call other functions or set up preconditions or set up monkeypatches or mocks or insert dummy data into a database, etc.
Think of fixtures in pytest as being analogous to unittest's setUp methods.
In pytest, you'd do py def test_thing(a, b, c): whereas in unittest you'd do ```py
class SomeTest:
def setUp(self):
self.a = a()
self.b = b()
self.c = c()
def test_thing(self):
...
Except that the fixtures can also handle their own tearDown as well, so that's not a perfect analogy; they're more powerful than that would imply.
@hollow basin ^
So I don't necessarily need pytest for this?
I don't think I understand the question
There's nothing that you ever need pytest for, it's just a less verbose, more flexible, easier to use, more Pythonic alternative to unittest
like, in the example I gave above, pytest is doing in 1 line what unittest takes 7 to do.
typical examples of things that you'd use a fixture for are, for instance, opening a connection to a database, inserting some canned data into some table, setting up some environment variables, replacing some global with a mock, etc. And then undoing whatever you did at the end of the test function run.
which are all things that in the unittest world you'd do in setUp() and possibly tearDown().
and pytest does it with a declarative syntax, so that instead of copy-pasting code between the setUp() methods of several different test classes that need similar things, you only need to declare which types of setup you need.
Am I making any sense to you?
maybe looking at some of the pytest builtin fixtures will make it clearer:
A test that depends on caplog will capture all logging calls made by the code under test so that assertions can be made about what was logged. At the end of the test normal logging is restored.
capsys works similarly, but for what is written to sys.stdout and sys.stderr instead.
recwarn works similarly, but for calls to warnings.warn() instead of logging.
monkeypatch allows performing monkeypatches that are automatically reverted at the end of the test.
tmpdir creates a temporary directory and passes the path to it to the test function. At the end of the test, the directory is removed.
Most fixtures don't merely return static data, they perform some sort of setup, and often some sort of teardown as well.
so if fixtures didn't exist, instead of py def test_something(capsys, caplog, recwarn, tmpdir): assert 1 == 1 you'd wind up doing something like ```py
def test_something():
with (
capture_logs() as caplog,
capture_sys_streams() as capsys,
record_warnings() as recwarn,
create_tmpdir() as tmpdir
):
assert 1 == 1
I feel like I'm overexplaining this, so I'm gonna shut up unless you tell me to keep going ๐
I think so. The one time I went on a unit testing spree, I did everything with unittest.TestCase and didn't wonder if there was a better way beyond thinking it was a weird way to use classes.
yeah - unittest is borrowed nearly verbatim from the Java junit library, which is why a bunch of the names and patterns are much more Java-y than Python-y
pytest fixtures in a nutshell are a way to perform any necessary setup steps before running the code under test, and/or teardown steps after running the code under test, while allowing those steps to be declared and reused across tests.
I'm learning 
For the purposes of demonstrating my programming abilities, I'm worried that having two globals and one assertion is going to be underwhelming.
fair enough. without knowing anything about what your code does, I'd add a test that covers the mode="lenient" case, and the case where mode="something invalid". Are there any interesting edge cases in the code? Are there other types of invalid input? Are there cases that it took you a few tries to get right, that you want to make sure you don't break in the future?
can I ask for help about this module
https://github.com/fundakol/selenium_datatable
I'm trying to understand how to give the driver to the UsersTable class
Testing the lenient mode would be a huge pain
A professional - or at least someone who's trying to look good - would probably do it anyway ๐
from the software engineering point of view, it's pretty normal to have 2x or 3x as many lines of test code as actual non-test code.
pytest is actually beautiful
the only thing I'd like is the ability to use fixtures in test parametrisation out of the box
but I guess you can't have everything
Hello folks! I'm trying to do TDD python development but struggling to find test frameworks that run automatically in the background of my IDE without needing to interact with them (ie don't want to have to push "run tests" button). Something similar to NCrunch in Visual Studio. Google fu is failing me here, finding plenty of frameworks that need you to click a run button but what I'm looking for is on code change or at least on file save. Does this exist? Anyone know of a good framework and what IDE it plugs into?
If you're using PyCharm, you might be able to set something up using File Watchers: https://www.jetbrains.com/help/pycharm/settings-tools-file-watchers.html
Or perhaps a pre-commit hook if you're using git for your VCS
This is a pretty handy python package if you go with using pre-commit hooks: https://pre-commit.com/
I'll give these a look, thanks for the info. I've been using vscode but not against switching to PyCharm. I'll look into that, it looks promising, thanks!
FWIW, I would guess that VS code has similar functionality (or at least a plugin for it).
Yeah had the same thought and found a plug in for file watching
How would one approach testing that โwhen a connection is lost, the API should stop streamingโ? I want to create a test for this issue, https://github.com/sysid/sse-starlette/issues/7 --- I checked starletteโs tests, then looked at their testclient module. I see there is a WebSocketSession.Close (but Iโm thinking this is the server closing the connection) whereas I need the client to be the one closing the connection. TestClient seems to not have a โcloseโ method or anything similar. Any pointers?
I am mistaken! According to docs https://www.starlette.io/testclient/,
.close(code=1000)- Perform a client-side close of the websocket connection.
I'm using the "Text Explorer" extension. It allows you to automatically run tests (either from one file or all of them) on save.
Works with pytest, should work with unittest as well
this approach means less button presses, but if you're using hypothesis, it's going to constantly eat your CPU
https://i.stack.imgur.com/KSX4f.png
Can Windows permission seeking messages(See the image) not be automated?
I believe those are shown in an environment that's restricted
Hello guys. I have a question. Is it possible to add a path and work with two work directories like in matlab?
Fantastic! I set this up yesterday and worked like a dream. I also setup Coverage Gutters extension to get the full experience with covered and uncovered lines showing up in real time. Thanks!
๐
I'm currently writing a unittest.TestCase implementation and I was wondering if there's a way to make my test_requires_dict method more DRY. Very new to unit testing. Here's the test class:
class TestDynamicObject(unittest.TestCase):
def test_requires_arg(self):
""" Should raise TypeError when not passed arg """
with self.assertRaises(TypeError):
DynamicObject()
def test_requires_dict(self):
""" Should raise TypeError when not passed dict arg """
""" Test with string """
with self.assertRaises(TypeError):
DynamicObject('string_arg')
""" Test with list """
with self.assertRaises(TypeError):
DynamicObject(['list', 'object'])
""" Test with integer """
with self.assertRaises(TypeError):
DynamicObject(1)
""" Test with float """
with self.assertRaises(TypeError):
DynamicObject(1.2)
Should I put all my test args in a parent list and then iterate through them within a single with self.assertRaises context or should they be separate like they are now?
I personally prefer having them in separate tests so that each component (individual test) focuses on as small of a bit of functionality as possible.
Regarding selenium, how can multiple instances of the Selenium driver run at the same time opening different URLs? :)
Hello
People
I want to learn all kind of broswer and apps automation, what all to learn with selenium
Also web scraping, for that beautiful soup is best ?
For automated testing using the browser, https://seleniumbase.com is a lot easier to use than just selenium
I was using selenium to open a web page, and by xpath find a button and I would get it's href value. How can I efficiently do the same thing through requests instead of selenium?
requests would get the page, and then you could use beautiful soup to find the href value
page = requests.get('https://google.com')
html = html.fromstring(page.text)
soup = BeautifulSoup(html, features="lxml")
for a in soup.find_all('a', href=True):
print(a)
print("Found the URL:", a['href'])
@floral ember soup = BeautifulSoup(html, features="lxml") ends up throwing me a TypeError: expected string or bytes-like object, any idea?
You should be able to pass the page.text itself to beautifulsoup
with a
page = requests.get('https://google.com')
html = html.fromstring(page.text)
for a in html.find_all('a', href=True):
print(a)
print("Found the URL:", a['href'])
@split field to bring relevant discussion over here:
https://github.com/swfarnsworth/bratlib/blob/master/bratlib/calculators/entity_agreement.py#L96
This module has a measure_ann_file function that counts things based on a certain heuristic, so the unit tests for it ensure that it's applying that heuristic correctly. But then there's the measure_dataset function which is just using functools.reduce to merge an arbitrary number of calls to the first function. There's a lot less that can be messed up with the second function. If I wrote a test for it, would that be integration testing?
integration testing refers to a test that goes across multiple units. In a unit test, you define what code you're testing, and break dependencies on other components that are not being tested (using mocks or dependency injecting fakes, etc). In an integration test, you allow tests to cross component boundaries. Unit tests validate that a particular component works when used properly. Integration tests validate that one of your components uses others properly.
I'm not sure if that answers your question, though ๐
Hmm, let me make my question more specific to what I might do with the answer you give me:
reduce(
lambda x, y: x.add(y, fill_value=0),
(measure_ann_file(gold, system, mode=mode)
for gold, system in zip_datasets(gold_dataset, system_dataset))
)
functools.reducedoes not need to be testedDataFrame.adddoesn't need to be testedmeasure_ann_fileis tested by another testzip_datasetsis tested by another test
But I still want to have a way of finding out if this function were somehow broken, or if a change made in another component didn't necessarily break that component but did break this function.
But what do I really test? Just that it returns a dataframe? (You don't necessarily need to know the exact answer.)
I usually consider the "unit test" versus "integration test" line to be drawn based on whether it's testing the code within my module (unit test) or testing how my module interacts with its environment (integration test). So, if measure_ann_file actually opens and reads a file from disk, that's integration test territory. If it's using hardcoded data that has been injected or mocked or faked, it's unit test territory.
As for what to test - I'd say inject known values, and validate that you get the expected outputs, if that's not impractical to do. Not just that you get a dataframe, but that the dataframe's contents are what you expect them to be.
For tests that open & read files from disk, would it still be an integration test if you use the tempfile module (or a fixture) to create data just for the test itself?
Asking because, I almost always use tempfile when writing tests for functions that open/read/write files.
That means I'll need to monkeypatch measure_ann_file to generate a specific set of dataframes, regardless of what is passed to it
hmmmmmmmmmmmm
I'd say yes, personally, but the line is blurry. Unit tests should be very fast - 1ms as an upper bound on how long it should take to run one, I'd say - and things that interact with the filesystem, even to read a temporary file, are not fast.
^ @evilbiologist if that wasn't clear
That makes sense/seems reasonable. As a follow up re fast tests, do you have any experience with writing fast PySpark tests? I work on/wrote a service at work that uses pyspark and running the entire test suite is pretty slow. I think ~8 minutes for a couple hundred or so tests.
Even individual tests are a bit slow, because one has to instantiate a spark context.
nope, never used pyspark, or spark at all. But for the record, I consider a test suite that takes 2 seconds to run 1000 unit tests to be slow, heh
don't look at the test suite for my nlp library that I wrote over a year ago, then.........................
Tests are better than no tests, regardless - but I really like being able to rerun the full test suite whenever I make a change to see if I broke something, and if the test suite takes more than a few seconds to run that's really painful to do. If the test suite breaks out unit tests from integration tests, I'll usually only run the unit tests as I'm iterating, and save integration tests for later, just because I want something fast.
https://www.testim.io/blog/test-automation-pyramid-a-simple-strategy-for-your-tests/ seems like a good foundational read on unit tests vs integration tests and mocking versus accessing external resources
if my pytest test has monkeypatch as the name of a parameter, does that have unstated magic behavior?
It would if you have a fixture named monkeypatch, i think
there's a builtin fixture named monkeypatch
it's an instance of a class that has methods for patching and unpactching stuff, and that automatically undoes the patches when the function ends.
so the only "unstated" behavior, I think, is that any patches that you make are automatically reversed when the test function finishes.
By "unstated magic behavior" I guess I'm referring to the meta-programming phenomenon we were talking about before.
right - well, the same as any other fixture. The monkeypatch fixture does some setup (creating an instance of a class with some specific teardown behavior), then that instance is passed into your test function (with instance methods that let you apply and unapply various monkeypatches), and then after your test ends that fixture has some teardown that happens (any patches that you haven't already unapplied are unapplied)
there's nothing magic about it above and beyond the "normal" fixture magic, where the name of the test parameter is introspected, and pytest decides to create and pass you an instance of the monkeypatch fixture because it sees monkeypatch in your parameter list.
Something like this
page = requests.get('https://google.com')
soup = BeautifulSoup(page.text, 'html.parser')
for a in soup.find_all('a', href=True):
print(a)
print("Found the URL:", a['href'])
That makes sense/seems reasonable. As a follow up re fast tests, do you have any experience with writing fast PySpark tests? I work on/wrote a service at work that uses pyspark and running the entire test suite is pretty slow. I think ~8 minutes for a couple hundred or so tests.
@vernal spear PySpark is unfortunately slow
Iโd suggest isolating as much as possible
hi all i really need help with selenium
i would like to get tha highlited div
this is the xpath that i use but it says that is not a valid xpath
//*[@id="pane-side"]/div[1]/div/div/div[24] this is the xpath of that specific div, the thing is dont want the specific one, because the site is dynamic and the path would change
the only thing that remains is the style="transform: translateY(72px)" that means is the first one to appear
im trying to get it with tah xpath but it doesnt work
if i want to determine what happens post form submission with selenium how could i do that
like some callback
hello guys
im having some errors at web scraping
i just try to use the GET method in a page
but it returns me an error
that wouldnt have to appear because the website works perfectly
any ideas?
@knotty vault, that site seem to require User-Agent. Set it to something to fix the issue.
page = requests.get(url, headers={'User-Agent': 'foobar'})
Does anyone one else think pytest fixtures are meh?
Maybe it's bc my class that I'm testing but like it seems that if you need to change the input a lot they're not that great
Is it just me; or for pyautogui; the locateCenterOnScreen just replies none to it. Is it just a mac issue; or what exactly is the case. Be sure to dm me if you need ( I will respond tmrw as i am going to bed)
hello @proper wind
am going headless
and am using this website to test if it's detectable, and its detecting it via plugins length and the hairline feature
any recommendation
?
am using python selenium
Thanks in advanced
hey does simebody know how to disable console log?
where do i start my testing journey
Hey guys, what is the best framework to use in Python? I've been just using debugger, and print statements in my IDE for the time being but need to branch out
!rule 5 @half hemlock
5. Do not provide or request help on projects that may break laws, breach terms of services, be considered malicious or inappropriate. Do not help with ongoing exams. Do not provide or request solutions for graded assignments, although general guidance is okay.
For testing? Check out pytest.
hey, Is there a way in which one can use mechanicalsoup and selenium together?. Basically my issue is that I'm using mechanicalsoup but now there's this particular form (a search form) who's input field doesn't have a name attribute and it needs to be filled so that the form can submit... ..any suggestions
i did it using selenium_stealth
Hey, anyone have used selenium and got IE mode working with Edge?
I only managed to got either Edge in default/normal mode or actual IE to open. Haven't found anyone actually got it working, people just seem to link to this Microsoft blogpost but never heard anyone say they managed to get it to work.
Hello
what should i test in CRUD application that consist of only function do interact with SQLite3
Thanks
Hi guys, are there any web sites contained examples I can do to improve my python skill? Just beginner here
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Ooooh
They have easy examples or problems?
I'm just a beginner.
I'll check it out. Thank you so much.
im new into testing
like 10minutes
import unittest
from math import gcd
from main import (
basic_euclidean_algorithm,
optimized_euclidean_algorithm,
recursive_euclidean_algorithm
)
class TestEuclideanAlgorithm(unittest.TestCase):
def test_basic_euclidean_algorithm(self):
for i in range(0, 20):
for j in range(0, 20):
self.assertEqual(basic_euclidean_algorithm(
i, j), gcd(i, j))
if __name__ == "__main__":
unittest.main()
i would like to test mine euclidean alg
how it works
i would like to use it for running a milion times
and is it working?
couse it stops on i,j == 1
In case it can help someone, yes one can combine mechanicalsoup and selenium in a hacky way. I was able to do this by passing the site's cookie from mechanicalsoup to selenium and once i submitted the form the resulting redirect url i passed it back to mechanicalsoup .....
I want to make a python file that can copy itself to system startup, but if it is in the startup folder it should not execute the part of copying itself to the startup else it will duplicate, how to do that, also i want to then hide that file using attrib +h +r +s +a file.name command of cmd
i dont know where to send it so i sent it here
i converted my program into exe but it not running ,why ?.
reduce(
lambda x, y: x.add(y, fill_value=0),
(measure_ann_file(gold, system, mode=mode)
for gold, system in zip_datasets(gold_dataset, system_dataset))
)
I need to monkey-patch measure_ann_file so that the whole generator expression returns fixed objects, but since it's already in a generator expression, patching it with another generator just causes that generator to get popped out rather than the type it's meant to return.
Silly me: measure_ann_file is a function, so I needed to mock n calls rather than have a generator.
can anyone point me to a direction how to test a single function that asks for multiple inputs using input()?
There's 2 approaches you could take: monkeypatch sys.stdin to return hardcoded data when input calls it, or monkeypatch input to be a mock or dummy function that returns hardcoded data
This is very helpful thank you
when would unit tests succeed but integration tests fail?
i've never run into a situation like that, so integration tests have always felt useless
Like if one unit doesn't properly call or initialise some other unit. Integration tests look at how one unit uses another unit. Unit tests don't test how other things use them, which is the gap that integration tests fill.
Well I suppose you could write a test for unit that depends on the other to mock and assert the calls of the other unit, but I'm not sure if that should still be considered a "unit" test.
It's sort of vague what a "unit" even is anyway
@kind meadow that's what i usually end up doing. instead of making an integration test where unit A passes 3 to unit B and I assert that the interaction worked, I make 2 unit tests. One where I assert what A returns is 3, and one where I make a mock returning 3 and assert that B works with that
What I dislike about that approach is that the tests tightly couple units to each other
Which makes the tests more of a burden when code has to change down the line
But it's a trade-off
I think as I get more and more experience, I make "units" more broad. for example at very start, I would always doMock(spec=str) when passing strs to these units as part of testing (to make it so I wasn't testing two "unit"s)
but now that seems a bit overboard...
@kind meadow i'm thinking about an objective way I could define a unit, what something outside of the environment? so IO, random numbers, etc. would always be separate units that would be mocked, whereas other units might be better grouped under an integration test instead of doing mocking for the sake of mocking
I've not found a good definition
I just have some vague idea of what should be a unit from experience and go by gut feeling
I've seen plenty of conflicting definitions
Like I've seen some say a unit is the smallest testable public part of an interface
But I think there's value in testing private helper functions too if they're significant enough
i installed pygame module when initalize the pygame.init then i an error says module has no variable.
how to fix it ?.
anyone bumped into this issue? I get 0 autocompletion for webdriver
That's an issue with your IDE, so you should ask in #tools-and-devops
Your question isn't related to testing. Claim a help channel #โ๏ฝhow-to-get-help
its pygame.init()
okay ,sry!
How can I use selenium's find_elements_by_xpath based on text, when it may or may not have a word?
Example: it can be either #1 here or #1 is here. I want both to be part of the same list, since that func return a list. ATM I have driver.find_elements_by_xpath("//*[contains(text(), '#1 here')]") but that would only find the first case, not the ones with an is. How could I do that?
Im not sure if this goes here but
im new to python
and im working on a project with selenium to post some tickets to see if theyre open
we usually have to check them at the end of every year
its like 5000
so im attempting to automate them
can you render any assistance
# selenium
from openpyxl import load_workbook
import unittest
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.keys import Keys
# pandas data science
import pandas as pd
report = pd.read_excel(r'report.xlsx')
print(report)
# Excel Import
# webdriver
driver = webdriver.Chrome()
# sabre redirect
driver.get("https://accounts.havail.sabre.com/login/srw?goto=https%3A%2F%2Fsrw.sabre.com%2Flogin%2F%3Fts%3D439070&force=true")
# login info
driver.find_element_by_id('username').send_keys('1994')
driver.find_element_by_id('password').send_keys('_______-')
driver.find_element_by_id('pcc').send_keys('_________')
driver.find_element_by_id('submitButton').click()
# wait for page load
WebDriverWait(driver, 25).until(
EC.presence_of_element_located((By.ID, 'cmdln')))
# enter data
# data values
driver.find_element_by_id('cmdln').send_keys(report)
driver.find_element_by_id('cmdln').send_keys(Keys.ENTER)
# read excel data
hello I need help
with requests.session() as s:
url = "URL"
r = s.get(url, headers=headers)
print(r.content)
uhh so I cant get the html
even if I added the headers, does anyone have a solution?
you need the beautifulsoup
you can try:
request = requests.get(url)
soup = BeautifulSoup(request.text,'html.parser')
header = soup.header
print header
if you type in "requests.get(url)" you will see that your object is: <Response [200]>
That is a good response. If it's bad, I don't think you can work with it
But you can't read the requests object directly. You need BeautifulSoup to parse the HTML
@proper wind forgot to tag you
Also FYI: AttributeError: 'Response' object has no attribute 'session'
and from bs4 import BeautifulSoup is how to import BeautifulSoup (assuming you already did the pip install)
Here is the resource I used to get started with web scraping (using Requests & BeautifulSoup): https://automatetheboringstuff.com/2e/chapter12/
A colleague of mine and me having a "best practice" debatte about how to write tests. We are using pytest as the testing framework. We both agree that a test has essentially three components: : setup, call and assert. Where we both disagree is, where to put the setup code. One opinion is, the setup code belongs directly in the test so everyone can see in which environment the test is running. The other opinion is, to have as little setup code in the test method itself as possible and use fixtures or normal method calls to do the setup. The benefit of this: Faster recognition of what is tested and expected when reading the code. Knowing about how the environment is set up isn't important in first place, but can be accessed with a few clicks more. Opinions?
can someone help me am working on a virtual shop but... i need help to add how much you want and multiply it with the price to get the total
Why doesnt it make the folders as intended ? ` import os
import shutil
current_dir = os.getcwd()
for f in os.listdir(current_dir):
filename, file_ext = os.path.splitext(f)
try:
if not file_ext:
pass
elif file_ext in ('.py'):
shutil.move(
os.path.join(current_dir, f'{filename}{file_ext}'),
os.path.join(current_dir, 'Python files', f'{filename}{file_ext}'))
elif file_ext in ('.jpg', '.png', '.gif'):
else:
shutil.move(
os.path.join(current_dir, f'{filename}{file_ext}'),
os.path.join(current_dir, 'Andre filer', f'{filename}{file_ext}'))
except (FileNotFoundError, PermissionError) :
pass `
well, what do you intend it to do?
I just fount it online, and adjsuted the name of the folder. I intend, when i run the script that it takes all files in the directionary and sort it out to the specific file types like this https://learndataanalysis.org/how-to-organize-your-files-with-python-python-tutorial/ @candid light
In this tutorial, I will be sharing a very useful Python script I use very frequently when I need to organize my files by file type.
Okay. Seems fine to me. Copied the code and tried it out.
What does not work as you want it to?
It only makes the "else" folder, and not the other folders that are supposed to organizae e.g. the python files in the python folder and so on
You could edit the except statement to:
except Exception as e:
print(e)
And take a closer look at what happens in your script
I aint so sure what you mean, i am totally new in the "space"
At the bottom of your code is the "except" statement. This will catch all Errors that occur during code execution and execute the code inherited.
At this time this is "pass" which will not print you anything or give you any other information. This is bad for debugging your code.
Ok. so delet except (FileNotFoundError, PermissionError) : pass
and tahn put in except Exception as e: print(e) instead?
yes like this
except Exception as e:
print(e)
ok
Properly indented as you can tell for sure.
^^ it needs to be the same indentation as try:
ok ๐
try:
pass
except:
pass
Yes i understand ๐
I know this script is different from one i send by start but it still gives me error on the identation
Unfortunately I can't tell what is wrong with the indentation. Make sure you are using no tabs and 4 spaces indentation through your script.
This is a common issue when copying code from the internet.
Maybe it is the blank line above the except statement. I'm sure you can figure this out! ๐
Okay it was in the except statement
i had done a tab instead
but it still does not make the directionaries for me ?
It on says it does not exist
But that's is good! We are getting closer!
Yes i know ๐
But i do not undertstand why it does not create the folder and add in the respective files
In the documentation it says:
"Recursively move a file or directory (src) to another location (dst) and return the destination.
If the destination is an existing directory, then src is moved inside that directory. If the destination already exists but is not a directory, it may be overwritten depending on os.rename() semantics."
https://docs.python.org/3/library/shutil.html?highlight=shutil#module-shutil
I think you need to extend your script to create the folders, if they do not exist.
But it automatically create the folder situated in the "else"-statement, why does it not create the other folder than?
Okay i created the folders accordingly and now the script works, but i still do not understand my last question
I tried it on my machine and I'm encounting the same issue with the script not creating the folders.
I only can trace the issue so far that shutil.move is not trying to create the directory instead it tries to write to a file which doesn't exist.
Yes okay. But if i make the correct folder it moves it, which is my intention
glad I could help. ๐
Thanks ๐
It depends on how much set up code there is and whether it can/will be re-used. Keeping code localised can be helpful, but it can also backfire if there is a lot of code. Monolithic functions are terrible for readability.
Furthermore, if the code needs to be re-used, then it should be put into a fixture without exception. If it's a short one off-thing, just throw it into the test function. Could be argued that such inconsistency is bad, but I don't seem to mind it.
This arguably goes beyond writing tests. I generally prefer to split code up into logical groupings, even if those functions are only used once. It helps me follow my code. Besides the performance overhead of extra function calls, there is also overhead in having to come up with a good name and possibly add docstrings and type annotations. I think it's worthwhile.
If your fixtures have good names then a reader should have a good enough idea of what's going on without needing to see the exact set up code. As you wrote, the setup isn't necessarily important to see in that context.
I picked up a habit from a coworker that I think helps with this. It comes from Behavior Driven Development, originally, but I apply it to pytest tests as well: every single test function gets split into 3 sections, separated by comments: ```py
def test_some_thing(fixture1, fixture2):
# GIVEN
mock_something()
mock_something_else()
# WHEN
do_something_Using_the_mocks()
# THEN
assert effect1
assert effect2
And everyone can read it without being told what it is, and worst case scenario they just ignore the comments and read the test from top to bottom anyway. It can be a bit tough to get other people to stick to the style - stopping people from testing multiple things in one test function is hard; they want to do it because those things share common setup code and they don't want to repeat it. But other than that, I like this a lot: it adds clarity to test functions at the cost of a bit of discipline.
I wouldn't factor setup code and post-condition checking code out into other functions or fixtures unless they're intended to be reused. Beyond that, it's a judgment call. I don't mind seeing a single line of setup that's copy-pasted into most tests and only tweaked occasionally, but if that becomes 5 or 10 lines I'd almost certainly refactor it into a fixture or helper function.
@cedar pagoda I've seen a test suite for a tool that worked with files, and it just used tempfile to create temporary files for tests
Is that what you were asking about?
Or are you asking how to assert that your code has proper checks for existing files/dirs?
This
I'd approach it by giving it a directory that doesn't exist and then seeing how ti responds (e.g. asserting it raises an exception or returns some alternate value)
Eventually though, in order to make the assert pass wouldn't you need to point it to a structure that's similar?
Would I have to artificially create some example folder structure along in the package?
You need to test a complex directory structure?
I'm not sure if there's a better way to do that actually
It sure seems complex to me lol
I'm using os.walk to look for a file starting from a path the user will pass in
Say I'm looking for a file called "optimization.log". The folder it appears in gets made regardless of whether the pipeline that calls it succeeds or not.
We want to parse that file
I can't think of another way than just creating temporary directories
Like you can create a temp parent dir and then assert that the folder got created
Make it in your test, before you call the function.
tempfile uses a context manager and can do the cleanup for you.
I don't think there's an easy way to mock a directory structure instead of just creating it temporarily on the filesystem
That's the best approach I've heard so far, since I'm testing a folder structure, I suppose I need an actual folder structure lol
And this does not sound like I'm testing the wrong thing, does it? I think it's called the XY problem haha
The fact that it's not clear how to test it, it's not some symptom that maybe I'm testing the wrong thing (and there's a better way)
I'm not sure. I don't have enough context. But it sounds realistic.
Thanks for the rubber ducking, I'm a lot happier with the context manager idea than packaging a full folder!
You're welcome
IDK how to fix this. I already turned the str in to a int but it still din't subract?
look at line 16
is both an int
if not you have to do:
new_var = (int(var_1) - int(var_2))
@proper wind
Worked?
can you send me the code pls
from bs4 import BeautifulSoup
import requests
source = requests.get('https://chap.manganelo.com/manga-dr117685').text
soup = BeautifulSoup(source, 'lxml')
for chapter in soup.find_all('li', class_='a-h'):
current_chapter = 134
chap_src = chapter.find('a', class_="chapter-name text-nowrap")['href']
chap_num = chap_src.split('/')[4]
chap_num = chap_src.split('-')[1]
print(int(chap_num) - int(current_chapter))
btw solo leveling is a good manga you should read it ๐
and please the full code
you missed a bit
@trail river
what a wonderful site ๐

I did
from bs4 import BeautifulSoup
import requests
source = requests.get('https://chap.manganelo.com/manga-dr117685').text
soup = BeautifulSoup(source, 'lxml')
title = soup.find('div', class_='story-info-right').h1
print(title.text)
for chapter in soup.find_all('li', class_='a-h'):
current_chapter = 134
chap_src = chapter.find('a', class_="chapter-name text-nowrap")['href']
chap_num = chap_src.split('/')[4]
chap_num = chap_src.split('-')[1]
print(int(chap_num) - int(current_chapter))
click the site and paste your code
oh
then click save and share your link
its here

I got a new problem
You should use brain
'
Put the print like I did
I swear I am just following a tutorial๐
link

It's like:
x = 3
x = 4
print(x)
hahahaha
It is the same as:
x = 4
print(x)
no problem.
Start with something easy
Like calculator with input:
number_1 = input("Please write you first number")
ok, write it
write what?
calculator with input
there you should understand how var work
try:
num1 = float(input('Enter a number: '))
op = input('Enter the operator: ')
num2 = float(input('Enter another number: '))
if op == '+':
print(num1 + num2)
elif op == '-':
print(num1 - num2)
elif op == '/':
print(num1 / num2)
elif op == '*':
print(num1 * num2)
except ValueError:
print('Invalid Value')
except ZeroDivisionError:
print(f'Cannot divide {num1} with {num2}')
look men I was just following someones tutorials
but there you see thing, you made wrong.
There are two var
numb1 and num2
You made 2 numbers on one var in the first script you sent
You're in the wrong channel. None of your questions seem related to testing. #โ๏ฝhow-to-get-help
Is there a way that I can create a Python script that when running will launch a web browser and capture HTTP requests?
The context of this is for performance testing. A customer describes a flow for their website, ie. Launch URL, login, click button. I need to create a Python script that will simulate this flow. Other tools like LoadRunner allow you to start recording traffic in a browser, and it captures which HTTP requests are being sent, then creates a script that will make these same requests.
I know I could do it manually by examining a network log, or by exporting a har file and converting that to python, but I'm trying to take those steps out of the process.
If you have any ideas, please @ me.
Looks like selenium can capture network traffic. It should also be able to simulate the flow you describe.
I thought Selenium was just to replay the requests, but I'll look into it more
Sorry
I was told by somebody else I should look into science stuff, and I found this channel that seemed more relevant @kind meadow
If you read the channel's description, you'll see it's about automated software testing
Like unit testing
I am currently scrapping 10+ websites(using chromium separate pages) to notify me when a product is available but it is very taxing on the machine I am running it on. What are some methods I can use to reduce the impact selenium and chromium have on my machine? (I am also using threading to run the multiple chrome pages)
How can I write tests for a scraper that determines several things from a url? The status of things on the url may change, so sending the actual request for the test may cause tests to break if any status in the url is updated. Should I just save the html from a request in a static file and read that for the test that way I will always know the expected output from the tests?
I want to automate with python basically make robot that itself opens sites and surfs internet. Where I can start and which library I can use for that
@molten vapor, I don't think your question is related to the channel topic of "automated testing", but the libraries requests and BeautifulSoup are a great place to start
I would think that just using python requests library would be less resource intensive than Selenium. I haven't used Selenium much but I think it starts a browser process when you run it. It will be harder to scrape data without Selenium but it's definitely possible
Hi! I try to test the following function, but I have troubles testing the exception:
def sys_output(command: list, path: Path = None, timeout: int = None) -> str:
try:
output = check_output(
command, cwd=path, text=True, stderr=PIPE, timeout=timeout,
)
except CalledProcessError as e:
raise CalledProcessError(
f"Command '{e.cmd}' return with error (code {e.returncode}): {e.output}"
)
return output
This is my test function. Any quick insights why it doesn't work?
@mock.patch("syscmd.check_output")
def test_sys_output_CalledProcessError_exception(mocked_check_output) -> None:
mocked_check_output.side_effect = CalledProcessError(returncode=1, cmd=["echo"])
with pytest.raises(CalledProcessError):
sys_output(["echo"])
selenium python is opening 2 chrome windows instead of 1
can some help me fix this problem
Hey @edgy pebble!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
โข If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
โข If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
!code-blocks
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
selenium python is opening 2 chrome windows instead of 1
can some help me fix this problem
pls find a solution for this
This doesn't seem related to automated testing. If you have a question, see #โ๏ฝhow-to-get-help and open a help channel.
Selenium maybe
I couldn't use selenium
I couldn't configure chromedriver.exe
My laptop is 64 bit
I never tried?
Me too?
Is this the name of library
I'm going to test
