#unit-testing

1 messages · Page 20 of 1

fresh blade
#

this is very weird

#

does your file have anything? @nocturne moat

nocturne moat
#

I have created empty directories actually

#

oh wont git accept that?

fresh blade
#

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

nocturne moat
#

oh Im so so sorry for being so dumb

#

thank u so much

fresh blade
#

and an initial commit without any files actually commited is kinda useless too

#

you're welcome

nocturne moat
#

yes indeed , Ill have to be more aware , really sorry for such a dumb question

inland sleet
#

Asked a question in #help-pie in case anyone can help with a Robot question

inland sleet
#

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.```
fiery musk
#

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

proud oyster
#

you make a fake site for testing

proud nebula
#

The best way is to not do it at all if at all possible.

inland sleet
#

can't you use a mock library to mock a server?

fiery musk
#

hm, right

thin gazelle
#
<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.

urban burrow
#

Anyone know how I can have a pytest fixture act like a context manager (executing code on test finish)?

fresh blade
#

@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.

urban burrow
#

@fresh blade would something like this be accurate?

@pytest.fixture
def blah() -> str:
  yield "hi"
  print("teardown")

Edit: tested. It works 🙂 Thanks a lot!

sick valve
#

[nevermind i repair it]

cursive minnow
#

im testing discord on my raspberry pi 4b

#

it worss

#

works*

royal pivot
#
- 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
 ```
mystic viper
#

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 🙂

fresh blade
#

Do i really need tox if I am testing against a single python and django version?

digital grotto
#

Probably not

balmy saffron
#

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.

proud nebula
#

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.

regal laurel
#

!eval print("hm..")

bitter wadiBOT
#

You are not allowed to use that command here. Please use the #bot-commands channel instead.

regal laurel
#

oh swoy

fresh blade
#

thanks @proud nebula @balmy saffron @digital grotto

proper wind
#

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

gentle terrace
#

find element by ID with "useremail"?

#

@proper wind

#

also check if it's spelled correctly

#

and post code

bitter wadiBOT
#

You are not allowed to use that command here. Please use the #bot-commands channel instead.

bitter wadiBOT
frozen ore
#

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?

frozen ore
#

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'

glass tendon
#

Looks like you don’t have the library installed

#

If you use Linux, just type “pip install pyinstaller” @frozen ore

gentle terrace
#

wouldn't that mean he couldn't build it in the first place

#

So idt that's the issue

kind meadow
#

This is completely the wrong channel for such question anyway

frozen ore
#

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

kind meadow
#

a general help channel, I mean

balmy saffron
#

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 ^

tiny widget
#

@balmy saffron maybe python -m tests?

balmy saffron
#

/usr/bin/python: No module named tests.__main__; 'tests' is a package and cannot be directly executed

tiny widget
#

Right

#

Is the not found module django.tests?

balmy saffron
#

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

tiny widget
#

Great

#

Yeah, you should open an issue

balmy saffron
#

Oh....

#

DJANGO_SETTINGS_MODULE=tests.settings python -m unittest gives me ModuleNotFoundError: No module named 'promise' ... Ironically, that is very promising xD

tiny widget
#

Is it haha

#

I guess you can activate the audit for imports, and trace the problem a bit better

balmy saffron
#

I set up a venv and am installing dependencies.

fresh blade
#

DJANGO_SETTINGS_MODULE=tests.settings python -m unittest gives me ModuleNotFoundError: No module named 'promise' ... Ironically, that is very promising xD
@balmy saffron looks like adriane is a dependency, their requirements.txt specify it

balmy saffron
#

Aye, I know. The dependencies are not the problem lemon_sweat

sterile reef
#

in selenium i have 2 class with same name i want to work with the 2nd class how do i do that??

proud nebula
#

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.

frank jewel
#

can someone help me convert python script to exe file

wintry raft
#

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

stuck helm
carmine bay
#

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
heady iris
#

is tdd standard when working in the enterprise?

carmine bay
#

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

heady iris
#

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.

urban burrow
#

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..

urban burrow
#

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

fresh blade
#

if you are using pytest, it has a coverage extension.

#

so you can use that instead

urban burrow
#

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 >

fresh blade
#

that's quite weird since I use travis too and it works fine for me

proud nebula
#

@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.

heady iris
#

@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

proud nebula
#

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.

sinful wind
#

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.

fresh blade
#

if you don't find testing hard, you might want to get yourself seen by a psychologist

sinful wind
#

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?

fresh blade
#

I don't use selenium at all, but you should probably be using selenium to test buttons and the likes

sinful wind
#

ah so it is tested manually?

fresh blade
#

Returned html can be tested using django's client easily

sinful wind
#

thanks, long road ahead of me

proud nebula
#

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!

sinful wind
#

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__

proud nebula
#

That seems like not a very useful test to me.

fresh blade
#

@sinful wind self.assertEquals(found.func.view_class, auth_views.LoginView.as_view()) is the correct way

proud nebula
#

Comparing equality between two generated functions won't work right?

fresh blade
#

idk what that means, but this works. I copied it from an old project

sinful wind
#

@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

fresh blade
#

that is a valid test

proud nebula
#

@fresh blade strange. I wouldn't do that.

fresh blade
#

ehh worked for me, so I'm not complaining

proud nebula
#

I think it's a silly and useless test :)

fresh blade
#

:)

proud nebula
#

You already have a list of urls to views. urls.py

sinful wind
#

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..

fresh blade
#

yeah and getting the perfect coverage feels really good ngl

sinful wind
#

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

proud nebula
#

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.

sinful wind
#

so in similar fashion, should I test if view gets correct template?

fresh blade
#

why not? it's just a few extra assert statements. it doesn't hurt

sinful wind
#

is there maybe online some resource about testing django? some lists with point what should be tested in view/model etc

fresh blade
#

when I started testing i couldn't find any good resources. if you find one, please do. share it with me.

sinful wind
#

I will keep that in mind

#

thanks a lot guys

proud nebula
#

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.

sinful wind
#

thanks a lot for advice

proud nebula
#

A lot of my advice is "work for a few years and get hard earned experience" :)

#

The answer is almost always "it depends"

fallow jasper
#

Does anyone want to test my Software 😂 (Hangman, Binary Converter and HiLo Number Guessing Game)

austere warren
#

Hangman hm...

proud nebula
#

No. This is for discussing testing.

fallow jasper
#

I realised that 😂

viscid crown
#

How to test my code in selenium. I am new for selenium Please guide me !

manic yew
#

Guys how could i get my computer audio?? (obs: its not the microphone)
like in real time

urban burrow
fresh blade
#

maybe raise an issue in pytest github if it isn't solved?

urban burrow
#

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.

fresh blade
#

wait a minute

#

let me give you my pytest.ini,maybe try if that works? @urban burrow

willow stream
#

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

urban burrow
#

Sure! Is there some sort of config that allows it to.. well work?

fresh blade
#

idk but mine is a bit different

urban burrow
#

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

fresh blade
#

umm lol

#

you're welcome

proud nebula
#

@urban burrow you could fix the error message and submit a PR

urban burrow
#

@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.

digital grotto
#

When it would be appropriate to test the __str__ dunder of an object, or at least in my case, various wrapper/container classes?

proud nebula
#

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.

digital grotto
#

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

proud nebula
#

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.

near lance
#

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.

proud nebula
#

Could also be internal but useful to check for other reasons

placid vigil
#

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

fresh blade
#

@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

placid vigil
#

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

fresh blade
#

@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?

placid vigil
#

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

fresh blade
#

@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

placid vigil
#

(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?

fresh blade
#

oh you're on windows?

#

i dont have much experience with it

#

but yeah you're correct i think

placid vigil
#

thats what i thought too, but i just get a message it cant find the path specificed

fresh blade
#

@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

placid vigil
#

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

fresh blade
#

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

placid vigil
#

: ( ah i see

#

im trying to use Cygwin atm, but that might not work then

placid vigil
#

if i get wsl to work as you mentioned, could that still be a solution?

fresh blade
#

Yeah its supposed to be a complete linux subsystem within windows so I suppose it should

#

Make sure you go with ubuntu though

placid vigil
#

okey, ill try
thanks

placid vigil
#

idk what happened, DIV2K is in that folder

fresh blade
#

came this far
@placid vigil Looks like you need super user access afterall. Try sudo sh get_data.sh

gentle terrace
#

@placid vigil are you using double [[?

#

because sh doesn't support that, only bash does

#

just post your script here

shy condor
#

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

gentle terrace
#

pyinstaller

#

@shy condor

shy condor
#

It doesn't work with pyttsx3

manic yew
gentle zephyr
#

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?

proud nebula
#

You can make any name point to any new object any time. A class definition is just that.

gentle zephyr
#

no i meant like the class itself

#

and i got my answer @proud nebula but thx

proud nebula
#

Yea a class is just the assignment of a created type assigned to a name.

gentle zephyr
#

i was getting all kinds of problems giving a test class the same e as a class

proud nebula
#

Well yes. Overwriting gets confusing. Don't do that :)

gentle zephyr
#

ye thankfully i got helped

proper wind
#

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

gentle parrot
#

@proper wind "needs more testing"? works4me

proper wind
#

it doesn't with some

#

im using 3.8 idle

gentle parrot
#

IDLE is.. not very good. you can't count on it acting like a real terminal, including coloring text

proper wind
#

but it doesn't recognize colorama

gentle parrot
#

"it"?

proper wind
#

might use vis studio

#

"it" is idle

gentle parrot
#

yes, IDLE isnt' very good

proper wind
#

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

proud nebula
#

This channel is for testing. Try a help channel.

strong yarrow
#

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

fresh blade
#
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)
bitter wadiBOT
#

You are not allowed to use that command here. Please use the #bot-commands channel instead.

fresh blade
#

@strong yarrow

strong yarrow
#

oh, that's good

#

thank you!

fresh blade
#

yw

untold vapor
#

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 🙂

fresh blade
#

@untold vapor why not use a CI? Travis would be great.

gray hawk
#

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

untold vapor
#

@fresh blade hm?

fresh blade
#

@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

untold vapor
#

so like

#

completely another user pc

#

without another user pc

fresh blade
#

just look it up, you'll find better answers on the internet than I can supply.

#

it might just be what you need

untold vapor
#

ok thanks

proper wind
proper wind
#

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()
terse fog
#

I think you'll want r.choices

proper wind
#

oh, i'll try that

rose jungle
#

choice only uses 1 argument afaik

#
from random import *
print(choice([1,2,3,4,5,6,7,8,9]))
proper wind
#

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)

rose jungle
#

then its r.choices(10, roles)

#

just swap the arguments

#

should work

proper wind
#

it says object of type 'int' has no len() @rose jungle

rose jungle
#

cant you just use the python interpreter?

#

but it did worked here tho

proper wind
#

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)
terse fog
#

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?

proper wind
#

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

terse fog
#

try:
roles = ["Snake", "Snake", "Snake", "Snake", "Snake", "Snake", "Snake", "Snake", "Snake", "Python"]

proper wind
#

['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 . . .

terse fog
#

Without commas the strings get concatenated

proper wind
#

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?

terse fog
#

" ".join(['Purple', ' looks at something, and then makes an escape.'])

#

What ever is printing the result

#

put it in print(" ".join(____))

proper wind
#

print(" ".join((plyrChosen) (plyrEscape)))

'list' object is not callable

#

i tried with a comma and it said it only takes 1 argument

proper wind
#

?

digital grotto
#

@proper wind Not the appropriate channel for these types of questions. Software testing is about automated testing through tools such as unittest or pytest

proper wind
#

What would you reccomend? @digital grotto

digital grotto
bitter wadiBOT
#

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:

https://paste.pythondiscord.com

quasi sequoia
#

oof

#

how is it?

#

can you pls run and tell?

proud nebula
#

@quasi sequoia this is the wrong channel. And you really should look up enumerate() and str.lower(). Your code is much too complex.

quasi sequoia
#

like?

#

pls

#

tel

trail charm
#

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?

proud nebula
#

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)

pearl cliff
#

@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

gentle zephyr
#

what is this channel about

fresh blade
#

see the sidebar

gentle zephyr
#

whihc sidebar

fresh blade
#

or top bar if you're on pc

gentle zephyr
#

ohhhhh, wdym by our applications and libraries

#

is this kinda like share your projects thing

fresh blade
#

nope, testing is a major concept in programming wherein you test that your code works as expected.

#

this channel is basically for that

digital grotto
#

is this kinda like share your projects thing
@gentle zephyr It's not. It's about the practice of testing software through tools like unittest or pytest.

gentle zephyr
#

ohhh i see

proper wind
#

ok

proud nebula
#

I hope the rename of this channel fixes things.

gentle zephyr
#

ohhh this channel is dead

dawn frost
#

Lol

tiny widget
#

We renamed it to bring it back from the deads though

fresh blade
#

people use it as and when required, why would it be dead?

faint void
#

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...

unreal dome
#

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?

proud nebula
#

@faint void hmm... Seems weird. Would seem more reasonable to make a separate package in that case.

faint void
#

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

proud nebula
#

Maybe more like a playground?

faint void
#

Yeah that's a nice name, thanks lol

proud nebula
#

Naming things. It's one of those things 20 years of experience does help with ;)

#

Off by one and cache invalidation less so :(

desert sluice
#

So I am trying to do unit testing in python and I am confused by how the setUp() class is implemented. Can anyone explain?

proud nebula
#

You should probably be more specific. It's called before the test functions are run. The implementation doesn't seem very relevant?

pearl cliff
#

the idea is that you can assign stuff to self in setUp, for use in tests within that class

willow stream
#

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

magic dawn
#

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

willow stream
#

Grumble

#

Thank you sir, I was so used to sublime showing me purple highlights, I must have missed one

proud nebula
#

Hah. Asks for ruby help on a python server. Gets great help 😂

digital grotto
#

Hastebin probably misidentified the language lol, seems like a unittest test just fine

proud nebula
#

Wat. Hmm. Strange.

willow stream
#

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

fresh blade
#

hastebin often misidentifies languages

#

I've gotten cpp on a python file

turbid walrus
#

selenium: my code crashes when i try to declare form_button ( https://bpa.st/6JNQ ), says Unable to locate element, any advice?

forest fractal
#

I do not not know what you are trying to do?

proper wind
#

you should try to enable the cookies of that site

forest fractal
#

are you just trying to open the page

proper wind
#

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

forest fractal
#

so you are just doing ```python
driver.get(URL)

proper wind
#

which site are you trying to go to?

forest fractal
#

u right
@proper wind What is the URL or is it private?

proper wind
#

kk

forest fractal
#

So the site opens then you click on an element and get the error?

proper wind
#

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

#

?

forest fractal
#

is there a splash screen on that page?

proper wind
#

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

forest fractal
#

what is selenium?
@proper wind it is a automation tool

proper wind
#

ohhh

#

lol

#

try explorer bruh

#

there is a much higher chance for success there

forest fractal
#

You know what I think could be the issue here? Your Firefox version

#

which geckodriver did you download?

#

which version

proper wind
#

did the explorer work?

#

ohk

forest fractal
#

just try with chromedriver as a test dude

proper wind
#

he doent have chrome bruh

forest fractal
proper wind
#

he dont "like it"

forest fractal
#

I know he does not like it but it is just for a test

proper wind
#

what are these drivers used for tho?

forest fractal
#

are you on windows?

#

I assume you are

proper wind
#

i guess bcz he has edge

#

and almost nobody downloads edge seperately

forest fractal
#

then the download should still be in your downloads folder

proper wind
#

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

forest fractal
#

download that version I posted

#

cool

proper wind
#

but you can use it for testing dude

#

even without an account 🙂

#

they dont

#

how would you know?

#

is it a site?

forest fractal
#

I think a lot of companies would not choose to automate with Chromedriver if they did that

proper wind
#

ok

forest fractal
#

I work for a major corporation and we use Google

proper wind
#

the ip address is not found

#

it says this

#

ik

#

i did

#

ok

forest fractal
#

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?

proper wind
#

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?

forest fractal
#

Google has multiple revenue streams

proper wind
#

yes it does

#

cross platform treaties

#

contributers

#

apple respects privacy
@proper wind and apple earns the same amount every minute

forest fractal
#

I am wondering are you clicking a link or a button?

#

Print the url

proper wind
#

okok

forest fractal
#

Or copy the url

#

Take it to your normal browser and execute it

#

what does it say?

proper wind
#

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

forest fractal
shadow warren
#

@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

glossy crane
#

I am quit new where can I post my question about selenium?

shadow warren
#

ngl not sure ; won't harm to ask in the asking area though

fresh blade
#

I am quit new where can I post my question about selenium?
@glossy crane This channel is fine

glossy crane
#

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.

wise fox
#

paste the link and we I will try to give you the selector @glossy crane

proper wind
#

@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

gentle terrace
#

but half of that isn't code

proper wind
#

ik

#

i was just showing him how it would look

magic dawn
#

i was just showing him how it would look
@proper wind but it shouldn't look like that...only the code part.

proper wind
#

k sry i lose

#

it was just an example

faint solstice
#

hi

#

i wrote a short program and there are a def which pops without calling

fresh blade
#

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 ?

potent badge
#

hey which text channel would be fitting to ask about the subprocess module

gentle terrace
willow stream
#

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

willow stream
#

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 😦

fresh blade
#

@willow stream selenium has explicit waits built in, maybe look into them?

willow stream
#

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

jaunty hearth
#

@willow stream on the topic of selenium, have you tried helium?

willow stream
#

I've not @jaunty hearth but the front page of github looks verrry interesting. I'll chunk into it tomorrow I think. Thanks kindly

jaunty hearth
#

np :)

proud nebula
#

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)

glossy crane
#

@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.

proper wind
#

which site?

glossy crane
#
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.

slender zealot
#

Ahh, this seems to be the spot. Anyone aware of bot detetion?

jaunty hearth
#

uhm?

heady python
#

does unittest have any way to run a callable before each test method is ran?

#

a callback would work too

fresh blade
#

@heady python classes have a def setUp method which runs before every test case

heady python
#

test case as in each method that runs a test, or the class itself

fresh blade
#

each method. look into the unittest docs. it has many hooks like this

heady python
#

perfect

#

thanks

digital grotto
#

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.

fresh blade
#

won't pytest's parametrize do the trick?

magic dawn
#

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

digital grotto
#

Seems fair

cobalt ore
#

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.

fresh blade
#

@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

cobalt ore
#

@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

fresh blade
#

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

cobalt ore
#

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

fresh blade
#

yeah pytest has something called parametrize, idk if uk about it @cobalt ore

cobalt ore
#

I don't 🌚

fresh blade
#

you can use it to reduce code written drastically

#

and if you use that, then the conditional will have to be there

cobalt ore
#

Ok interesting, what should I look at for this?

fresh blade
#

because even though you have you parameters that will fail and that won't separately, the test itself wouldn't know that

cobalt ore
#

Sounds like hypothesis or something

fresh blade
#

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

cobalt ore
#

Right, maybe I'll leave it for now then

fresh blade
#

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

cobalt ore
#

Cool, I have to land stuff this afternoon tho

#

So, for now I'll leave it 😅

proper wind
placid mica
#

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

fresh blade
#

Does Facebook allow web scraping?

slender zealot
#

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.

placid mica
#

@fresh blade technically no, but was testing to see if I could pull ads for a data project I'm working on

fresh blade
#

!rule 5

bitter wadiBOT
#

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.

brave dock
#

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.

dense lodge
#

Has anyone used AUTOGRADER with Jupyter or Google Colab?

twin pier
#

how do i access this button with webdriver?
the xpath seems to change, but there is nothing unique to identify it with...

proper wind
#

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.

kind meadow
#

I don't see any exception being raised

#

You're catching the exception with try-except rather than raising it

brittle nova
#

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)
slender zealot
#

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

gentle zephyr
#

Can we ask unittest related questions here

digital grotto
#

@gentle zephyr Sure can

gentle zephyr
#

ok just checking what each channel's purpose was

umbral kernel
#

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

kind meadow
#

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.

tacit stump
#

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

fresh blade
#

you can target the element, get the image url from src and then continue as you are doing

digital grotto
#

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

unkempt linden
#

or is there something else that other people typically use?

proud oyster
#

Beachtastic, just importing JSON and see if throws an error

keen crow
#

hello all,
i need regex for end of url /-page-123456.html
need only digits between - and .html

keen crow
#

any fastcode

#

?

autumn finch
#

Uhmm, what is automated-testing chat for😅😅

#

Is it like for automization for like anything?

digital grotto
#

@autumn finch It's specifically for automated software testing through libraries and frameworks such as unittest or pytest

autumn finch
#

@autumn finch It's specifically for automated software testing through libraries and frameworks such as unittest or pytest
@digital grotto hmmm, where do pyautogui, selenium belongs in this server?

#

Hmmm

fresh blade
#

but selenium is also used for test automation so it fits here here too sometimes

autumn finch
#

Wait, there different?!

fresh blade
#

I've never used pyautogui but afaik it can be used outside browsers too. Selenium can't

digital grotto
#

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.

vale ice
#

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

mystic musk
#

hello

#

I have come bearing a question

#

there is a select input

#

nvm got it

pure tulip
#

i want a script to analyse galaxy images that i download for the web

kindred quarry
#

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!

fresh blade
#

@kindred quarry deepening on what you want to do, maybe Google has an api for it.

kindred quarry
#

Unfortunately all I need from them is to log in, and I do not belive there is an API for that...

thin harness
#

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 ?

tacit stump
#

how to run multiple web scrapes at once ?

fresh blade
#

create multiple instances of BeautifulSoup

gentle terrace
#

concurrent.futures.ProcessPoolExecutor

sullen topaz
#

has anyone used opencv?

proper wind
#

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?

fresh blade
#

you can probably use the Facebook api for it

proper wind
#

i don't need to connect to facebook i need to get a message icon like in facebook

opal hamlet
#

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

patent bridge
#

Has anyone automated twitter account creation?

#

my accounts get blocked every now and then

gentle terrace
#

!rule 5

bitter wadiBOT
#

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.

gentle terrace
#

that's definitely against the tos

patent bridge
#

Just want to know how twitter detects fake accounts

#

@gentle terrace just for knowledge

fresh blade
#

the rule still stands

patent bridge
#

okay

peak vault
#

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?

random bramble
#

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.

peak vault
#

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)

old night
#

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?

blissful slate
fresh blade
#

@blissful slate Can you show your github repo you're trying to test?

#

We need the directory structure to understand whats going on

blissful slate
#

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

fresh blade
#

@blissful slate ok so as far as I can see, you need a pytest.ini in your root directory

#

Remove addopts since you'll have different plug-ins than i do

blissful slate
#

cool will take a look at that, thank you

lean tusk
#

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!

fresh blade
#

@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

lean tusk
#

@fresh blade what i mean is there is this toggle device toolbar thing is there way to toggle it???

#

in the script

fresh blade
#

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

lean tusk
#

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

fresh blade
#

btw using selenium on Instagram is not legal

proper wind
#

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.

proper wind
#

Anyone here looking to help me write some code for $$?

agile kestrel
#

@proper wind we do not allow recruitment

proper wind
#

ok sorry

#

how come?

twin remnant
#

ג

bitter wadiBOT
#

: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).

twin remnant
#

,ע,ע,עע

#

ע

#

ע

bitter wadiBOT
#

: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).

proper wind
#

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...

proper wind
#

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

spring brook
#

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.

fresh blade
#

wouldn't docker do the job?

spring brook
#

what's docker?

#

oh

#

is it easier than virtual machines?

real aurora
#

heres an image comparing docker to a hypervisor

spring brook
#

oh

#

looks like containers are more direct then

#

thanks for the image!

fresh blade
#

How did you deduce that?

proper wind
#

@real aurora 👀

real aurora
#

@proper wind 👀

winter tiger
#

how do i tell selenium to click on a specific word

fresh blade
#

depends on whether that word has a unique xpath

nova briar
#

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

gentle birch
#

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
#

@fresh blade lol wtf
@gentle birch ?

gentle birch
#

i didnt know that selenium on instagram is illegal

#

how do you know that?

fresh blade
#

@gentle birch

#

read the Last 2 lines

#

everything is disallowed

gentle birch
#

bruh

split field
#

@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!)

river pilot
#

@split field it's an interesting idea

#

tbh, i don't put much energy into coverage these days

split field
#

tbh, it works well as is; I've used it for a long time without finding any issues!

river pilot
#

(there's no :thanks: emoji somehow...)

split field
#

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.

midnight roost
#

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?

magic dawn
#

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

midnight roost
#

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?

frosty shuttle
#

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)
whole shuttle
#

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

midnight roost
#

@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.

frosty shuttle
#

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.

midnight roost
#

Alright, thanks. Do you mind if I ever shoot you a DM if I get stuck or need some more advise?

frosty shuttle
#

sure you can tag me here for generic questions or DM me (but I am not sure about DM permissions, I barely use discord)

midnight roost
#

Ok thanks

spring brook
#

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

proper wind
#

For some reason I can't access localStorage with geckodriver or chromedriver

peak prawn
#

Does anyone know if Selenium can export webdata to excel?

proper wind
#

its an automation

lunar basalt
#

cron?

radiant sigil
#

Could anyone help me with sharing GitHub Actions Workflows across Repos in an Organization? #help-burrito message

proper wind
#

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?

gentle terrace
#

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

proper wind
#

@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)

brittle nova
#

👋 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.

brittle nova
#

yea that was exactly it, changed it to @mock.patch("laudit.main.GithubClient", autospec=True), thanks @kind meadow !

meager smelt
#

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?

proper wind
#

How do I use a list of proxies for selenium?

warm shuttle
#

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?

proper wind
#

got a question: can I use selenium on a server hosting site

fiery arrow
#

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

gentle terrace
#

@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

fiery arrow
#

Just converting them to the same format is a good idea, thanks!

#

Maybe I can configure a formatter to sort the attributes.

proper wind
#

@warm shuttle do you use windwos

proper mason
#

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)

light geyser
#

Can I get a window title by cursor position in python?

fresh blade
#

@proper mason Maybe docker?

#

or perhaps thatd be overkill

kind meadow
#

How does this relate to software testing?

remote skiff
#

Not sure but I’m trying to make the same thing in JS

kind meadow
#

If there's no clear relation then this is not the appropriate channel for such question

strange pecan
#

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

kind meadow
#

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

fresh blade
fluid garden
#

Can anyone help me in unittest

#

?

limpid jungle
#

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.

pulsar canopy
#

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"?

gentle terrace
#

@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

pulsar canopy
#

Is that a module?

digital grotto
#

@pulsar canopy It's a third-party package, yes

magic dawn
#

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?
@pulsar canopy you should also test whether it returns False for things that aren't palindromes

#

try to think of edge cases.

pulsar canopy
#

An edge case could be the empty string.

cosmic grotto
#

does anyone know how could i make my clock update every second and print it?
print the updated value

gentle terrace
#

wrong channel @cosmic grotto

cosmic grotto
#

ye already fixed

meager smelt
#

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
#

@limpid jungle Could you use the images that show up in the google search for "selfie"?
@pulsar canopy
What do you mean?

pulsar canopy
#

@limpid jungle I mean instead of asking users of this server to send you selfies, you could use selfies from google images.

jaunty goblet
#

anyone have any experience with 2captcha here?

formal sonnet
#

Anyone know the best way to bypass website blocking selenium?

proper wind
#

@formal sonnet use a different search engine?

gentle terrace
#

change the user agent @formal sonnet

#

however,

#

you should make sure it doesnt break TOS

west pine
#

Anyone know how to input text from a notepad to a website form using selenium

neon summit
#

@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
#

@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?

pulsar canopy
#

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

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.

burnt palm
#

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/')

fresh blade
#

I'm not sure what you mean by notepad
@neon summit I think they meant Windows Notepad. In that case they can just open the file and use read to save it to a variable.

fresh sail
#

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/')

@burnt palm Its working fine for me. Can you try by moving chromedriver to working directory and also check your internet speed.

tidal minnow
proper wind
#

hi

#

we looking to add test to company code 🙂

#

we using rest_framework

idle kindle
#

How do I click this button using selenium?

fresh sail
#

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()'''

idle kindle
#

@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 😬

fresh sail
#

@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
#

@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

fresh sail
#

Share html screenshot and your code. Let me see if I can help

idle kindle
#
viewBookings = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.CLASS_NAME, 'btn btn-success'))
        )
        viewBookings.click()
#

@fresh sail

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

idle kindle
#

@fresh sail

#

No luck

fresh sail
#

what it is printing ?

#

okay , May be you are selecting incorrect id

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

fresh sail
#

Are you learning or working on some project ?

idle kindle
#

@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

fresh sail
#

Use cron jobs to autmatate this

#

Good luck and happy learning

proper wind
#

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()
thorny fable
#

is anyone here experienced with writing integration tests???

proper wind
#

Selenium is against websites?

idle kindle
#

yes @proper wind

proper wind
#

@idle kindle yeah because of the automation bot init

idle kindle
#

yeah

proper wind
#

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

idle kindle
#

why cant I automate things on big websites

#

its not illegal

gentle terrace
#

just check if it breaks TOS

#

but that applies to all sites, big or small

proper wind
#

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

gentle terrace
#

so you're saying its ok to violate TOS as long as they can't do anything about it

proper wind
#

@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

gentle terrace
#

"its ok to break TOS if nothing bad happens"

proper wind
#

yeah whats wrong , it's not like i'm hacking

#

i'm just testing

digital grotto
#

Right, getting a bit off-topic now.

proper wind
#

ok sorry

chrome bay
#

If i had a question about beautifulsoup web scraping, would I ask it here, or in another text channel?

digital grotto
#

@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.

chrome bay
#

do yall know any discord servers where I can ask about beautifulsoup and web scraping specifically?

gentle terrace
#

plenty of people here know bs4 and can answer your question

hasty oasis
#

hey guys

proper wind
#

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

regal mesa
#

have you tried appium?

dawn blade
#

Hi

boreal fox
#

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

fiery arrow
#

@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.

remote sage
#

E

glad loom
fresh blade
#

@boreal fox what's the error? Can you elaborate?

humble aurora
#

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>```
proper wind
#

wha

#

whar

proper wind
#

i keep getting white spaces.

craggy mortar
#

@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.

proper wind
#

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

runic pecan
#
[
    {
    "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?

gentle terrace
#
for x in d:
  if x["name"] == "john":
    result = x["street"]
    break
runic pecan
#

ty

bitter wadiBOT
#

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:

https://paste.pythondiscord.com

buoyant wedge
#

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

junior magnet
#

😯

fiery cove
#

that's one way to learn python I guess

proper wind
#

when theres a will theres a way

bold fossil
#

hi

#
passwordsearch.send_keys(Keys.RETURN)```
#

i want it to press enter here

#

but it isn't working

noble raptor
#

Is it free

gentle terrace
#

?

noble raptor
#

Any advice to get into google

proper wind
#

@bold fossil can you send some code here maybe I can help

#

And can you also send the error

bold fossil
#

i asked in help

#

i got it but thanks anyways

#

i didn't import keys 🤦

inland oar
#

@proper wind can you help me out, im in help-iron but no ones come by 😦

proper wind
#

I thought that would be the problem as I had faced it earlier as well

#

Aur @inland oar

#

Sure

inland oar
#

Thanks man

proper wind
#

What's the problem

inland oar
#

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.

proper wind
#

I saw your messages on help iron and I understand what you want to do

#

We can easily do it using sqlite3

inland oar
#

is it free?

proper wind
#

Yes it come with python

#

It is a local db

#

You can use anything for the project or there are limited conditions?

inland oar
#

Anything is good because manipulating the data isnt part of my report, it just preparation before I do stat analysis in R.

proper wind
#

So if we enter all the data to SQL dB and check for the country's continent is that ok?

inland oar
#

Can I show you what I had in SQL? I was using a switch statement like this and this works its just too large

proper wind
#

Sure

inland oar
#

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

proper wind
#

So your project is to take an input from the user for checking the country's continent

inland oar
#

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

proper wind
#

So you want to just differentiate between countries continents at first?