#unit-testing
1 messages · Page 20 of 1
oh no not at all. Your directory needs to contain at least one file, for it to become a valid directory that git can track @nocturne moat
and an initial commit without any files actually commited is kinda useless too
you're welcome
yes indeed , Ill have to be more aware , really sorry for such a dumb question
I am looking to use Robot framework for some web testing and I wrote a function in python that concats a base url e.g www.mysite.com to a subdomain that i want to test ... e.g www.mysite.com/home
the function I have is
@keyword("create full url")
def create_url(arg1):
if arg1.startswith('/'):
subdomain = arg1.lstrip('/')
base_url = 'https://mysite.com/'
url = base_url + subdomain
return url
from a test, i call it like so:
*** Keywords ***
create url /home
*** Variables ***
${now} datetime.datetime.now() modules=datetime
${email} me+${now}@mysite.com
${url}= create full url home/
*** Test Cases ***
Verify_Home_Page_Accessible
Start Test ${url} ##Passing url to start browser session
Title Should Be ${home_page_title}
Finish Test
however the error i get is
Keyword 'create url' expected 0 arguments, got 1.```
What are best practices on mocking functions that send requests to a server?
In order to make them return some custom responses and not interact with it
you make a fake site for testing
The best way is to not do it at all if at all possible.
can't you use a mock library to mock a server?
hm, right
<html>
<body>
<div class="1">
"ignore"
</div>
<div class="1">
<div id="want1">...</div>
<div id="want2">...</div>
<div id="want3">...</div>
<div id="want4">...</div>
</div>
</body>
</html>
@tired kiln I recommend using a Chrome extension called CroPath, which creates a new tab in the Chrome Developer Tools and allow you to right click an element and get the Xpath of the element. This you help you on figurint out how to search the elements or, depending on what are you doing, you can search the element by Xpath on your code.
Anyone know how I can have a pytest fixture act like a context manager (executing code on test finish)?
@urban burrow instead of using return something in your pytest fixture, you can use yield something in it, and anything else after that will act as teardown.
@fresh blade would something like this be accurate?
@pytest.fixture
def blah() -> str:
yield "hi"
print("teardown")
Edit: tested. It works 🙂 Thanks a lot!
[nevermind i repair it]
- words = raw_input('Enter some text to translate to spanish')
print ("You entered: ", words)
words = words.split(' ')
for i in words:
if len(i) >= 1:
i = i + "%say" % (i[0])
i = i [1:]
print (i)
else:
pass```
line 1 ```cs
- words = raw_input('Enter some text to translate to spanish'```
saying raw_input is undefined
Traceback (most recent call last):
File "main.py", line 1, in <module>
words = raw_input('Enter some text to translate to spanish')
NameError: name 'raw_input' is not defined
```
raw_input is Python 2
raw_input is obsolete and doesn't exist in Python 3. If you're following a tutorial, find a less ancient one 🙂
Do i really need tox if I am testing against a single python and django version?
Probably not
Just pytest is what I use in those cases.
If you are only testing your own site, and control the deployment, one version is fine.
If you write e.g. libraries / reusable apps, using tox is a good way to ensure it works across versions.
I normally use pytest (or hammett if possible) until all tests pass and maybe I run tox at the end. Normally there are no problems at this point as it's rare I change something that is actually affected by different python or django versions.
!eval print("hm..")
You are not allowed to use that command here. Please use the #bot-commands channel instead.
oh swoy
thanks @proud nebula @balmy saffron @digital grotto
Simple error in selenium that I still don't understand
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="useremail"]"}
The ID is correct, but I went ahead and used .find_element_by_name() yet that didn't work either
I even used .find_element_by_xpath() and it was still incorrect for some odd reason
I've used almost all objects, doesn't seem to work
I've also used .find_element_by_classname() still did not work
I've also added time.sleep(2) to maybe slow it down if it isn't reading but that didn't help either
find element by ID with "useremail"?
@proper wind
also check if it's spelled correctly
and post code
You are not allowed to use that command here. Please use the #bot-commands channel instead.
Hey @barren plaza!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
I don't know if this is where I should ask, but I'm trying to use pyinstaller but It keeps saying me: "Error loading Python lib: [...] : no suitable image found", do you know how to solve?
Error loading Python lib '/var/folders/5r/qt87dj1955jfj8sxv2vjlsy40000gn/T/_MEIlxV9qs/Python': dlopen: dlopen(/var/folders/5r/qt87dj1955jfj8sxv2vjlsy40000gn/T/_MEIlxV9qs/Python, 10): no suitable image found. Did find:
/var/folders/5r/qt87dj1955jfj8sxv2vjlsy40000gn/T/_MEIlxV9qs/Python: code signature invalid for '/var/folders/5r/qt87dj1955jfj8sxv2vjlsy40000gn/T/_MEIlxV9qs/Python'
Looks like you don’t have the library installed
If you use Linux, just type “pip install pyinstaller” @frozen ore
wouldn't that mean he couldn't build it in the first place
So idt that's the issue
This is completely the wrong channel for such question anyway
I have pyinstaller, I create the exe and then the error appears when I lunch
This is completely the wrong channel for such question anyway
@kind meadow sorry
Hey! Does anyone know how I can run the test suite for this: https://github.com/Usama0121/ariadne-jwt
I tried python -m unittest, which raises ImproperlyConfigured errors because it doesn't detect settings, and if I run python tests/run_tests.py, I get ModuleNotFoundError: No module named 'tests
Also get ModuleNotFoundError if I try it with pytest.
Please do @ me
@tiny widget ^
@balmy saffron maybe python -m tests?
/usr/bin/python: No module named tests.__main__; 'tests' is a package and cannot be directly executed
Just says tests. https://paste.pythondiscord.com/rupaxucuca.sql
python -m django works, so django is installed.
Maybe I should just open an issue and be like document your tests bruh and ask lol
Oh....
DJANGO_SETTINGS_MODULE=tests.settings python -m unittest gives me ModuleNotFoundError: No module named 'promise' ... Ironically, that is very promising xD
Is it haha
I guess you can activate the audit for imports, and trace the problem a bit better
I set up a venv and am installing dependencies.
DJANGO_SETTINGS_MODULE=tests.settings python -m unittestgives meModuleNotFoundError: No module named 'promise'... Ironically, that is very promising xD
@balmy saffron looks like adriane is a dependency, theirrequirements.txtspecify it
Aye, I know. The dependencies are not the problem 
in selenium i have 2 class with same name i want to work with the 2nd class how do i do that??
You mean two things in the DOM with a specific css class? Select all with that css class and then you have a list. Then take the second entry.
can someone help me convert python script to exe file
Greetings everyone, hope all is well. I asked here not too long ago and didn't get any response, but:
I've written a parser for xml reports and I'm new to the idea of fuzz testing. Can anyone here point me in the right direction for fuzzing my parser? I'm not having much luck finding an xml based fuzzer for python.
I tried messing around with untidy, which I can't seem to find a working copy of: https://github.com/clem1/segvault/untidy
I also found this one, but it's not documented and I havent been able to get it to work: https://github.com/kahowell/py-xmlfuzzer
https://stackoverflow.com/questions/63941837/invalidregistration-fcm-when-sending-push-notifications-via-appium-and-python any idea on this one when using the get_clipboard_text() function from Appium?
I'm feeling really happy with my Python CLI app lately -- I feel that I've finally gotten the hang for writing tests in Python.
This pattern in particular has been super helpful for testing HTTP requests:
@pytest.fixture
def mock_my_endpoint() -> Tuple[MyEndpointRequest, MyEndpointResponse]:
"""Fart."""
mock_request = MyEndpointRequest(...)
mock_response = MyEndpointResponse(...)
schema = desert.schema(MyEndpointResponse)
_mock = mocker.patch("requests.get")
_mock.return_value.__enter__.return_value.json.return_value = schema.dump(mock_response)
return mock_request, mock_response
def test_my_endpoint(delegate: MyDelegateClass, mock_my_endpoint: Tuple[MyEndpointRequest, MyEndpointResponse]) -> None:
"""Butts."""
mock_request, mock_response = mock_my_endpoint
response = delegate.use_my_endpoint(mock_request)
assert response == mock_response
is tdd standard when working in the enterprise?
is tdd standard when working in the enterprise?
@heady iris On paper, yes, but in reality, no.
People will talk about the tests at the beginning, but not actually write them until the end. So, it's similar to TDD
Ok thanks @carmine bay I’ve been in two roles so far out of college where I was the sole author of all the code that goes into prod, so I was wondering how it works when many devs are working on a project(in practice) I’ve never written tests and I know it’s not good programming practice so I’m trying to learn and start refactoring the code with tests.
Is there a way to run coverage.py terminal output in Travis? I've got coverage -m pytest blah/ and then in after_success coverage run -m pytest blah/ but it's not working? Showing: Can't add file tracer data for unmeasured file '/home/travis/build/HUGE PATH TO AN HTML FILE
@heady iris Not to market and stuff, but you can checkout https://github.com/Donate-Anything/Donate-Anything I'm a freshman in college, but when I was pushing stuff into prod during high school, I too didn't have any tests. It's hard to write a lot of tests for your already written code, and I had to completely restart one of my other projects because I had no tests for it (and one little change in the DB made me quit for awhile since it was a huge breaking change apparently).
I don't have any industry experience with other programmers, but I can just say that when many devs are working on one project, your fork is gonna get clumped up real fast testing other people's functionalities (i.e. don't use master branch on your fork except for syncing with upstream); even if all their tests pass, you need to test with your own code, a list of naughty words, etc. etc..
Just reposting after that lengthy message: Is there a way to run coverage.py terminal output in Travis? I've got coverage -m pytest blah/ and then in after_success coverage run -m pytest blah/ but it's not working? Showing: Can't add file tracer data for unmeasured file '/home/travis/build/HUGE PATH TO AN HTML FILE
Didn't work. pytest --cov-report term --cov=blah blah/ gave me ValueError: I/O operation on closed file. Ah it gave me the same aforementioned error first as INTERNALERROR >
that's quite weird since I use travis too and it works fine for me
@heady iris TDD is a tool. No tool is good all the time.
TDD is great if you have a clear idea what you are producing. Which is the exception, not the norm if you aren't just spending your days making knockoff software.
@proud nebula thanks for the perspective. That makes a lot of sense. I guess Since I’ve never worked with a “team” or get peer reviews on my code, I was thinking that it may provide some kind of benefit to the code “quality”(lol). There was a recent job posting that had TDD as a requirement which got me looking into it. I def do manual testing though. Just trying to become a more proficient developer
When starting out you probably ARE making knockoff software and then absolutely take the time to practice TDD. It's a really good tool and you have many opportunities to practice it when you're starting out. Later in your career it's harder to find those things to practice on.
And TDD for bug fixes is pretty good obviously. But even that is often not as good and easy as we'd like.
Hello. I am making a project in Django and today I started to learn how to write tests with a book by Harry Percival. Just general question, is testing more hard than actual making an app? Because I find it very confusing, and to test something properly you have to be sure how it exactly works etc... I have a current app written in django, it's a content aggregator but I find it super hard to test it properly... Tbh I don't even know where to start.
if you don't find testing hard, you might want to get yourself seen by a psychologist
another question regarding testing with selenium. Do you just basically use it as a scraper and verify received html this way? Or are there many more applications?
I don't use selenium at all, but you should probably be using selenium to test buttons and the likes
ah so it is tested manually?
Returned html can be tested using django's client easily
thanks, long road ahead of me
Selenium is absolute last resort. It's the slowest way to make a test and should only be used as little as you can safely get away with.
But you should definitely have it for super critical stuff like login!
I have this test for testing if django resolves to correct view based on url, but how do I test django auth_views? Working code for my view:
def test_local_news_url_resolves_local_news(self): found = resolve('/local_news/') self.assertEqual(found.func, local_news)
I tried this with auth_views and it doesnt work:
def test_login_url_resolves_login(self): found = resolve('/login/') self.assertEqual(found.func, auth_views.LoginView.as_view())
that's the error:
AssertionError: <function LoginView at 0x052F0148> != <function LoginView at 0x051EF4F0>
okay, if anyone else is wondering, it was comparing two objects in memory hence different.. You have to compare found.func.__name__ with auth_views.LoginView.as_view().__name__
That seems like not a very useful test to me.
@sinful wind self.assertEquals(found.func.view_class, auth_views.LoginView.as_view()) is the correct way
Comparing equality between two generated functions won't work right?
idk what that means, but this works. I copied it from an old project
@proud nebula I just started to learn testing today, it is very probable that this test is gibberish... I just thought it is useful, I check if '/login/' maps to correct view, even though it is a view imported from django
that is a valid test
@fresh blade strange. I wouldn't do that.
ehh worked for me, so I'm not complaining
I think it's a silly and useless test :)
:)
I don't even know if i should agree or not 😛 I think if I get more experience I will be able to tell if test is useful or not, right know this idea of testing every feature/line of code is alien to me..
yeah and getting the perfect coverage feels really good ngl
I think to test it properly you have to have good knowledge, even thought I've built something I am not 100% how it works so testing is very difficult
You'll have coverage on urls.py anyway.
You won't have mutation coverage though! But I would whitelist all urls.py files from mutmut.
so in similar fashion, should I test if view gets correct template?
why not? it's just a few extra assert statements. it doesn't hurt
is there maybe online some resource about testing django? some lists with point what should be tested in view/model etc
when I started testing i couldn't find any good resources. if you find one, please do. share it with me.
It hurts to have useless tests. It makes your test suite slower, it burns electricity, and if you don't have 100% renewable electricity it's CO2 wasted. Tests compounds too as you run them over and over.
Test your business logic. Have super paranoid tests for access control and critical stuff like login. But don't just write tests because your religion tells you to :)
You can statically verify template names point to valid file names. You don't have to run slow tests for that.
thanks a lot for advice
A lot of my advice is "work for a few years and get hard earned experience" :)
The answer is almost always "it depends"
Does anyone want to test my Software 😂 (Hangman, Binary Converter and HiLo Number Guessing Game)
Hangman hm...
No. This is for discussing testing.
I realised that 😂
How to test my code in selenium. I am new for selenium Please guide me !
Guys how could i get my computer audio?? (obs: its not the microphone)
like in real time
@fresh blade Using my open source website as a testing base: https://travis-ci.com/github/Donate-Anything/Donate-Anything/jobs/387795851 Not sure why coverage isn't working on terminal (not looking into using coveralls or codecov)
@urban burrow looks like this might be a bug https://stackoverflow.com/a/59899304/11667450
maybe raise an issue in pytest github if it isn't solved?
Hm interesting. The Travis build is using Python 3.8, which the SO answer said was fine?
Yea I guess I'd have to raise an issue in their repo. I've had this issue in two different repos, so I'm not sure what's going on.
Hey guys, I'm working on a few selenium tests (mostly working) but they're not truely automated as I'm failing to accept the Google cookie consent form and this needs manual intervention for now. I've tried
- Setting a cookie (taken from a browser that accepted) after loading the page (didn't work - possibly dynamic strings I'm unable to recreate)
- Clicking the 'I Agree' button on selenium (I'm failing - my xform requests aren't hitting) and changing frames (there don't seem to be any frames or iframes defined)
- Running the ScriptExecute on the script mentioned in the same button tag (broken - script not found)
I'm possibly going about this all the wrong way, any advice? Thanks in advance
Sure! Is there some sort of config that allows it to.. well work?
idk but mine is a bit different
i'm sure something different will happen lmao. Thanks!
OH Shit I think it was because I didn't have a .coveragerc file so coverage was getting an internal error when it was looking through the .HTML file...
that traceback could be worded better lmao........
Thanks @fresh blade, again
@urban burrow you could fix the error message and submit a PR
@proud nebula I thought about it, but it could actually be due to the HTML file using Jinja2-like stuff mixed in with the HTML. I haven't tested it with netbat's django coverage plugin, so I decided against a PR since I wanted to test some stuff first.
When it would be appropriate to test the __str__ dunder of an object, or at least in my case, various wrapper/container classes?
If it's important. I know that's vague :)
Same goes for repr for that matter.
We test reprs and str and exception messages in some libs at work because it's super important to us that the dev experience is top notch.
I'm basically using it to unparse the AST that I've built; testing classes that simply delegate the str call would be seem unnecessary at least imo
Yea, if it's a good idea to test these things is almost always super dependent on what you're doing. So one class might really need a test for dunder string while another really not.
Seems like you know that you don't want to test it.
You could think of it as whether the string output is "officially part of the API" (where you care about it being consistent), or just a bonus that could be anything without breaking user code.
Could also be internal but useful to check for other reasons
Dont know if if this is the right place to ask questions, but anyways, this is my question:
how do i run sh files?
trying to run this:
data/get_data.sh
@placid vigil if they're executable then ./get_data.sh otherwise sh get_data.sh
you can make the file executable using chmod +x get_data.sh
might need sudo depending on the files's pre-existing permissions
this is doing my head in haha, so long since ive touched programming, and ive never used python
Do i need to add the folder that sh file is in the PYTHONPATH?
cause i cant get any commands like that to work
@placid vigil sh is not dependent on python and you don't need to add to PYTHONPATH for it to work... What exactly are you trying to do?
i wanted to try this
https://github.com/fperazzi/proSR#install-dependencies
im at the step: "Getting the Data"
just trying to run the get data file to get the datasets
Im like 90% sure im gonna get stuck in the later steps since im out of my depth here, but i just wanted to try
@placid vigil from what I see, the script is just unzip and wget commands, so you won't require sudo access for it
cd data; sh get_data.sh should work
(thanks for helping btw)
okey, im not that familiar with cmd, but i think i enabled to navigate to the folder where "get_data" is located
This is the location:
C:\Users\Vann\Documents\Python Scripts\proSR\data
so its:
cd C:\Users\Vann\Documents\Python Scripts\proSR\data; sh get_data.sh?
oh you're on windows?
i dont have much experience with it
but yeah you're correct i think
thats what i thought too, but i just get a message it cant find the path specificed
@placid vigil since you have a folder called Python Scripts with spaces, you might have to escape it
an easier method is to open the data folder in windows explorer
and then type cmd in the url bar
oh neat, cool way to do it
just read that windows dont have built in support for sh files so im gonna look around for a program that lets me do it
maybe just dual boot with Linux
or you could look into wsl i suppose but it has never worked for me
@placid vigil also looking at the script again, it contains a few apt commands, so you'll need Ubuntu or a debian system to run that script
if i get wsl to work as you mentioned, could that still be a solution?
Yeah its supposed to be a complete linux subsystem within windows so I suppose it should
Make sure you go with ubuntu though
okey, ill try
thanks
came this far
@placid vigil Looks like you need super user access afterall. Trysudo sh get_data.sh
@placid vigil are you using double [[?
because sh doesn't support that, only bash does
just post your script here
Hi
I wanted to know how to convert a .py file to an exe file
I'm using the modules pyttsx3 and tkinter in my program
It doesn't work with pyttsx3
https://stackoverflow.com/questions/64027528/how-could-i-get-my-intern-computer-audio-in-real-time
Guys could you help me 👆
so if i have a class defined in a file and i import that class to another file for testing can u not define that class again?
You can make any name point to any new object any time. A class definition is just that.
Yea a class is just the assignment of a created type assigned to a name.
i was getting all kinds of problems giving a test class the same e as a class
Well yes. Overwriting gets confusing. Don't do that :)
ye thankfully i got helped
I need a color module to color Python text, ive tried colorama but i think it needs more testing. Anyone got a good solution?
ping if you know
@proper wind "needs more testing"? works4me
IDLE is.. not very good. you can't count on it acting like a real terminal, including coloring text
but it doesn't recognize colorama
"it"?
yes, IDLE isnt' very good
so how would i get vis working with colorama?
or any color module for that matter
oh, i just saw that you can use ansi
let me try that out
well you can still tell me
Deosn't work
This channel is for testing. Try a help channel.
hey guys, how to catch wich key inside a json.dumps is returning error?
example:
dict = {'data' : datetime.datetime.now()}
json.dumps(dict)
# this will return an error because dates are not json serializable.
# how to get 'data' value to raise an error with that?
how to raise an error and point the data
import datetime
import json
json_data = {'data': datetime.datetime.now(), 'name': 'my-name'}
for key, value in json_data.items():
try:
j = json.dumps(value)
except TypeError:
print(key)
You are not allowed to use that command here. Please use the #bot-commands channel instead.
@strong yarrow
yw
is anyone on a windows platform rn?
i created an app and its works fine in my pc,i want to see if its actual work for another user,ping me if u want to test 🙂
@untold vapor why not use a CI? Travis would be great.
Hello, I am currently working on a project that automates a website and i am going to sell this project to a company? Any one willing to help me? You can have a fine share in the profit.
If anyone is interested they can dm me
@fresh blade hm?
@untold vapor Travis CI is a Continous Integration system. Basically what it does is run your entire test suite when you commit to your upstream repo.
It can do other stuff too, but yeah testing is its forte
just look it up, you'll find better answers on the internet than I can supply.
it might just be what you need
ok thanks
am. just am
How would I fix this?
You, Cyan, Red, Blue, Green, Lime, Purple, Pink, White, Black = r.choice(roles, 10)
Message=choice() takes 2 positional arguments but 3 were given Source=C:\Users\i'm not revealing my username on my pc lol\Downloads\Among Us.py StackTrace: File "C:\Users\i'm not revealing my username on my pc lol\Downloads\Among Us.py", line 36, in <module> You, Cyan, Red, Blue, Green, Lime, Purple, Pink, White, Black = r.choice(roles, 10)
I'm not so sure on it lol
It's import random as r
i just forgot to put that at the start 🤦
bc the import random as r is at the beginning of my game
so it would be
import random as r
r.choice()
I think you'll want r.choices
oh, i'll try that
choice only uses 1 argument afaik
from random import *
print(choice([1,2,3,4,5,6,7,8,9]))
i did r.choices(roles, 10) and it gave me this error
Message='int' object is not iterable
Source=C:\Users\i'm not revealing my username on my pc lol\Downloads\Among Us.py
StackTrace:
File "C:\Users\i'm not revealing my username on my pc lol\Downloads\Among Us.py", line 36, in <module>
You, Cyan, Red, Blue, Green, Lime, Purple, Pink, White, Black = r.choices(roles, 10)
it says object of type 'int' has no len() @rose jungle
it just does this with the k=
i want one individual result per r.choices, like
Lime scurries off in some direction.
You, Cyan, Red, Blue, Green, Lime, Purple, Pink, White, Black = r.choices(roles, k=10)
That should assign a (non-unique) choice to each. r.sample(roles, 10) would assign a unique result to each.
Where do You, Cyan, Red, Blue, Green, Lime, Purple, Pink, White, Black get used?
You, Cyan, Red, Blue, Green, Lime, Purple, Pink, White, Black are meant to be variables containing their role
also when i run @terse fog's solution it gives me Sample larger than population or is negative
roles = ["Snake" "Snake" "Snake" "Snake" "Snake" "Snake" "Snake" "Snake" "Snake" "Python"] it's got exactly 10 tho
try:
roles = ["Snake", "Snake", "Snake", "Snake", "Snake", "Snake", "Snake", "Snake", "Snake", "Python"]
['Red', ' scurries off in some direction. looks at something, and then makes an escape. takes a deep breath, and runs off.'] Press any key to continue . . .
oh, i remember to do the same with the other list
['Purple', ' looks at something, and then makes an escape.'] Press any key to continue . . .
Can i remove the [','] somehow?
" ".join(['Purple', ' looks at something, and then makes an escape.'])
What ever is printing the result
put it in print(" ".join(____))
print(" ".join((plyrChosen) (plyrEscape)))
'list' object is not callable
i tried with a comma and it said it only takes 1 argument
?
@proper wind Not the appropriate channel for these types of questions. Software testing is about automated testing through tools such as unittest or pytest
What would you reccomend? @digital grotto
You can check out our help channel system #❓|how-to-get-help
Hey @quasi sequoia!
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:
@quasi sequoia this is the wrong channel. And you really should look up enumerate() and str.lower(). Your code is much too complex.
I have this endpoint:
@app.route("/api",methods=["POST"]) def marks(): if request.method=="POST": f = request.files["file"] print(f.filename) path="./static/" + f.filename f.save(path) caption = get_caption(path) os.remove(path) return jsonify(caption)
I want to understand how can I test this endpoint using Postman?
What have you tried?
(Also remove the if for method. It's redundant as the decorator already guarantees that it is in fact a post)
@trail charm using postman specifically, all you can really do is test that the output of the test in postman matches what you expect
what you can do is construct a file with a known caption, that you can then confirm is returned correctly
its a bit odd to me that get_caption takes a path as its argument... is it reading the file from disk right after you saved it? perhaps this code could be more testable if get_caption was able to read the file data itself. then you could test get_caption separately. you can also write a separate function to retrieve the file info and construct a filename, which can also be tested separately. at which point the only thing left to test is that the endpoint works, without having to test any of the logic inside it
not that you always have to be a fanatical unit tester like this, but sometimes it can make your testing a lot less complicated
what is this channel about
see the sidebar
whihc sidebar
or top bar if you're on pc
ohhhhh, wdym by our applications and libraries
is this kinda like share your projects thing
nope, testing is a major concept in programming wherein you test that your code works as expected.
this channel is basically for that
is this kinda like share your projects thing
@gentle zephyr It's not. It's about the practice of testing software through tools likeunittestorpytest.
ohhh i see
ok
I hope the rename of this channel fixes things.
ohhh this channel is dead
Lol
We renamed it to bring it back from the deads though
people use it as and when required, why would it be dead?
If I were to make a library, would making a testing subpackage that abstracts away mocking some of the library be useful? Just wondering what your opinion on it would be...
hello everyone, does anyone have some exp on Selenium with hotkeys? Currently I'm working on hotkey to reload browser (CMD + R) since i'm on Mac, but i'm unable to do it even once.
I've researched a lot on stackoverflow but seems no answer. I've tried 2 ways:
element.send_keys(Keys.COMMAND, 'r', Keys.NULL)
It's working with CMD + A (select all) but does not work with reload, or open new tab or any general browser related. Can anyone shed me a light?
@faint void hmm... Seems weird. Would seem more reasonable to make a separate package in that case.
Cause I'm more thinking "test" as in "a person can throw arbitrary data at it and see what happens to their application"
But yeah that would make sense
Maybe more like a playground?
Yeah that's a nice name, thanks lol
Naming things. It's one of those things 20 years of experience does help with ;)
Off by one and cache invalidation less so :(
So I am trying to do unit testing in python and I am confused by how the setUp() class is implemented. Can anyone explain?
You should probably be more specific. It's called before the test functions are run. The implementation doesn't seem very relevant?
the idea is that you can assign stuff to self in setUp, for use in tests within that class
Hey all, hope this is the right room. Running into selenium issues, can anyone advise why line #4 would throw a syntax error but not line #3? It doesn't seem to be the get html function (it still errors without it)
Hey all, hope this is the right room. Running into selenium issues, can anyone advise why line #4 would throw a syntax error but not line #3? It doesn't seem to be the get html function (it still errors without it)
https://hastebin.com/dowakewawa.rb
@willow stream line 3 has an unmatched parenthesis
Grumble
Thank you sir, I was so used to sublime showing me purple highlights, I must have missed one
Hah. Asks for ruby help on a python server. Gets great help 😂
Hastebin probably misidentified the language lol, seems like a unittest test just fine
Wat. Hmm. Strange.
I just noticed the file extension in the name - weird =/
Unit testing is not fun, I may come for some more help later friends. Thanks for everything so far
selenium: my code crashes when i try to declare form_button ( https://bpa.st/6JNQ ), says Unable to locate element, any advice?
I do not not know what you are trying to do?
you should try to enable the cookies of that site
are you just trying to open the page
does it work outside the driver?
oh so why would it not run inside it?
do you have any other driver handey?
you can try in that
yeah
but you need help right?
i think so
so you are just doing ```python
driver.get(URL)
which site are you trying to go to?
u right
@proper wind What is the URL or is it private?
kk
So the site opens then you click on an element and get the error?
guess it would work
try edge
i think he is saying that only
its k
and btw if it STILL doesnt work, you might still be in luck if you have internet explorer
cuz it runs on the old dos system so it is supported by nearly every website in the world
k
did it work?
hello
?
is there a splash screen on that page?
ok
is there a splash screen on that page?
@proper wind is there?
is there a splash screen on that page?
idk bosses asked that
i am just repeating his question
what is selenium?
what is selenium that you are talking about
what is selenium?
@proper wind it is a automation tool
You know what I think could be the issue here? Your Firefox version
which geckodriver did you download?
which version
just try with chromedriver as a test dude
he doent have chrome bruh
Did you download this version?
he dont "like it"
I know he does not like it but it is just for a test
what are these drivers used for tho?
then the download should still be in your downloads folder
bruh
what is geckodriver used for tho?
well, if you r not a super techy guy, you might still have chrome on your machine
ohh
download that version I posted
cool
but you can use it for testing dude
even without an account 🙂
they dont
how would you know?
is it a site?
I think a lot of companies would not choose to automate with Chromedriver if they did that
ok
I work for a major corporation and we use Google
If that does not work then remove firefox from your machine and install this https://www.mozilla.org/en-US/firefox/developer/
You should be using that in anycase if you are developing
You can surely try
Are you running your script?
does it still give you the redirecting issue?
there is no sign of them saying "we are spying on you you dirty person! keep your history clean."
Most typical Internet users will never see 1e100.net, but we picked a Googley name for it just in case (1e100 is scientific notation for 1 googol).```
but how can you interpret increasing security to spying?
nvm
did explorer solve the issue
?
google earns a 200,000 dollars trough ads a single minute bruh
what else do they need?
so?
does apple do that?
Google has multiple revenue streams
yes it does
cross platform treaties
contributers
apple respects privacy
@proper wind and apple earns the same amount every minute
okok
Or copy the url
Take it to your normal browser and execute it
what does it say?
thats my bro
🤜
hey are there any benefits of having a virtual machine for daily use?
are there any benefits in any section?
like?
ooh
ethical hacking
where can i download one?
wait, is it kind of like kali linux?
but it is an OS
yeah yeah
got that
so where can i download one?
what do u want to do with that
@proper wind practice hacking
wdym
lol 😉
so, how do u do?
🙂
nope
but i will
using kali linux
you know...... it is "legit"
why u want to learn it
@proper wind just for fun ryt now
but i am going to take software engineering in future
through where u want to learn
@proper wind youtube
it has a 10 hour course
@proper wind i suggest udemy
@proper wind whats that?
is it free?
cuz my parents wont give me any money
what?
not kinda
wdym?
like getting scammed or somethin'?
i will practice for a job in GOOGLE
so how old are you?
got that by your profile
lol
ik
😂
yeenanamous
ya
bai
friends?
thnx
@proper wind Try this too if you do not come right https://support.mozilla.org/en-US/questions/1148196
@proper wind whats that?
@proper wind sometimes u can find decent course promotions- get them free. can find the promo codes in discudemy.
(teachers want people to get course for free so they end up closer to the front page and get a lot of reviews -> benefits their sells -> win:win) ; initial phase
I am quit new where can I post my question about selenium?
ngl not sure ; won't harm to ask in the asking area though
I am quit new where can I post my question about selenium?
@glossy crane This channel is fine
How do you get the text from an element that has no own ''id'' but is a ''label for='id name' from an element.
In my example I use ''EXAMPLEID'' as ''id name''.
Example website Source (inspect element):
PARENT<input id="EXAMPLEID" type="radio" name="name" value="somevalue" onclick="javascript:setTimeout('__doPostBack('ctletcetcetcime$0','')', 0)">
CHILD<label for="EXAMPLEID"><span class="label">06:30 - 12:00 uur</span>
<span class="expositionPeriodCommentLabel"></span></label>
Python Code:
textout=driver.find_element_by_id('EXAMPLEID')
print(textout.text)
I want to get the ''6:30-12:00 uur'' out of it but don't know how. It does work when it's in it's own element and not a label for.
I also tried finding by xpath and class but that doesn't seem to work either.
Of course I tried to google/stackoverflow it but coudn't manage to get it solved.
paste the link and we I will try to give you the selector @glossy crane
@glossy crane and also please insert 3 backticks and type py before the code and again insert 3 backticks at the end
it will look like this
Example website Source (inspect element):
PARENT<input id="EXAMPLEID" type="radio" name="name" value="somevalue" onclick="javascript:setTimeout('__doPostBack('ctletcetcetcime$0','')', 0)">
CHILD<label for="EXAMPLEID"><span class="label">06:30 - 12:00 uur</span>
<span class="expositionPeriodCommentLabel"></span></label>
Python Code:
textout=driver.find_element_by_id('EXAMPLEID')
print(textout.text)
I want to get the ''6:30-12:00 uur'' out of it but don't know how. It does work when it's in it's own element and not a label for.
I also tried finding by xpath and class but that doesn't seem to work either.
Of course I tried to google/stackoverflow it but coudn't manage to get it solved.```
it is much easier to read
but half of that isn't code
i was just showing him how it would look
@proper wind but it shouldn't look like that...only the code part.
I have setup CI in my project using Travis and tox. My question is do I really need this line to install dependencies on the travis machine https://github.com/IgnisDa/python-random-markdown-generator/blob/master/.travis.yml#L11 since I am already installing all my dependencies inside my tox environment in this line https://github.com/IgnisDa/python-random-markdown-generator/blob/master/tox.ini#L8 ?
A library to generate random markdown text. Contribute to IgnisDa/python-random-markdown-generator development by creating an account on GitHub.
hey which text channel would be fitting to ask about the subprocess module
#❓|how-to-get-help @potent badge
Howdy friends, I'm wondering if someone could give me a nudge towards a solution. I'm trying to wrap my head around PyUnit with selenium. I have a functional script that does what I need it to do, https://hastebin.com/iyeqojulos.py. It goes to google maps, deals with 'cookie consent' (if you're EU you'll understand), does a search for an area, validates that I've searched for it via xpath, then clicks the 'directions' button and validates again that the location specified is listed. (again via xpath and comparing strings)
This works, but I'm struggling to wrap it in pyunit for assertion purposes, when I run it, the browser instance is launched, the location is searched then the tests suddenly fail. 1 timeout and 1 'unable to locate element' error. Code and stacktrace at https://hastebin.com/mucisomehu.rb
EDIT: I do see my destination input into the search bar before failure, so I know it's working just incredibly delayed when pyunits involved (my pyunit code anyway)
I have a feeling I'm missing something something fundamental, any help appreciated, please and thank you
I feel bad but I've started to 'fix' this by ripping out the selenium 'wait for object to appear' code and replacing it with sleeps 😦
@willow stream selenium has explicit waits built in, maybe look into them?
My understand was explicit waits was a part of the EC code I was attempting - wait for element to appear but ill dig more. Cheers @fresh blade
@willow stream on the topic of selenium, have you tried helium?
I've not @jaunty hearth but the front page of github looks verrry interesting. I'll chunk into it tomorrow I think. Thanks kindly
np :)
Todays public service announcement: collect coverage on your tests and make sure it's 100%. (I just found a test that wasn't run because it had the same name as another)
@proper wind Thank you for the example. I can't really give you the link because you have to login to get to that page. I can however give you part of the source from the website.
which site?
PARENT<input id="EXAMPLEID" type="radio" name="name" value="somevalue" onclick="javascript:setTimeout('__doPostBack('ctletcetcetcime$0','')', 0)">
CHILD<label for="EXAMPLEID"><span class="label">06:30 - 12:00 uur</span>
<span class="expositionPeriodCommentLabel"></span></label>
I will update it to the real source code later on.
Ahh, this seems to be the spot. Anyone aware of bot detetion?
uhm?
does unittest have any way to run a callable before each test method is ran?
a callback would work too
@heady python classes have a def setUp method which runs before every test case
test case as in each method that runs a test, or the class itself
each method. look into the unittest docs. it has many hooks like this
How much are multiple asserts in one test discouraged? Pretty broad question but I'll elaborate in a bit.
Basically I'm trying to test writing a test for a parser that just reads tokens prefixed with a single quote. Writing multiple tests, one for each token seems a bit redundant.
won't pytest's parametrize do the trick?
How much are multiple asserts in one test discouraged? Pretty broad question but I'll elaborate in a bit.
@digital grotto think it depends on their nature
but I agree that that sounds like a job for test parametrisation
Seems fair
I have a function which has an assertion - I expect that assertion to fail if given a value over a given threshold
eg
def f(x, m):
assert x < m, 'x should be < m'
... stuff ...
I'm wondering how to test this - in pytest there's xfail, so I could have
@pytest.mark.xfail
def test_f():
f(3, 4)
Which will give me 1 xfailed in the terminal output - I'm not sure that this is a permanent solution though, or something that's intended to be temp
so - how should I go about this?
perhaps :
def test_f():
with pytest.raises(AssertionError):
f(3, 4)
would be preferred here.
@cobalt ore you could test if your input parameters are over that certain threshold using a conditional and then use the with pytest.raises as you did before
@fresh blade this is in a test though
The input will definitely be over BC I'm writing a test for it, so I don't get the if statement
I might be missing something though
if ALL your test parameters are over that threshold then there's no need for a conditional,but then the question wouldn't make any sense then
Well I have that one which is, then the one that isn't is in a separate bit
Perhaps i should just iterate and use an if as you suggest
yeah pytest has something called parametrize, idk if uk about it @cobalt ore
I don't 🌚
you can use it to reduce code written drastically
and if you use that, then the conditional will have to be there
Ok interesting, what should I look at for this?
because even though you have you parameters that will fail and that won't separately, the test itself wouldn't know that
Sounds like hypothesis or something
Ok interesting, what should I look at for this?
@cobalt ore pytest docs, but it's pretty difficult to understand at least for me it was
so maybe a few yt videos explaining it
Right, maybe I'll leave it for now then
don't leave it,it's very very useful once you get it
if you don't understand it, just open a help session here
@cobalt ore
pls help in #help-cookie
Does anyone know how to use Selenium to scrape a site?
I'm trying to use it to scrape Facebook's ad library, but their HTML div id's change every day so idk how to keep track of them on a rolling basis
Essentially given a URL like this,
I want to just print out all the Ad start times, their ID, and the link the ad redirects to
Does Facebook allow web scraping?
Use class or id
To scrap ever changing HTML.
Was wondering if anyone here is familiar with selenium bot detention. 🤔 Or know all elements to bypass one.
@fresh blade technically no, but was testing to see if I could pull ads for a data project I'm working on
!rule 5
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.
Is anyone a pytest super user? I've got a suite of tests in a project and I'm wondering if there are any out of the box solutions for aggregating historical test history.
For example, I run my test suites in Jenkins/Drone.io/whatever, and somehow push the result and logs somewhere that keeps track of every time test X was run, failure/success rate over time, etc.
Has anyone used AUTOGRADER with Jupyter or Google Colab?
how do i access this button with webdriver?
the xpath seems to change, but there is nothing unique to identify it with...
Hey guys. I have an issue with a Test Case. https://github.com/johngi-thb/keepy its in the tests.py file. I am asserting that it raises an Exception but the testcase always fails even though I am raising that exception in the kee.py file. Its the third test case in that Test Class.
I don't see any exception being raised
You're catching the exception with try-except rather than raising it
Hello! I'm writing a command line tool that utilizes the PyGithub library. I'm trying to write a test for a function that calls get_hooks()(https://pygithub.readthedocs.io/en/latest/github_objects/Organization.html#github.Organization.Organization.get_hooks) on an instance of Organization. The library returns a github.PaginatedList.PaginatedList of github.Hook.Hook. This function then iterates over each Hook and returns an array of hook.raw_data (which is a json object turned dict)
What would be the best way to go about writing this test? I was thinking of creating some fixtures via .json files and use the mock library to mock the call to raw_data. Is this too convoluted?
Here's what the function being tested looks like:
def invoke(self) -> ListResult:
webhooks = [webhook.raw_data for webhook in self.organization.get_hooks()]
return ListResult(label="Organization webhooks: ", values=webhooks)
how do i access this button with webdriver?
the xpath seems to change, but there is nothing unique to identify it with...
@twin pier you can use the class
Can we ask unittest related questions here
@gentle zephyr Sure can
ok just checking what each channel's purpose was
i see a lot of libraries covering mock testing also some from 2014/15 and im kinda became confused.
i was wondering if anybody could recommend me a python library, i want to do some unit testing with Mocks.
My code is doing HTTP requests to a third party/external API
with http request i basically mean doing a GET request to a external api, or a POST
The Python standard library has unittest and unittest.mock
Another popular choice is pytest, which is 3rd party
I believe there's an extension to pytest which adds nicer support for mocks.
anyone know how to get an image with selenium and put it into a pil img object like this
response = requests.get(url)
img = Image.open(BytesIO(response.content))
but with selenium instead of requests so I can speed it up
you can target the element, get the image url from src and then continue as you are doing
Would it be a good idea to enforce certain attributes to be non-callable when writing custom Mock objects?
I guess I could be pretty lax about writing them since it wouldn't be worth the effort
for json schema validation, is https://python-jsonschema.readthedocs.io/en/stable/# pretty much the defacto tool?
or is there something else that other people typically use?
Beachtastic, just importing JSON and see if throws an error
hello all,
i need regex for end of url /-page-123456.html
need only digits between - and .html
Uhmm, what is automated-testing chat for😅😅
Is it like for automization for like anything?
@autumn finch It's specifically for automated software testing through libraries and frameworks such as unittest or pytest
@autumn finch It's specifically for automated software testing through libraries and frameworks such as
unittestorpytest
@digital grotto hmmm, where do pyautogui, selenium belongs in this server?
Hmmm
@autumn finch pyautogui in #user-interfaces and selenium in #tools-and-devops
but selenium is also used for test automation so it fits here here too sometimes
Wait, there different?!
I've never used pyautogui but afaik it can be used outside browsers too. Selenium can't
Yet another unittest.mock question incoming, how strict do spec'd mocks have to be? I'm basically modelling them after instances of dataclasses and I figured that since I'm able to get the type annotations for the attributes I might as well spec their mocks.
When using requests library I'm only able to use Transparent proxies,
proxies = {
"http": "xxx.xxx.xxx.xxx:8080",
"https": "xxx.xxx.xxx.xxx:8080"
}
url = 'https://google.com'
response = requests.get(url, proxies=proxies)
print(response.content)
Error:
Traceback (most recent call last):
File "c:/Users/Person/Documents/PythonProxy/main.py", line 102, in <module>
response = requests.get(url, proxies=proxies)
File "C:\Users\Person\AppData\Local\Programs\Python\Python38\lib\site-packages\requests\api.py", line 76, in get
return request('get', url, params=params, **kwargs)
File "C:\Users\Person\AppData\Local\Programs\Python\Python38\lib\site-packages\requests\api.py", line 61, in request
return session.request(method=method, url=url, **kwargs)
File "C:\Users\Person\AppData\Local\Programs\Python\Python38\lib\site-packages\requests\sessions.py", line 530, in request
resp = self.send(prep, **send_kwargs)
File "C:\Users\Person\AppData\Local\Programs\Python\Python38\lib\site-packages\requests\sessions.py", line 643, in send
r = adapter.send(request, **kwargs)
File "C:\Users\Person\AppData\Local\Programs\Python\Python38\lib\site-packages\requests\adapters.py", line 510, in send
raise ProxyError(e, request=request)
requests.exceptions.ProxyError: HTTPSConnectionPool(host='google.com', port=443): Max retries exceeded with url: / (Caused by ProxyError('Cannot connect to proxy.', OSError('Tunnel connection failed: 503 Service Unavailable')))
Can someone tell me what I'm doing wrong
I would like to use Elite proxies if I am able to but I cant find any docs or anything about using different types of proxies
i want a script to analyse galaxy images that i download for the web
Trying to seemlessly control a browser
Hey guys, I am trying to log into a google account to access a website for testing and cannot figure it out.
Currently I am using Selenium, although Im not tied to it or anything, and have tried using both Firefox and Chrome.
The exact error I get is "This browser or app may not be secure", since Google does not allow logging into an account even with less secure apps turned on.
Are there any other packages that can log into a Google account? Or my other thought was some how use OAuth2 or something and log in that way?
Thank you guys!
@kindred quarry deepening on what you want to do, maybe Google has an api for it.
Unfortunately all I need from them is to log in, and I do not belive there is an API for that...
What are some frame works for testing ?
I have experienced robot and hate it
I am mostly interesting in testing network infra
are there any frame works that learn on pytest for testing infrastructure ?
how to run multiple web scrapes at once ?
create multiple instances of BeautifulSoup
concurrent.futures.ProcessPoolExecutor
has anyone used opencv?
does anyone know of a way to get my python window to have something that can tell me something has happened like an unread message on social media?
you can probably use the Facebook api for it
i don't need to connect to facebook i need to get a message icon like in facebook
It's platform dependent I'm positive
And tkinter probably doesnt allow such a call, because its more generalised between platforms
I usually use a completely different engine to make desktop apps; try electron and write a python framework for its functions
Has anyone automated twitter account creation?
my accounts get blocked every now and then
!rule 5
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.
that's definitely against the tos
Just want to know how twitter detects fake accounts
@gentle terrace just for knowledge
the rule still stands
okay
so uh
i've written a python program that manages an election, for a preferential ballot system.
i'm asking on the off chance that this is already a known thing, but how do i generate good "random" preferential ballots? (a random list of length n, containing integers from 0 to n, where only 0 may repeat, and represents "unranked")
my current generator takes [i for i in range(n)] and applies random.shuffle(ballot)
and then i've tried working out a way to crop out a random number of values (since not every voter will rank every candidate)
is this good, and are there better ways?
I'm by no means an expert but if you want it to repeat 0 you could have it start at a negative value then you check if there are any negative values in the list and it there are, change them into 0.
There are probably better ways for this like with anything so take this with a grain of salt but this should work regardless.
well for the zeroes actually thank you that's a genius innovation
my ballot object has a process which takes max(i,0) for i in ranks
so in fact i could just feed in:
ranks = [i-k for i in range(n)] # random k
random.shuffle(ranks)
however i would also like to someday introduce party biases, since that's another important part (solving the vote-splitting problem)
umm... I have a simple code and want to know if it would work or not and if there's a method that'll take less time to compute the answer. Which channel should I go to?
noob question about how to kick off pytest via GitHub Actions: https://github.com/AndrewLane/andrew-is-hungry-for-py/issues/7
@blissful slate Can you show your github repo you're trying to test?
We need the directory structure to understand whats going on
directory structure is just like this: ./.vscode/settings.json ./andrew_is_hungry_for_py/eat.py ./andrew_is_hungry_for_py/__init__.py ./LICENSE ./README.md ./requirements.txt ./setup.py ./tests/test_eat.py
@blissful slate ok so as far as I can see, you need a pytest.ini in your root directory
you can use this one https://github.com/IgnisDa/python-random-markdown-generator/blob/master/pytest.ini
Remove addopts since you'll have different plug-ins than i do
cool will take a look at that, thank you
hey there can someone help me out with selenium.. i want to use selenium on windows in android mode...!
can someone help how can that be done
i want to use selenium in the android mode on window.. is there a possible way to do so!
@lean tusk wdym android mode?
selenium isn't supposed to be used on Android
you can obviously resize the window size using selenium to resemble an android screen but that's pretty much it
this is what i mean
@fresh blade what i mean is there is this toggle device toolbar thing is there way to toggle it???
in the script
driver.set_window_size() will get it to any size you want the screen to be @lean tusk
you don't need to play with Chrome itself to achieve that
no its not about the window size it about the upload button that shows up only in android or when i toggle the device toolbar
Can someone help me with getting started on unittest mocking my postgresql database? I have functions written in python that add and remove records from the database. But I would like to test those without actually affecting the database. Anyone experience with mocking?
Can someone help me with getting started on unittest mocking my postgresql database? I have functions written in python that add and remove records from the database. But I would like to test those without actually affecting the database. Anyone experience with mocking?
@proper wind I would like to test my connection to the postgresql database from my python file.
Anyone here looking to help me write some code for $$?
@proper wind we do not allow recruitment
ג
:x: According to my records, this user already has a mute infraction. See infraction #13719.
:incoming_envelope: :ok_hand: applied mute to @twin remnant until 2020-10-15 16:57 (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).
:incoming_envelope: :ok_hand: applied mute to @twin remnant until 2020-10-15 17:33 (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).
I want to use a database mock instead of my database to see if my code logic internally produces the stuff I expect. I have already written my (very first) unittest.mock -testfile but I cannot seem to pass the test. I'm 1000% confident that I have made a mistake while writing the test. Can someone help me out?
already stuck for 5 hours...
Can someone review my unittest? I'm trying to mock my database. and currently I'm checking whether my add function works properly like an insert query
Is there a good library for Mutation, Function, and Unit testing on multiple different, sometimes obscure, operating systems at once (or in sequential order) on a single machine? A repo I'm helping on found that Artix Linux shares a bug with Windows, but not with Ubuntu, even though they're both Linux distros, and that made me want to test out as many different operating systems at once, as this bug can cause the entire program to fail, so we don't want to wait for users to come in and say "hey, this isn't working for me", we'd rather be proactive and prevent that from happening in the first place.
wouldn't docker do the job?
How did you deduce that?
@real aurora 👀
@proper wind 👀
how do i tell selenium to click on a specific word
depends on whether that word has a unique xpath
I'm trying to make a monitor for a squat rack on amazon
but it won't let me make features ='lxml'
and it also recognizing id, even if it's on the page
btw using selenium on Instagram is not legal
@fresh blade lol wtf
what i mean is there is this toggle device toolbar thing is there way to toggle it???
@lean tusk this small button
@fresh blade lol wtf
@gentle birch ?
bruh
@river pilot I wasted a bunch of time the other day trying to figure out why coverage was telling me that lines that I knew for certain were being reached were not covered. Turns out I was misinterpreting the output, because 10-14 would have meant those lines were unreached, but 10->14 meant a branch was unreached. Which, now that I know to look for it, makes enough sense, but it's really subtle and easy to miss if you're not already looking for it. The missing branch would be way more obvious if it was displayed as 14<-10 instead (10-14 would mean "the range from 10 to 14", and 14<-10 would mean "the jump to 14 from 10"). I don't suppose there's any chance that no one depends on parsing that output format and it could be changed? 😄
I'm guessing that's a non-starter, but if it's not then it may be worth giving some thought to.
(thanks for coverage, btw - use it every day!)
@split field it's an interesting idea
tbh, i don't put much energy into coverage these days
tbh, it works well as is; I've used it for a long time without finding any issues!
(there's no :thanks: emoji somehow...)
I'm consistently amazed by anyone who can maintain a popular OSS project and still manage a day job, honestly. I don't know where anyone finds the time.
Hello, I am currently developing a website with Django (more like a tool) and v1.0.0 is near completion but I have no tests. I don’t really know how to get started. Any advice?
Hello, I am currently developing a website with Django (more like a tool) and v1.0.0 is near completion but I have no tests. I don’t really know how to get started. Any advice?
@midnight roost testing Django is a bit involved.
at the very least, test your public API (the views)
with one test per view that asserts that you can access it with valid data and get an okay response back
and a suitable number of tests that assert that you get an appropriate non-okay response with invalid data
Yes, I know testing is involved but I know it’s pretty important so o want to ensure I do it now. The project seems to be growing more and more and I don’t want to have to add tests after I have 60 views but now when I only have 20 or so
But how should I get started? Which package should I use if any? I was looking at the Django documentation and they had some suggestions. Should I just go with that? And to test the views do I just make simple get, post requests and ensure I am receiving a valid response?
pytest-django is nice to use!
with django-webtest, much nicer thant the built-in http test client
- tests for models are regular python unit tests: test that can instantiate one; test that some computer property is what you expect for some fields; test a custom method
- tests for managers/querysets are similar (and it is a django best practice to have more logic in managers than in views): if you write custom filtering or creation methods, test them (setup: create many models, test: call your method, assertions: check that you only get the models you expect)
- tests for views can be exactly unit tests (mock the manager, only check what the view does), or more like functional tests that exercise everything from DB to managers to views to rendering (JSON or HTML conversion) — I find the latter more useful (setup: prepare models in DB, test: send an http request, assertion: check the response + the state of the DB if it was supposed to change)
Why is my SMTP code not working ( the emails are fake but I use real ones for the errors shown below):
File "scratch.py", line 10, in <module>
server.login(senderemail, password)
File "C:\Users\dhruv\AppData\Local\Programs\Python\Python38-32\lib\smtplib.py", line 734, in login
raise lastexception
File "C:\Users\dhruv\AppData\Local\Programs\Python\Python38-32\lib\smtplib.py", line 723, in login
(code, resp) = self.auth(
File "C:\Users\dhruv_\AppData\Local\Programs\Python\Python38-32\lib\smtplib.py", line 646, in auth
raise SMTPAuthenticationError(code, resp)
smtplib.SMTPAuthenticationError: (534, b'5.7.9 Application-specific password required. Learn more at\n5.7.9 https://support.google.com/mail/?p=InvalidSecondFactor x23sm2799418pfc.47 - gsmtp')
Sign in with App Passwords - Google Account Help
Tip: App Passwords aren’t recommended and are unnecessary in most cases. To help keep your account secure, use "Sign in with Google" to connect apps to your Google Account.
An App Password is
Tip: App Passwords aren’t recommended and are unnecessary in most cases. To help keep your account secure, use "Sign in with Google" to connect apps to your Google Account.
An App Password is
@frosty shuttle I really appreciate your feedback! I am going to add this to my to-do. I don't quite understand everything you mentioned but I got most of it.
cheers! I should have said, start with general pytest and webtest docs if you are not familiar. pytest-django sets up settings because django settings are badly designed, and django-webtest give you a nice object to make HTTP request to your app and check responses.
Alright, thanks. Do you mind if I ever shoot you a DM if I get stuck or need some more advise?
sure you can tag me here for generic questions or DM me (but I am not sure about DM permissions, I barely use discord)
Ok thanks
is there a library for mutation testing that, rather than or in addition to testing whether different mutations work, also tells you if any of those mutations are faster?
i'm looking to try and find the optimal value of a chunking parameter for long lists in terms of speed
ping me if you have an answer
For some reason I can't access localStorage with geckodriver or chromedriver
Does anyone know if Selenium can export webdata to excel?
cron?
Could anyone help me with sharing GitHub Actions Workflows across Repos in an Organization? #help-burrito message
Hello folks. I have encountered an unexpected issue with ddt, pytests and kernprof.
I can run and pass all tests I've set up from pytest.
When I try to profile my code, in my Ananconda console I run the usual: kernprof -l -v test_01.py and all JSON loading tests trigger:
raise ValueError(message % file_attr)
ValueError: test_500K.json does not exist```
This is the relevant test:
def test_json3(self, g1, g2, g3, g4, hand_size, num_letters, expected):
return self.do_test(g1, g2, g3, g4, hand_size, num_letters, expected)```
... which works fine within pytest but comes up short when it's triggered by kernprof.
The JSON files are UTF-8, in an NTFS folder, along with sources, LF line separator ...
Any idea?
whats the folder structure look like
I'm guessing that pytest runs from a different working dir than kernprof
so relative paths are resolved differently
@gentle terrace: Everything's in one folder: main module, tests, JSON files. I am running kernprof from that folder.
(naturally I have the same error profiling the function with Spyder)
👋 I'm trying to test the following code
from github import Github
if os.getenv("GITHUB_ENTERPRISE_HOSTNAME"):
base_url = "https://%s/api/v3" % os.getenv("GITHUB_ENTERPRISE_HOSTNAME")
app.extend("github", Github(base_url=base_url, login_or_token=GITHUB_ACCESS_TOKEN))
and I want to write a test that ensures that Github was initialized with the set env
@mock.patch("github.Github", autospec=True)
def test_github_enterprise_env_config(mocker, monkeypatch):
monkeypatch.setenv("GITHUB_ENTERPRISE_HOSTNAME", "github.example.com")
argv = ["github"]
with LauditTest(argv=argv) as app:
mocker.assert_called_once()
However this results in AssertionError: Expected 'Github' to have been called once. Called 0 times.
yea that was exactly it, changed it to @mock.patch("laudit.main.GithubClient", autospec=True), thanks @kind meadow !
hey folks, i'm using pytest and defined some markers which work.. but they were giving me the unregistered marker warning, so i added the makers into the pytest.ini file (like outlined in docs), but it's still throwing the warnings.. what am I missing?
How do I use a list of proxies for selenium?
hello! how i can schedule my scripts to Fixed hour every day
@proper wind could i ask what is automated here?
and its using an app with an ui?
got a question: can I use selenium on a server hosting site
What is a good way of testing HTML output? I want to test whether the output of a function is a particular HTML code, but I don't care how exactly it's structured. For example, bot <div id="hello" class="world"></div> and <div class="world" id=hello ><div/> should both pass the test.
I'm using pytest, if that matters
@fiery arrow hmm, what if you ran a html formatter on the output?
that should give a consistent output
oh wait that might not fix the attr ordering
Just converting them to the same format is a good idea, thanks!
Maybe I can configure a formatter to sort the attributes.
@warm shuttle do you use windwos
hello guys, sorry if i'm using the wrong channel i don't know where to ask
basically i made this python program where i used matplotlib and pandas and mysql.connector and have to send the program to my teacher in but she is unable to install pandas on her device, i was thinking of making a .exe file but then i don't know if my libraries will be adjusted in that.
anybody got any solution??????
i used pyintsaller but the final .exe could not be run (failed to be executed)
Can I get a window title by cursor position in python?
How does this relate to software testing?
Not sure but I’m trying to make the same thing in JS
If there's no clear relation then this is not the appropriate channel for such question
If there's no clear relation then this is not the appropriate channel for such question
@kind meadow I apologise, I thought since selenium is used for web testing purposes, I thought this channel was appropriate... deleting my messages
Yeah it's fine if you were going to use it for testing purposes, but seems you're automating something for the sake of automating it rather than for testing
Better to claim a help channel in that case
Hi guys, sorry, i'm not really sure where else to post this
I'm testing an app that will require users to verify their identity with front facing id, back facing id and a selfie. It's really tedious to do the tests by hand one by one, i'd like to have a few people make videos in different lighting conditions, then I can send those videos to the camera feed of a real android phone and see how the app fares.
I know it's possible to do something like this on PC with ManyCam, where you can send a video to the camera api, I was wondering if there's a similar app or method to achieve the same thing on androids.
I'm trying to test whether my function works.
"""Returns True if s is the same forwards and backwards when ignoring white-space and punctuation, False otherwise"""
These are my tests
print(is_palindrome_ignore("rAceCaR"))
print(is_palindrome_ignore("r a ce car"))
print(is_palindrome_ignore("]r< A=c> e?c @a[r"))
These all return True which is expected. Are there any other ways that I should be testing this function?
@limpid jungle Could you use the images that show up in the google search for "selfie"?
@pulsar canopy could you use hypothesis to generate random test cases
it's been a while since I last used it, but I'm pretty sure it can do that
Is that a module?
@pulsar canopy It's a third-party package, yes
I'm trying to test whether my function works.
"""Returns True if s is the same forwards and backwards when ignoring white-space and punctuation, False otherwise"""These are my tests
print(is_palindrome_ignore("rAceCaR")) print(is_palindrome_ignore("r a ce car")) print(is_palindrome_ignore("]r< A=c> e?c @a[r"))These all return
Truewhich is expected. Are there any other ways that I should be testing this function?
@pulsar canopy you should also test whether it returnsFalsefor things that aren't palindromes
try to think of edge cases.
An edge case could be the empty string.
does anyone know how could i make my clock update every second and print it?
print the updated value
wrong channel @cosmic grotto
ye already fixed
Hey folks, I'm trying to improve my knowledge of the page object model and hopefully implement it in my work.. But i'm honestly struggling to find good resources on it with a solid explanation. I've had a poke around google and read a few blog posts, got a couple courses from Udemy and had a look at some youtube tutorials so far.
@limpid jungle Could you use the images that show up in the google search for "selfie"?
@pulsar canopy
What do you mean?
@limpid jungle I mean instead of asking users of this server to send you selfies, you could use selfies from google images.
anyone have any experience with 2captcha here?
Anyone know the best way to bypass website blocking selenium?
@formal sonnet use a different search engine?
change the user agent @formal sonnet
however,
you should make sure it doesnt break TOS
Anyone know how to input text from a notepad to a website form using selenium
@west pine you could use
element = driver.find_element_by_name("elementname")
element.send_keys("inputtext")
I'm not sure what you mean by notepad
@limpid jungle I mean instead of asking users of this server to send you selfies, you could use selfies from google images.
@pulsar canopy
I wasn't looking for selfies...I was looking for a way to mock the camera app on real android devices. How could you misunderstand so badly?
i'd like to have a few people make videos in different lighting conditions, then I can send those videos to the camera feed of a real android phone and see how the app fares.
@limpid jungle
I know it's possible to do something like this on PC with ManyCam, where you can send a video to the camera api, I was wondering if there's a similar app or method to achieve the same thing on androids.
@limpid jungle
Did you miss this? It's the only other paragraph.
Can anyone help me with this code. When I run it the page just never stops loading.```py
from selenium import webdriver
PATH = "C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)
driver.get('https://zoom.us/')
I'm not sure what you mean by notepad
@neon summit I think they meant Windows Notepad. In that case they can justopenthe file and usereadto save it to a variable.
Can anyone help me with this code. When I run it the page just never stops loading.```py
from selenium import webdriverPATH = "C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)driver.get('https://zoom.us/')
@burnt palm Its working fine for me. Can you try by moving chromedriver to working directory and also check your internet speed.
Hi @idle kindle Try this .
WebDriverWait(self.driver,30).until(expected_conditions.presence_of_element_located((By.LINK_TEXT, "Book")))
self.driver.find_element(By.LINK_TEXT, "Book").click()'''
@fresh sail frick suraj, what's all that
try:
monday = driver.find_element_by_id("ctl00_MainContent_activityGroupsGrid_ctrl12_lnkListCommand")
print("Found monday")
except NoSuchElementException:
print("Monday's not here")
# mondayButton.click()
bookDay(monday)
I'm trying to pass this monday variable to a function that books specific days
Why isn't it working 😬
@idle kindle It clicks on link having Book as link text. You need to import those mentioned module from selenium.
try:
monday = driver.find_element_by_id("ctl00_MainContent_activityGroupsGrid_ctrl12_lnkListCommand").text
print("Found monday")
except NoSuchElementException:
print("Monday's not here")
# mondayButton.click()
bookDay(monday)
@zardoss try this
@idle kindle It clicks on link having Book as link text. You need to import those mentioned module from selenium.
@fresh sail I found it was because monday was retrieving html that wasn't visible yet
Also I'm trying to click a button atm with no luck
Share html screenshot and your code. Let me see if I can help
viewBookings = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.CLASS_NAME, 'btn btn-success'))
)
viewBookings.click()
@fresh sail
viewBookings = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.CLASS_NAME, 'btn btn-success'))
)
print(driver.find_element(By.CLASS_NAME, 'btn btn-success').text)
driver.find_element(By.CLASS_NAME, 'btn btn-success').click()
try this and see what print statement is printing
@idle kindle
You can see the button is hgihlighted in the screenshot
@fresh sail
Yep, you're right @fresh sail
It's all good
Just gotta figure out how to make some sort of GUI so I can have it running and checking at certain times of the day
Also potentially tell me on discord
Are you learning or working on some project ?
@fresh sail Bit of both
Personal project
Just wanna be able to book slots at a library every week
So I don't miss it
cause I've gone a few times and forgot to book and I look in and can see peeps just in there watching netflix
I wanna friggin study
So I'm gonna make something to autobook it every week at the times I want
I'm trying to get ActionChains working with Selenium and I've watched a video on YouTube about automating Cookie Clicker, but I still can't get it to work. I've tried to write the most basic example I can think of, which is just to open YouTube and press CTRL + F, but as soon as the browser opens, Google will yell about cookies and then the window closes.
I have another Selenium script and that works just fine without Google yelling at me. But I want to use ActionChains in that script, so I thought I would test it out and it doesn't work for me at all. At the moment, for pressing keys, I'm using PyAutoGUI but that takes control of my mouse and keyboard, and I don't want that. I want to still be able to use my mouse/keyboard.
Currently, my ActionChains command looks like this:
driver = Chrome.webdriver(executable_path=r"C:\bin\chromedriver.exe")
body = driver.get_element_by_tag_name('body')
chains = ActionChains(driver)
body.send_keys(Keys.CONTROL)
body.send_keys('F')
chains.perform()
is anyone here experienced with writing integration tests???
Selenium is against websites?
yes @proper wind
@idle kindle yeah because of the automation bot init
yeah
selenium is alright for web scraping
as long as we don't use selenium against big companies like facebook we are ok
we can run script on small websites
come on, small websites can't protect themself
i'm not gonna harm them
i'm not like a hacker
it's all just learning purpose
u tell me , u haven't done anything out of order
so you're saying its ok to violate TOS as long as they can't do anything about it
@gentle terrace nah , nah i'm saying i can test script websites , which i can't do anything
i'm not doing anything harm
i'm just seeing if that work or not
if its work then i'm not gonna use it again
because ik it's against
"its ok to break TOS if nothing bad happens"
Right, getting a bit off-topic now.
ok sorry
If i had a question about beautifulsoup web scraping, would I ask it here, or in another text channel?
@chrome bay Quite a lot of Selenium questions got asked a lot here because it automates frontend testing, although this channel fits unit testing and friends better.
do yall know any discord servers where I can ask about beautifulsoup and web scraping specifically?
just put it in #❓|how-to-get-help
plenty of people here know bs4 and can answer your question
hey guys
Hey guys i am having problems with selenium, https://hastebin.com/kewivevoli.lua this piece of code is not working as expected, i do some actions on a website and after that i want to open a new tab and put it in mobile mode, it opens the new tab but it doesn't go into dev options
have you tried appium?
Hi
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
PATH = "C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)
driver.get("https://www.techwithtim.net/")
print("You Have Opened",driver.title)
search = driver.find_element_by_name("s")
search.send_keys("test")
search.send_keys(Keys.RETURN)
try:
main = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "main"))
)
finally:
driver.quit()
print(main.text)
when i run this code it doesnt work can some1 help me
@boreal fox What are you trying to get from techwithtim.net? Also, not sure this fits in #unit-testing... Unless techwithtim hired you to test his website.
E
guys i wanna use a bot for my server that can control my atternos minecraft server but its very very bugged
ill attach the git hub here: https://github.com/Mekolaos/Aternos-On-Discord.git
Im a noob at python 😂
Any help is appreciated
@boreal fox what's the error? Can you elaborate?
Hi I am trying to select from a dropdown menu, however the code is inside a ul class and I cannot use select.
<ul id="ui-id-3" class="ui-menu ui-widget ui-widget-content ui-autocomplete ui-front" style="top: 354.5px; left: 11px; width: 428px; display: none;">
<li class="ui-menu-item">
<div id="ui-id-9" tabindex="-1" class="ui-menu-item-wrapper">Brandon </div></li></ul>```
https://discordapp.com/channels/267624335836053506/267624335836053506/772819042792112139 does anyone know what the problem is?
i keep getting white spaces.
@thorny fable Pretty much what I did for the last 4 years, but it was a pretty specialized environment. I suspect that integration tests in general are going to be pretty environment dependent - in contrast with unit tests, which are suitable for running in isolation, with mock classes or dummy services to fill in where needed.
Has anyone here mocked out ftplib? I’m trying to test some code and having a hard time figuring out how to mock out calls to ftplib
[
{
"name" : "john",
"lastname" : "doe",
"street" : "test123"
},
{
"name": "doe",
"lastname" : "john",
"street" : "idk123"
}
]``` how do I access the street if I already know the "name" value?
So lets say I want to know the street that the person with first name "john" lives in
how do I access the street value?
for x in d:
if x["name"] == "john":
result = x["street"]
break
ty
Hey @proper wind!
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 guys i just finished up my first project ever i have very little knowledge of programming but it seems to be working pretty well I'm searching for things that i can improve if anybody can help!!! thanks in advance
Its basically a bot that join my online lessons so i can sleep coding is very junky all round any help would be appreciated
😯
that's one way to learn python I guess
when theres a will theres a way
hi
passwordsearch.send_keys(Keys.RETURN)```
i want it to press enter here
but it isn't working
Is it free
?
Any advice to get into google
@bold fossil can you send some code here maybe I can help
And can you also send the error
@proper wind can you help me out, im in help-iron but no ones come by 😦
I thought that would be the problem as I had faced it earlier as well
Aur @inland oar
Sure
Thanks man
What's the problem
Basically I have a school project where I have to do analysis on a dataset with hundreds of countries. I want to assign each country a continent but doing it manually would not look good on a report so I tried using SQL. My query was too large so now I am hoping that i could make the changes in a pandas dataframe and export it to excel.
I saw your messages on help iron and I understand what you want to do
We can easily do it using sqlite3
is it free?
Yes it come with python
It is a local db
You can use anything for the project or there are limited conditions?
Anything is good because manipulating the data isnt part of my report, it just preparation before I do stat analysis in R.
So if we enter all the data to SQL dB and check for the country's continent is that ok?
Can I show you what I had in SQL? I was using a switch statement like this and this works its just too large
Sure
UPDATE ProjectDataInAccess
SET Continent =
Switch(
Country = 'Afghanistan', 'Asia',
Country = 'Albania', 'Europe',
Country = 'Algeria', 'Africa',
Country = 'Angola', 'Africa',
Country = 'Antigua and Barbuda', 'North America',
Country = 'Argentina', 'South America',
Yea im open to anything
So your project is to take an input from the user for checking the country's continent
nah, my project is to do a statistical analysis on life expectancy across countries. Before i start my analysis I want to add an artificial continent column so that I could analyze the differences across continents
Theres no input from the user because once the continents are in the dataframe, i just want to export to a csv
So you want to just differentiate between countries continents at first?