#unit-testing

1 messages ยท Page 21 of 1

inland oar
#

i have a list that I made already, basically the format I posted above but for all of my countries.

#

See the problem is that each country has like 20 lines and I have like 300+ countries so Id rather have python or SQL do something like if country = afghanistan then Asia

proper wind
#

Yes that's what I have in mind

inland oar
#

cool cool

proper wind
#

We can first insert all countries from a text file to SQL dB maybe

inland oar
#

Sure how can i start>

proper wind
#

Hmm what kind of file do you have all the countries in

inland oar
#

This is a google doc with the code i used in SQL but it has all of the countries and the assigned continent

proper wind
#

Can you give the access I have requested for the access to the file

inland oar
#

Im sorry, I think i changed it to anyone with link can view

proper wind
#

Ok I got it

inland oar
#

Cool thanks

proper wind
#

What we can do is we can make a table with two columns first continent and country

#

No no no

#

We can also make a table for each continent how would that be?

inland oar
#

sure, make the table in where though? Like a dictionary in python or a table in excel?

proper wind
#

SQL table

#

Table in SQL.db file

#

Before that we need to make a list for all the countries for inserting them automatically

inland oar
#

How do I launch that? I only have experience in access and razorsql. But im down to figure out Sqllite3

proper wind
#

Then after inserting the data it will be able to differentiate between continents for a country

#

Sqlite3 is the simplest dB I have seen till now I don't know about razor SQL but i am pretty sure this would be easy

inland oar
#

sure is it just an import for python?

proper wind
#

Yes you don't need to install any libraries

inland oar
#

is it alright if I do it from a jupyter notebook?

proper wind
#

I don't have any experience in juoyter notebook

#

I don't even know what it is I haven't tried it yet

inland oar
#

It looks like its working in my notebook, im gonna try to make the table

proper wind
#

So first make the table and make the values country and continent

#

Then make a list with country and continent like this [(country 1,continent1),(country2, continent 2)]

inland oar
proper wind
#

Yes that's great

#

Remember to add conn.commit and c.close at the end or you might get lock errors

#

Then make a list with country and continent like this [(country 1,continent1),(country2, continent 2)]
@proper wind

inland oar
#

Ok im gonna try it out

proper wind
#

@inland oar wait a minute

#

I have found a library which tells you what continent it is by giving in the country

#

Is this allowed for you?

inland oar
#

Yes thats fine

#

I can use anything pretty much because she isnt grading this part, only my stats analysis in R.

proper wind
#

You should comment out create table

#

That should work

inland oar
#

yup, should I continue adding in the rest of them, its gonna take me a while to go through all of them though sorry but I can probably have it in like 15 min

proper wind
#

But if you have the data you can just paste it in list and make some loops and it will automatically enter it into the db

inland oar
#

can you help me out with that part, im so rusty in python havent had to use it in a year ๐Ÿ˜ฉ

proper wind
#

You can just copy the names of countries from Wikipedia for the specific continent and just copy paste copy paste and for loop for inserting from the list and your done

inland oar
#

I have the countries and names on the doc

proper wind
#

What is the deadline for this

inland oar
#

its due like in a month, but the thing is I have a bunch of slacker group mates and so I wanted to send them a dataset they could work on within the next few days or they are gonna say "I couldnt work on the project because our data doesnt have the continents column"

proper wind
#

Ok so what's the time at your place rn

#

I can't do it rn but I will be free at night at my place

inland oar
#

its 4:41 Am lmao, ive been trying to do this for hours. yea man i appreciate all your help

#

I could even slide you some $10 or so for your time on paypal

proper wind
#

No no

#

I am just doing it for experience and would you be up at like 3 pm at your place?

#

2 or 3 pm

inland oar
#

yea that works, i can be online at either time

proper wind
#

Ok so I will try to do it by 2 or 3pm or if not done we will do it together at that time

digital grotto
#

This doesn't seem to be related to the topic of this channel

proper wind
#

Now Its like 1 pm at my place so I have things to do

inland oar
#

do you want me to email you my excel file?

proper wind
#

Yea but we started and we did not realize that sorry @digital grotto

inland oar
#

@digital grotto sorry I think we are wrapping up and we can talk somewhere else instead?

proper wind
#

Yes you can and just add me as a friend and we can catch up at night

digital grotto
#

It's alright, just please be mindful next time.

proper wind
#

Ok sure ๐Ÿ‘

inland oar
#

Can you add me? Im kinda new to discord and Ill email you rn so just email me back ill keep an eye on it tomorrow around 12-2.

proper wind
#

Ok

inland oar
#

thanks @digital grotto

#

ok good night bro

proper wind
#

Ok bro bye

swift sonnet
#

Any good tutorails for pyautogui other than the documentation ?

proper wind
#

shrug

bold fossil
#

How do you get the current url using selenium??

bold fossil
#

Pls anyone??

bold fossil
ashen basin
#

@bold fossil driver.current_url

lunar valve
#
def command(name, function):
        if choice==name:
            function()
def jeff():
  print('jeff')

command('jeff', jeff())

how do i make this work?

bold fossil
#

@bold fossil driver.current_url
@ashen basin I have tried that, it didn't work

#

I am using python 3 with the latest version of selenium

sleek frigate
#

how do you use monkeypatch for testing a class that has a method that uses requests.get(url)?

digital grotto
#

@sleek frigate Typically you'd go and patch requests.get directly, mocking the return type that you want to be processed. That depends on how you've imported it however; for example, if you have something like

# api.py
from requests import get
```you'd want to mock `api.get` as it's a different "name" from `requests.get`, even if it comes from the requests package
sleek frigate
#

@sterile sparrow interesting, i did try that but maybe im implementing it wrong? let me post some code snippets of what i have

#
# test suite for league scraper class
import pytest
import requests
from league_scraper import LolScraper


class MockResponse:

    def get(self, url):
        if url == 'https://leagueoflegends.fandom.com/wiki/Aatrox':
            with open('local_test_pages/aatrox.html') as a:
                self.text = a.read()


@pytest.fixture
def mock_response(monkeypatch):
    '''Requests.get will return MockResponse instead'''

    def mock_get(url):
        r = MockResponse()
        r.get(url)
        return r

    monkeypatch.setattr(league_scraper, 'get', mock_get)


@pytest.fixture
def test_scraper():
    '''Creates LolScraper object to use for tests'''
    return LolScraper()


def test_champ_stats_collected(test_scraper):
    '''Test if there are stats collected for a champion'''
    url = 'https://leagueoflegends.fandom.com/wiki/Aatrox'
    test_scraper.scrape_champion_page(url)
    assert len(test_scraper.champion_stats) == 1```
#

so i have a class called LolScraper that has a method called scrape_champion_page that uses requests.get(). I have mock response class that I am trying to use in place of it

#

i tried mokeypatch.setattr(league_scraper, 'get', mock_get) since league_scraper is the name of the script that is using the get requests

#

thanks for responding btw, its been hard to understand just from docs for me as im new to tests

arctic wren
#

why do you use ''' ''' instead of #?

gentle terrace
#

it's a docstring

#

used for documenting classes/functions/modules

#

@arctic wren

whole siren
#
 print(soup.select('.flt-subhead1 gws-flights-results__price gws-flights-results__cheapest-price'))
 ``` I have this soup code, that keeps returning none, or an empty list, I checked the website triplets, and it is the same id and not the ones that keep changing, so why ain't it finiding it?
mystic wraith
#

question

#

i dont understand what am i doing wrong here

#

i think the error says that its my chrome's version and my Selenium's version but its 86 and my Chrome is 86 too

ashen basin
#

@ashen basin I have tried that, it didn't work
@bold fossil wdym by it didn't work

#

did you get an error?

bold fossil
#
 print ('ok')```
#

Ignore the bad indent I'm on phone

#

And then when I went to youtube

#

It still printed 'ok'

arctic wren
#

used for documenting classes/functions/modules
@gentle terrace oh sure

proper wind
#

so i got an issue rn basically its a discord bot that gathers messages from users and stores them in a list, problem is if a user decides to put code in the list instead of a normal word (like sql injection) the command will be ran from the list when i use the eval() function, here is my simplified example

equations = ["os.system('tasklist')"]
for equation in range(0, len(equations)):
    eval(equations[equation])```
 anyone know a way around this so cmds aren't ran from a list just @ me thanks
mint scroll
#

@proper wind make the equation match a regex before eval? You're almost in parser territory, no easy answers

proper wind
#

@mint scroll how would i do something like that?

digital grotto
#

@near shadow Pinging here as it's a more appropriate channel for that question. Let's say you have something like

from threading import Lock

class SafeValue:
    def __init__(self, value):
        self._value = value
        self._lock = Lock()

    @property
    def value(self):
        with self._lock:
            return self._value

    @value.setter
    def value(self, value):
        with self._lock:
            self._value = value        
```you want to test for race conditions in your code, a simple way of doing that is to spawn `n` amount of threads, with each thread incrementing an `int` wrapped in `SafeValue`.
```python
from random import randint
from threading import Thread
from time import sleep

def slow_increment(sv):
    sleep(randint(0, 100) / 100)  # Make sure that each thread finishes at a random time
    sv.value += 1

def test_safe_increment():
    sv = SafeValue(0)

    ts = []
    for _ in range(100):  # `n` threads means sv.value == `n`
        t = Thread(target=slow_increment, args=(sv,))
        t.start()
        ts.append(t)
    for t in ts:
        t.join()

    assert sv.value == 100
```Ultimately, this test is fairly trivial and will most likely pass every time, considering that the locks do guarantee protection from the same thread doing the same thing at once.
near shadow
#

what kind of testing i have to do?

idle cave
#

yo so i have a text file containing my messages from discord (i need for ai training)

however i wanna make a program to remove all of the "<@!123456789" from the text file

not sure how im supposed to search thru the file and replace... also the numbers are random altho all are same length

viscid wigeon
#
from tab crashed
  (Session info: headless chrome=86.0.4240.193)```
any help on why my chrome session is not working i have no clue what to start looking for
chilly yacht
#

not sure if this is correct channel

#

im trying to set up a staging server, i have a web app that i need to start testing

#

currently just testing on my laptop then pushing to git, which connects to docker

proper wind
#

i need help

#

why does this appear in my replit?

#

/home/runner/Discord-Bot/index.js:5
});
^

SyntaxError: Unexpected token '}'

gentle terrace
#

@proper wind thats javascript

#

and this is the wrong channel

proper wind
#

Why

#

It puts that?

gentle terrace
#

because you're running a js file

#

with python

proper wind
#

Wdym!

#

How i fix that?

#

@Hi,

I'm happy to announce that iPOPO has been relased in v1.0.1.

What is iPOPO

iPOPO is a Service-Oriented Component Model (SOCM) based on Pelix,
a dynamic service platform. Both are inspired on two popular Java
technologies for the development of long-lived applications:
the iPOJO component model and the OSGi Service Platform.
iPOPO enables to conceive long-running and modular IT services.

It is based on the concepts specified by OSGi:

  • Bundle: a Python module imported using ... continue reading
#

@gentle terrace

#

How?

#

&'5'';6:/

#

Yo tmvo

#

Lvo

#

F. Yfp cm bj ghhelp

#

CCleaner

midnight bough
#

Hi all, I'm new here..

I'm working with selenium+pytest (and unittest for the testSuites) and trying to use the allure-pytest, the thing is I'm getting the following error: configparser.NoSectionError: No section: 'common info' (this came from the readProperties.py class that I'm using for configurations such as baseURL and etc..).

Script:
pytest --alluredir=%allure_result_folder% testCases/test_login.py

readProperties.py:

import configparser

config = configparser.RawConfigParser()
config.read("../Configurations/config.ini")


class ReadConfig:
    @staticmethod
    def get_url():
        url = config.get('common info', 'base_url')
        return url

    @staticmethod
    def get_iccid():
        iccid = config.get('common info', 'testing_iccid')
        return iccid

a part of test_login.py (there are some helpers function, it works on a regular run):

import unittest

import pytest

from pageObjects.LoginPage import LoginPage
from utilities.helpers import Helpers
from utilities.readProperties import ReadConfig


@pytest.mark.usefixtures("setup")
class LoginTests(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.url = ReadConfig.get_url()
        cls.iccid = ReadConfig.get_iccid()

    def test_login_page(self):
        self.driver.get(self.url)

        Helpers.stop_and_wait(self.driver, 1)

        if "Welcome back" in self.driver.page_source:
            assert True
        else:
            Helpers.snip_screen(self.driver)
            assert False

Thanks.

proper wind
#

ammaa```
wheat osprey
#

I'm trying to develop a function to use with selenium that verifies if data was input correctly. For example, to check if a given textfield is holding what I want it to hold.

Something like:

    def verifyInsertion(name, type, xpath, data, attribute='value'):
        insertedData = driver.find_element(By.XPATH, xpath)
        insertedData = insertedData.get_attribute(attribute)
        
        if insertedData == data:
            #type will be used here to verify if it's a number, a select, a checkbox, etc
            print(name, " verified with value ", insertedData)
        else:
            print(name, " could not be verified")
            raise Exception(name, " could not be verified")```
That's the solution I came up with. Is it good enough? What you think?
supple pecan
proper wind
#

I wanna be helper

fringe edge
#

the programm by itself runs

#

any idea?

oblique crater
#

Google it it's probably missing library (import)

#

Not sure about your setup but typically it's good to put down your pip depencies somewhere like at least in requirements.txt file or use package manager like poetry

#

Paths..

fringe edge
#

there is a requirements

#

crud is a custom module

oblique crater
#

Cruds is your py file probably

#

Put app in package and refer via it

fringe edge
#

"in package"?

oblique crater
#

Directory plus init.py file

fringe edge
#

is already done

oblique crater
#

Okay then importing via app.crud ?

#

And how do you start tests ?

fringe edge
#

running pytest in the parent of test and app

oblique crater
#

Hmm I hate paths try with python -m pytest and package path

#

At worst PYTHONPATH environment variable can anchor your project

fringe edge
#

strange, am I doing something unusual or why does it not work like it should

oblique crater
#

Long answer is that import behaves differently whether one execute python script via file or module as paths might be different. There's documentation for that and I always keep forgetting about it.

#

Try from project root
Python -m pytest test

fringe edge
#

same

oblique crater
#

It faults on trying to import crud via main.py crud as it expects .crud due to path

#

I'd recommend to use
import .crud
Instead of
Import crud

fringe edge
#

syntaxerror

oblique crater
#

Sorry

fringe edge
#

still

oblique crater
#

Hmmm i guess you have to read documentation about imports Vs paths then. Can't help from my memory alone

fringe edge
#

ok thanks anyways

oblique crater
#

Found it

#

From . Import crud

#

Sorry I couldn't recall

#

It's due to paths if you're running tests it has different find path then if you're running app.
What this does is from this package import crud not from global

#

Global has no crud module app has

#

When you run app you run with global path at same directory as main

#

That's the difference

#

Does it work for you / another import to fix ?

fringe edge
#

let me try

#

web_1 | File "./main.py", line 1, in <module>
web_1 | from . import crud
web_1 | ImportError: attempted relative import with no known parent package

#

but the test doesn't fail on importing crud anymore

oblique crater
#

It's better

#

Review other imports

fringe edge
#

Why others?

#

still errors with this one

oblique crater
#

From app.main import app this one might be overriding app package

fringe edge
#

commented that out

#

still

oblique crater
#

That error was from running test or main directly ?

fringe edge
#

thats main in a docker

#

I have an idea though

oblique crater
#

Please run test main is different case

fringe edge
#

app/crud.py:3: in <module>
import todo_model
E ModuleNotFoundError: No module named 'todo_model'

oblique crater
#

Cool

fringe edge
#

maybe the issue comes from how I start the app?

oblique crater
#

Yes

fringe edge
#

because I start it from within app

oblique crater
#

That's right

fringe edge
#

what if I start it from the parent?

oblique crater
#

You can either fix imports to use package or add app dir To pythonpath

#

If you start main.py from file that will be root and it will have no idea about the package

#

If you start test it will notice package app and import from that

#

I solved it by moving main.py above app

fringe edge
#

Alright

oblique crater
#

Still if test lies in different package imports have to use absolute or relative paths or PYTHONPATH has to be amended for import from app to be noticed

fringe edge
#

I'll try that

oblique crater
#

It takes forever and for me to try something on pc it's a pain with just one hand as another is broken

fringe edge
#

get well soon

oblique crater
#

But basically I have similar setup to your case except the main where I found it PITA to call via module I rather prefer if python script.py works same as python -m script

fringe edge
#

I figured it out

#

thank you very much

#

running the python script from outside and changing all imports to

#

from . import xxx

#

did the job

oblique crater
#

Good

#

Took me a while to recall though. Would like to pass it on less count of steps but well working on it ๐Ÿ˜‚

proper wind
#

How to select somethign in drop down menu with selenium

fringe edge
#
assert response.json() == {
        "priority": None,
        "due_date": None,
        "description": "This is a test description",
        "id": int,
        "done": False
    }
#

Is there a way to do something like?

#

Check if the id is an integer

fiery cove
#

Hello,

For my unittests, I do a lot of subtest when iterating over an iterable:

  for x in "1234567890":
    with self.subTest(x=x):
      #test

Any idea how to make it less verbose/flatten that?

#

I was thinking of a decorator

waxen holly
#
def test(cases, expected:list):
    def function(func):
        def wrapper():
            counter = 0
            for case in cases:
                value = func(case)
                if value == expected[counter]:
                    print(f"{expected[counter]} passed")
                else:
                    print(f"{expected[counter]} failed")
                counter += 1
        return wrapper
    return function``` smthing like that would work
#
@test([1, 2, 3], [2, 4, 6])
def main(case):
    return case * 2
main()
>>> 2 passed
>>> 4 passed
>>> 6 passed```
#

idk if that fits your subtests tho

proper wind
#

I Made a program that looks up funny memes on youtube by itself

#
import time
while True:
    time.sleep(2)
    wrd = ['https://youtube.com']
    wrd2 = ['funny memes v300']
    keyboard = Controller()

    keyboard.press(Key.ctrl)
    keyboard.press('t')
    keyboard.release(Key.ctrl)
    keyboard.release('t')

    time.sleep(1)

    for x in range(len(wrd)):
        for y in wrd[x]:
            keyboard.press(y)
            keyboard.release(y)
            time.sleep(0.02)

        keyboard.press(Key.enter)
        keyboard.release(Key.enter)
    time.sleep(7)
    keyboard.press(Key.tab)
    keyboard.press(Key.tab)
    keyboard.press(Key.tab)
    keyboard.press(Key.tab)
    keyboard.release(Key.tab)
    keyboard.release(Key.tab)
    keyboard.release(Key.tab)
    keyboard.release(Key.tab)

    for x in range(len(wrd2)):
        for y in wrd2[x]:
            keyboard.press(y)
            keyboard.release(y)
            time.sleep(0.1)

        keyboard.press(Key.enter)
        keyboard.release(Key.enter)```
#

try it in a browser

#

you will not be disappointed

#

nice! Did you ever consider using selenium for that?

#

in my experience its a lot easier to use / more condensed

#

Sorry, Server member list broke my discord.

#

Maybe I'll try selenium

#

I've been practicing pynput

pure cradle
#

selenium has some really easy to use functions for basic stuff like that

pure cradle
#

that would be like 5 lines of code

marble stump
#

Im not sure if this is the right channel for selenium but my question is how do i keep checking an element

gaunt ibex
#

@marble stump I am not sure about selenium specifically, but if you are looking to implement somewhat sophisticated retry mechanisms I had luck using the tenacity library.

burnt nebula
#

hello everyone im looking for some help with selenium ^^

nova fable
#

@ me if u need help with webscraping

round gyro
#

Can someone recommend any test course??

shut hedge
#

@proper wind What are you scraping? Is it in any way related to automated software testing, like running unittests or integration tests?

shut talon
#

Rather than writing out all the combinations to check with the pytest test I am trying to get fixtures working with parametrize. In essence I want to test each option in a collection with a set of known valid values, rather than every possible combination of all variables. e.g. try every stat with a static number of damage.

Taking the following approach seems to pass the function/fixture rather than the enclosed data. What am I missing?

_primary_stats = []
for stat in utility.get_class_members(PrimaryStat):
    _primary_stats.append(stat)


@pytest.fixture(params=_primary_stats)
def primary_stat(request):
    return request.param

test_damage_effect_parameters = [
    (primary_stat, 1, )
]

@pytest.mark.parametrize(["stat_to_target", "accuracy"], test_damage_effect_parameters)
def test_damage_effect(
        benchmark,
        stat_to_target,
        accuracy
):
  ...

I tried indirect=True, but every test in the test_damage_effect_parameters fails with "fixture not found"

nova fable
#

ok

#

i am here C:

#

@proper wind can i see the code

rocky flicker
#

Has anyone here ever launched autoit (.au3) scripts from a python script? If so what is the easiest way to do this?

fiery arrow
#

Can someone suggest any articles/blog posts/books on "testing the hard-to-test stuff"? Like, the IO boundary or the extremely side-effectful parts.

grave delta
#

I have a repo:
src
src/admin_tools
src/c_fixer
src/c_fixer/fixer.py
src/c_fixer/data/
src/tests
src/tests/admin_tools
src/tests/c_fixer
src/tests/c_fixer/main_test.py
src/tests/c_fixer/data/

I want to test my fixer.py, which looks in the data folder with a relative reference ./data/... However, when I run the test, I'm getting FileNotFoundError ./data/...

#

does anyone know why?

#

src is my source root

#

nvm, I had to mess around with the working directory on PyCharm and relative imports ๐Ÿ˜„

calm garnet
#

Hi everyone, does anyone know some docs about testing image editing tools with python+selenium?

split mauve
#

Hi, I am having hard time to test my webcam for landmark classification

old parcel
#

Is there anyway to time schedule fb messenger with python?

proper wind
#

assert response.json() == {
"priority": None,
"due_date": None,
"description": "This is a test description",
"id": int,
"done": False
}

hollow basin
#

I've only ever unit tested with the built-in unittest library and I'm wondering if I should plan to use a pypi package like pytest or hypothesis for a library that I'm working on individually

split field
#

I'm a big fan of pytest, @hollow basin - I find it easier to understand than unittest, cleaner, less verbose, and more flexible.

hollow basin
#

@split field I'll have to give it a try

shut owl
#

hey, if any of you need to automate hardware, I do recommend this library -> https://github.com/google/openhtf

proper wind
#

h

fiery arrow
#

Related to #async-and-concurrency / <#async-and-concurrency message>:
I implemented a function like this:

async def check_solution_against_single_spec(
    run_code: Callable[[Solution, str], Awaitable[ExecutionResult]],
    spec: ProblemSpecification,
    solution: Solution,
) -> SpecificationStatus:
    tasks = [
        asyncio.create_task(check_solution_against_single_test(run_code, test, solution))
        for test in spec.tests
    ]
    for coro in asyncio.as_completed(tasks):
        r = await coro
        if not r.is_successful():
            for dangling_task in tasks:
                dangling_task.cancel()
            return r
    return RightAnswer()

Basically, it tests a programming problem against a list of tests concurrently, and if one test comes back with an error (r = WrongAnswer | ErrorOccured | TimedOut), the other tests are cancelled.
How do I test the "the other tests are cancelled" part?
This is what I came up with:

@pytest.mark.asyncio
async def test_when_one_test_fails_other_do_not_get_executed():
    spec = ProblemSpecification(
        "it works",
        [SolutionTest("input", "good")] * 10
    )
    solution = Solution(id="42", code="correct solution")
    execution_count = 0

    async def fake_runner(solution: Solution, input: str) -> ExecutionResult:
        nonlocal execution_count
        await asyncio.sleep(random.random() * 0.1)
        execution_count += 1
        return ExecutionSucceeded("bad")

    await check_solution_against_single_spec(fake_runner, spec, solution)

    assert execution_count == 1

but to my understanding, this is a flaky test -- it will randomly fail from time to time (and it can be achieved easily by changing * 0.1 to * 0.01). How can I properly test this function?

#

Of course, it's possible and maybe even acceptable that 1 or 2 stray tests are executed when they shouldn't have, maybe I should change it to

assert 1 <= execution_count <= 3

or something like that?

#

But, for example, this implementation shouldn't pass the test:

async def check_solution_against_single_spec(
    run_code: Callable[[Solution, str], Awaitable[ExecutionResult]],
    spec: ProblemSpecification,
    solution: Solution,
) -> SpecificationStatus:
    aws = [check_solution_against_single_test(run_code, test, solution)) for test in spec.tests]
    for coro in asyncio.as_completed(aws):
        r = await coro
        if not r.is_successful():
            return r
    return RightAnswer()

because it executes all the tests in any case

gentle zephyr
#

@fiery arrow your function names lol test_when_one_test_fails_other_do_not_get_executed():

fiery arrow
#

that's a normal name for a test ๐Ÿ™‚

#

some languages even allow spaces in names (like Kotlin), so that you can use normal sentences as names

fiery arrow
proper wind
#

I think this is the right place to put it

#

I'm working on a thing with PIL

#

and I'm trying to put text above an image but idk how and I'll I can find is how to put text on an image

#

wait

#

this is the wrong thing

#

crap

#

๐Ÿ˜”

split field
#

BDD test names are commonly test_that_...

fiery arrow
#

Alright, a more... trivial question ๐Ÿ˜„

#

one of my modules has a class called TestCase that represents a test case of a programming problem. I'm importing it in my test. The issue is that pytest thinks that it's a test class, and it gives me a warning because it has an __init__. Any way to avoid it?

#

Well, I guess, I can export it by a different name

gray willow
sharp cliff
#

Hey guys, would anyone please help me with pytest?

midnight roost
#

Hello, I am new to this testing world and I am using Django's default test suite to test my views. I am trying to test posting of a file and I thought I knew how to do it but I am running into errors. Here is what I have.

def test_post_when_logged_in_with_permissions_form_error_1(self):
        """Test that the view returns a HTTP 400 when the user is logged in, has can_import_driver_data permissions, and
        posts invalid file extension"""
        url = reverse('main-import-driver-data')
        permission = Permission.objects.get(codename='can_import_driver_data')

        self.user.user_permissions.add(permission)
        self.client.force_login(self.user)

        # Create text file to post
        with open('Test.txt', 'w') as file:
            resp = self.client.post(url, {'driver_file_import': file})

        self.client.logout()

        print(resp)

        self.assertEqual(resp.status_code, 400)
gray willow
stiff crypt
#

Hello everyone, I am required to set up automated test.
What is the best approach?
I've used Selenium for web scraping. As I looked around, it is actually used for automated testing. My question is, what else do I need to prepare automated software testing ie. We've web application in which I need to test log in page, and subsequent pages also. Example scenario for an online exam web application:
User will be,
-log in
-click on his exam
-will solve the exam
-log out
I myself did an automation doing all that stuff. However, there is nothing related to test. I mean I didn't use any kind of assertion etc. Can somebody guide me please?

proper wind
#

is it okay for u to use JS

#

because I know just the tool for that

#

behold

#
https://www.cypress.io/
#

$npm install cypress

tall brook
#

yeah, I suggest cypress too, I have used Selenium but cypress do more things for you out of the box. The good part of selenium is that you can code in Python

cursive tundra
#

yeah

hollow sparrow
#

Hello guys, I have a weird problem in Selenium. I am trying to use send.keys() to input email address. I have that address in variable self.email. The address is for example "aaa@bbb.com". When I use self.element.send_keys(self.email), it actually sends something like "aaaself.emailbbb.com". I am becaming quite desperate, because I weren't able to find any fix or even mention of this problem.

tall brook
hollow sparrow
tall brook
hollow sparrow
echo zinc
#

or alternatively use something like Keys.ALT + Keys.CONTROL + "q" instead if @ is on your q key.

#

as far as i know, send_keys does not automatically press alt or ctrl. only shift.

quiet sierra
mortal sluice
#

Hey guys, I have an strange problem when using selenium, Im trying to set up a moderator bot for my youtube streams and Im required to send some messages through chat. I can't seem to find the right xpath to the youtube live chat, Im always getting the same error: "selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element" Ive been trying to find where to use .send_keys(), does anybody know a bit about this issue or how to solve it? Thanks

gentle terrace
#

@mortal sluice unfortunately, that appears to violate youtube TOS so we cant help you

#

You are not allowed to ... access the Service using any automated means (such as robots, botnets or scrapers) except (a) in the case of public search engines, in accordance with YouTubeโ€™s robots.txt file; or (b) with YouTubeโ€™s prior written permission;

echo zinc
frail garden
#

Hey guys I'm new here so I have a doubt

#

Suppose you have a tab open and you redirect to a new tab, you give the xpath of an element in the new tab, so does it try to locate the element in the new tab or the previous one??

cobalt aurora
#

Assume that Circle is defined using radius and Cylinder is defined using radius and height. Write a Circle class as base class and inherit the Cylinder class from it. Develop classes such that user can compute the area of Circle objects and volume of Cylinder objects. Area of Circle is pie radius*radius, while volume of Cylinder is pie(radius * radius)*height

#

HEY GUYS I GOT TO WRITE THIS PROGRAM IN PY

#

CAN U WELP???

south blade
#

hello

#

Sorry for coming just like this but i need help with pyautogui

#

note i'm a total nub

#

If you can help ping me pls. I wil try solving this meanwhile

#

Nevermind, just downloaded Pillow

cosmic grotto
#

What are some cool automation libraries

golden forum
#

As it turns out this is more of an issue not with how TK is installed but how pylint seems to be inconsistent across platforms on github actions. Tested with the file below on a clean repo. Any thoughts besides disabling pylint imports?

Results as follows:

python 2 windows (2.7.x) Linting Fail

  • E: 7, 4: Unable to import 'tkinter' (import-error)

python 3 windows (3.8.x) Success Linting

python 3 linux (3.8.x) Linting Fail

  • E: 7, 4: Unable to import 'tkinter' (import-error)

python 3 MacOs (3.8.x) Success Linting

Setup:
Github Actions Configuration
https://0bin.net/paste/sGbbX84r#vxpe73nMg6-YHd+Y+Z+hqCl8YRh9a8pmzgMK01PfWeF

tk_test.py

import sys, six
print(sys.version)

if six.PY2:
    import Tkinter as tk
else:
    import tkinter as tk

print(tk.TkVersion) # succeeds in all platforms to print version number
golden forum
#

Turns out to be an issue with six/ pylint a simple try /except ImportError: it lints just fine.

patent stag
#

How do I run chrome driver headless in Selenium?

cosmic harness
#

Hi All - im writing some tests for one of my uni courses and I just need some advice

#

should I be writing

#

assert function(a) == False

#

or

#

assert not function(a)

#

they both work

#

but I'm just wondering from a best practice / style side

nimble storm
#

The first one reads better to me, might be purely down to personal preference though

signal token
#

Are there any blogs/books/whatever on how to write good test cases? I'm new to testing and have written some quick pytest functions but I feel like I might be missing the point and testing for 'incorrect' things

#

as in, I dont think my tests will ever really fail

cosmic harness
#

I've been taught that you right the tests before you've written any code

#

so at some point they have to fail

#

write*

nimble storm
#

Same as Pete,. Your tests should fail before you write the 'implementation of the method' in test driven development. That said, once all is implemented, everything should pass until you introduce a bug refactoring the implementation. Unit test a happy and bad path to begin with, you'll likely never see them fail after implementation until someone else has to maintain your code.

chilly yacht
#

what do you guys recommend for testing linux server/flask app

chilly lava
#

Hey is there a way to disable one of the onclick functions

#
<a id="cmdLogin" onclick="javascript:formSubissionHTMLInjection(); javascript:formSubissionManVsMachine(); javascript:if(loginUser(document.getElementById('frmLogin'))==false) return false;" tabindex="0" title="Login" href="javascript:__doPostBack('cmdLogin','')">Login</a>
#

i need to disable javascript:formSubissionManVsMachine()

proper wind
#

how do you do python i dont know

frank sable
#

?

grave yoke
#

Hi I'm using Selenium Web Driver in python to automate a test, so far though when I try to click a link it sends me to that page BUT when I try click another link on the new page it doesn't register. I heard the issue is because it still thinks I'm on the first page. I was just wondering how do you fix this? I have tried doing something like this so far. ```python
linkhelp = driver.find_element_by_link_text('Help')
linkhelp.click()

newURl = driver.window_handles[0]
driver.switch_to.window("https://www.littlewoodsireland.ie/help/en/online-help-system.page")

privacy = driver.find_elements_by_link_text("Privacy and Cookies")
privacy.click()
driver.close()
driver.quit()```

pastel oracle
#

!hep

#

#bot-commands

raven sundial
timber kernel
#

Anyone has a tip on what kind of testing tool I could use best for Front- and Back-end testing?

#

Preferably a tool I can use with Python or an easy syntax

verbal spoke
#

how do i check if a captcha is solved in selenium

peak palm
#

@grave yoke its been a while using selenium for me, by the script example I am assuming when you click the link it opens a new window? First thing I would do is have a page wait for weekend to load before clicking, sometimes elements cannot be interacted with if they are not loaded, sometimes selenium can go a bit too fast for a web page.
Assert privacy was found before click.
List your windows in debug, assert you are going to the right window.

#

If the link you click is just a normal link that doesn't create a pop up you do not need the switch to window. Plus I would read the switch to window selenium doc. I think going title or is preferred (been awhile)

#

Ps assert the element you are interacting with on the new page isn't in an iframe, if yes tell selenium to step into the iframe first

delicate berry
#

Is anyone here good with setting up selenium on debian?

proper wind
#

hey

peak palm
#

Its pretty straight forward setting up selenium in a deb environment. I do recommend downloading the browser driver and give absolute path (if it is to be ran only in the environment)

#

Be sure to create the setup and teardown

#

So it knows to launch browser (if non headless) and close when done performing test

frail garden
#

Guys I have a doubt

#

How do you enable media access in geckodriver

#

I tried add_argument('--use-fake-ui-for-media-stream')

#

I also tried set_capabilities('permission.microphone.default',1)

meager smelt
#

has anyone had any luck automating webui testing for svg elements? I'm having a nightmare trying to get anything to work >.<

frail garden
lavish tapir
#

Anybody have some tips on identifying memory leaks

#

I have this one discord bot that is somehow taking wayyyy more memory than it needs

steel monolith
grim hill
#

If anyone is familiar with pytest, can I get some help in #help-candy ? Thanks!

cobalt ore
#

With testing we can use temporary directories ( pytest has them, there's tempdir, etc ) so that any written files are cleaned up after... I'm wondering if there's ever a case for handling this cleanup yourself instead of using a tempdir though ?

if things fail during a test will there be some random sodifnwofeiwefoefijoeo dir located somewhere on the system? That's about all I can think of atm... Also - the option of not cleaning up the files afterwards could be more easily toggled on/off if this was handled by the user I think.

but I'm not sure - so interested to hear if there are clear examples or whether this just highlights I haven't used tempdir and such enough.

#

( if anyone responds to the above please ping me )

kind meadow
#

@cobalt ore tempfile from the standard library has automatic cleanup through context managers. If you're not familiar with context managers, think of it like wrapping the code in a try-finally and doing the cleanup in the finally block.

The only way that could fail is if the process is forcefully killed, either with os._kill or something else sending it the SIGKILL signal. In such case, you wouldn't be able to do anything better manually to clean things up.

I can only think of caching as a use case for keeping the temporary directory around. However, you'd need to be very careful to avoid an old cache causing a test (perhaps one that's been recently modified) to incorrectly pass. Seems like more trouble than it's worth.

proper wind
#

Like a door bell notification

kind meadow
#

@proper wind You seem to be in the wrong channel. How does your problem relate to automated testing?

proper wind
#

Itโ€™s not a problem

#

Itโ€™s automated

kind meadow
#

So are you just discussing what you've made?

proper wind
#

Yea

kind meadow
#

Sure it's automated but what's it got to do with software testing?

proper wind
#

I finished it today

#

Uh what

kind meadow
#

This channel is topical. Discussions should focus on a specific topic. In this case, the topic is automation of software testing. What you've shown does not seem related.

proper wind
#

You are a developer for python?

#

I always wanted to do that but I donโ€™t have any money

#

@kind meadow whereโ€™s the projects channel

#

Have a lot of time to ask me questions but no time to answer mine

#

#Masterpythonrace hooora

kind meadow
#

Your first question is off topic. I've already given the #python-discussion channel for your second question. To be clear, there's no dedicated channel for projects anymore.

ember maple
#

gm

cobalt ore
#

@kind meadow thanks, context managers are fine. I was wondering if I was missing something, what you've said makes sense though, cheers

jade solstice
#

is there a better way to do this in unittest ? i can't directly test "v[2] = 0"

        def f():
            v1[2] = 0
        self.assertRaises(TypeError, f())
torn mirage
jade solstice
#

thank you, it seems to works : self.assertRaises(TypeError, v1.__setitem__(2,0))

#

errr... does it ?

#

i'm confused...

#

self.assertRaises(TypeError, v1.setitem(1,0)) <- this test also pass but it shouldn't since it's not supposed to raise a TypeError here.

#

my test isn't called ...

#

pfffffffffft

#

i'm not using assertRaise correctly

#
        with self.assertRaises(TypeError):
            v1[1] = 0
#

now it works and really do the check

jade solstice
#

thank you for the help @torn mirage

gray hawk
#

help

chilly yacht
#

resources for learning some testing?

rotund phoenix
#

How would you go about unit-testing code which requires a pyodbc connection to an MSSQL server?

frail garden
#
edge_options = Options()
    edge_options.set_capability('permission.default.microphone', 1)
    capabilities = edge_options.to_capabilities()
    driver = webdriver.Edge(executable_path=path_edge,capabilities=capabilities)```
#

I need my code to allow permissions

#

Can someone help

drifting basin
#

So - I have been trying to track down this issue for awhile now and I can't seem to figure out what the heck is going on.

Using selenium, I keep getting the following error:
selenium.common.exceptions.SessionNotCreatedException: Message: session not created from timeout: Timed out receiving message from renderer: 600.000

The SO posts that I've read say that chrome and chromedriver are not up-to-date, but I have confirmed multiple times that they are the correct married couple.

chilly lava
#

anyone has experience with playwright?

fast bough
#

You mods deleting my lines faster than I can.... So diligent.

#

can someone quickly explain this?

split mauve
#

hi, Does anyone have an experience of implementing GAN?

#

I have an error of 'Error when checking input: expected conv2d_1_input to have shape (48, 48, 1) but got array with shape (32, 32, 1)' when generator produce the fake images as 32 by 32.

tough saffron
#

Hello everyone.. what is the best way to write a python code which verifies if tab completion is working fine in a router

meager smelt
gray storm
pale citrus
#

hey guys, i'm using the unittest module for a large project i'm working on at work. I dont want to use the discovery feature as I want to manually point to which folders to pull tests for. Tests are organised in a test folder (it's large) and i think i've defined all my tests accordingly and want to use a testrunner. the issue? I'm using the test runnner setup as can be seen here: https://www.internalpointers.com/post/run-painless-test-suites-python-unittest but when i run my tests, (even using the loader.loadTestsFromModule() function) it 'finds' 0 tests so it gives

#

`Result: <unittest.runner.TextTestResult run=0 errors=0 failures=0>

Ran 0 tests in 0.000s

OK
`

arctic pike
#

hey guys, need help with selenium automation with python

#

having trouble launching the webdriver

late glade
#

I have a question that's not entirely python related.
How would you test an app that's supposed to send list of messages to the user.
Each message is a string and it contains some details about a problem on the PC.
For example "HardDrive C is full". How could I test the result so it's refactor safe?

arctic pike
#

@late glade you could possibly look at mock testing or mock requests

karmic storm
cobalt ore
#

is there any way for pytest to only carry out tests for files that have changes since the last test that was run? Like a Makefile or whatever

proper wind
#

wit

serene wadi
#

StaleElementReferenceException: The element reference of <span> is stale; either the element is no longer attached to the DOM, it is not in the current frame context, or the document has been refreshed

#

I m coding web scraper with selenium and i got this error for this code

#
counter = 0
while(counter<len(urls)):
    time.sleep(1)
    browser.get(urls[counter]+"/#ht-ft;2")
    
    oranlar= browser.find_elements_by_tag_name("span")
    j=0
    for i in range(len(oranlar)):
        
        if(oranlar[i].get_attribute("class") == "avg nowrp"):
            print(oranlar[i].text)
    
    counter+=1
        ````
#

how can i fix it?

jaunty glade
#

Because you are refreshing it

#

you are calling browser.get(blah, blah) in a loop form

#

meaning that you are changing the link each time

#

also, browser is not defined

bitter wadiBOT
#

Hey @zenith ridge!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

โ€ข If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

โ€ข If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

proper wind
#

hi everyone, can you give me an advice , i have a presentation to get my diploma of web developer. i present my trainingship and some test but i realise is not so easy to explain ! is there a special way for these type of presentation ?

#

im not sure im in the good channels but i try thanks ๐Ÿ™‚

twin pier
#

Hello. Having a lot of trouble with stale elements in selenium.

#

like, i make a list from "find elements using xpath", and the list returns just fine

#

but the next line, i try to to iterate it in a loop, and the first result already returns stale error?

#

of course, nothing changes on the screen...

#

all the online answers say i should use implicit wait until the item is no longer stale, but the item is already stale... waiting will not change that

lofty ocean
#

need help in webscraping

signal pivot
#

@lofty ocean has you install it ?

lofty ocean
#

yea

lofty ocean
#

I'm getting this same error when I used prettytable module

#

now it is coming for bs4 too

fiery arrow
lofty ocean
#

ok sorry

kind meadow
#

@pale citrus Did you figure it out? The only issue I can think of is that your tests functions don't follow the expected naming convention (they must start with test)

#

If you're not using that prefix then you can change the value of TestLoader.testMethodPrefix

slender seal
#

!e

numbers = [2, 3 , 5 , 6, 2 ,4 , 3, 5, 6]
duplicates = []

def delete_dup(self):
    for duplicate in self:
        if duplicate not in duplicates:
            duplicates.append(duplicate)
    return duplicates

dupli = delete_dup(numbers)
print(dupli)
bitter wadiBOT
#

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

harsh gust
#

I want to make a function taht increases "i" by +1, till (f * i+1)/e = "whole number". It needs to check for if the number has decimals, if it has decimals "i" has to be increased by +1, till the equation equals a whole number without decimals.

ex.
(5512 * 1+1)/35 = 157.51... <---- bad therefore i = i + 1
(5512*2+1)/35 = 315 <--- done

harsh gust
#

Is this the right channel to ask or no?

split field
#

It doesn't seem like the question has anything to do with automating software testing, no.

harsh gust
#

@split field where then should I post the question?

split field
hot sleet
#

hey folks, i think i have what i think should be a pretty basic question... i want to test a function that requests a URL where a zip file is downloaded and saved to a directory. I have the request mocked, but i'm not sure how i can prevent the side effect of saving the file to the directory which is hard-coded in the function. I realize i'm probably breaking SRP here and should either stub out a function with a path argument or just add a path argument to my current function, but i want to make sure i'm understanding testing architecture and pytest's capabilities. Is there any way to tell my function to save it to a tmp_dir instead of the path coded in the function?

#
def download_zip_from_url(url, chunk_size=128):
    r = requests.get(url, stream=True)
    filename = Path(url).name
    with open("data/geodata/" + filename, "wb") as f:
        for chunk in r.iter_content(chunk_size=chunk_size):
            f.write(chunk)
#
def test_download_zip_from_url(requests_mock, tmp_path):
    requests_mock.get(
        "https://testurl.org/test.zip",
        stream=True,
    )
    maps.download_zip_from_url(
        "https://testurl.org/test.zip",
    )
kind meadow
#

Without changing the function your testing, the only way I see to accomplish that is by mocking the open builtin, which I believe is possible.

#

Sorry, not mocking it. You'd have to patch it.

#

When patched open will do whatever you want, like using the tempfile library to open a temporary file instead.

#

But your intuition is right. You should add a path argument or at least define a constant for the base path which you can patch while testing.

hot sleet
#

ok, thanks so much! I've heard about patching but it's still a little bit of a head spinner, good to know of a use case even if it's not the ideal solution... so is patching a lazy-but-sometimes-worth it hack, or should i avoid it whenever possible?

kind meadow
#

That's a more loaded question than you might think

hot sleet
#

sorry if that question is a little broad

#

ha

kind meadow
#

It's contentious I'd say

#

Or testing methodologies in general are

#

Some try to use it sparingly and others patch a lot

#

It boils down to how tightly you want to couple your tests to your implementation

#

It makes your tests more thorough or precise at the cost of tight coupling.

#

Patching can also get really ugly and complicated

hot sleet
#

makes sense!

kind meadow
#

Some good uses cases are to mock database connections

hot sleet
#

is that cuz it's more difficult to dig under the hood so to speak?

kind meadow
#

Usually a database connection is handled by a third-party library that already has its own tests from its authors - it's code you're not responsible for.

#

So you mock it and just make sure that your program is correctly interacting with the database

#

There usually isn't an easy way for you to assert at any deeper level that the database is doing the right thing. And again, it's already tested. So you can assume if you call "db.foo()" with argument "x", it will do the right thing.

hot sleet
#

gotcha

kind meadow
#

I suppose an alternative would be to set up a real test database and perform queries to make assertions that a column got updated to a new value or whatever.

#

Django's test runner sets up a db like that I believe.

burnt kraken
#

anyone who knows what it means by "object of 'Response' has no len()" length of what do i need exactly

#

is it the amount of links that im scraping that i need to specify?

final ravine
#

use source_page.text insted

burnt kraken
#

markup = markup.read()

final ravine
#

can u show has your code

#

?

#

we might help

mint merlin
#

heya i was trying to bind the variable name in single quotes by using the function xpath() but aint working the actual syntax was like this driver.find_element_by_xpath(//span[text()='Electronics']

fiery arrow
#

(unless you're hired to do automated testing by flipkart, in which case you can probably ask the question to your colleagues)

mint merlin
tiny widget
#

Hey @mint merlin! Since automation isnโ€™t allowed by flipkart,com, we canโ€™t help you with your project, no matter if it is about the automation part or not, see our 5th rule.

tiny widget
#

No worries

hard temple
#

is it possible to write a python script that downloads and sets new desktop wallpapers for your pc every day or week without you worrying about it?

slate hatch
#

Hey everyone, I'm trying to reproduce a burp suite request as a python script. in burp suite i get the correct json response with the data i need. my python script sadly returns a totaly diffrent response.
The burp suite request: https://paste.pythondiscord.com/efakowidiw.http
The burp suite response: https://paste.pythondiscord.com/naxupoqesi.http
my python script: https://paste.pythondiscord.com/udovamodaq.pl
the printed response.text: https://paste.pythondiscord.com/gakizasuce.xml

response.json() returns an error.
Can someone tell me why the responses are diffrent?
Edited because i updated the code

burnt kraken
#

anyone who knows how to fix the "Getting default adapter failed" tried on google, loats have had it, can seem to fix it tho

#

im simply opening a website, literally nothing else, and it crashes down after 2 seconds (selenium

mint merlin
bitter wadiBOT
#

@fiery arrow :white_check_mark: Your eval job has completed with return code 0.

C:\Program files
fiery arrow
#

Huh, backslashes work ๐Ÿค”

#

Either way, please use this channel only for questions about automated testing. If you have a general question, please claim a help channel (see #โ“๏ฝœhow-to-get-help )

fiery arrow
#

Hi, this channel is for discussing automated testing -- unit testing, integration testing etc. If you have a general question, you need to claim a help channel, see #โ“๏ฝœhow-to-get-help

proper wind
#

but i got cooldown

#

or i had

torn mirage
silk iron
#

im using selenium and i have a problem with it, if someone is able to help me at help-zinc i would be very grateful

snow brook
#

what test framworks are people using ?

bitter wadiBOT
clever lake
#

My 1st python file! Check it out and inform me!!

serene escarp
#

@snow brook While I am quite lousy at using dedicated test frameworks, I do find the debugging, and coverage features of PyCharm absolutely stellar.

#

Any project file can be run in coverage mode, and when the execution halts, the reporting is nicely detailed and shows percentages of lines covered for all source files.

#

... My day job is programming flight software for ESA space probes so I have a weird sense of testing. Python just doesn't support sufficient level of paranoia to ever achieve sensible "certainty" that stuff really is reliable. So I rarely commit to testing python seriously since it's moot anyway.

fiery arrow
#

I use pytest for normal unit tests, and I recently started playing around with hypothesis, which is a property testing framework.

magic glade
#

any one here a experienced ethical hacker?

split field
#

That question is off topic for this channel, but would fit in #cybersecurity

boreal mist
#

why it is not allowed to use a module name inside a package that starts with a number/digit?

brisk sky
#

What does time.sleep do?

acoustic geyser
vivid snow
#

How do you upload a file to a website using selenium when there is no input form, the type is a button and I'm trying to upload a mp3

split mauve
#

2020-12-21 17:15:25.246427: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cudart64_100.dll
D:/Porject001/Test02/Sample_Test05.py:58: UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.
plt.show()

rigid token
#

does any one got decent pytest course in reasonable price?

fiery arrow
rigid token
#

I will get my first test to write soon after xmas

fiery arrow
#

And if you're not sure how to test something, you can ask here.

ivory echo
#

anyone knows best way to show the picture png as canvas streaming for live streaming?

#

which python module is good to work with png streaming?

hard temple
#

okay ๐Ÿ‘Œ

slender scarab
#

what is the best way to click a link with silenium

mint scroll
slender scarab
#

thanks

little flare
#

Um can someone please help me

#

I want to make the classic bee movie script bot

#

but it cant find the text file for some reason

#

im including sceensnippets

#

pl0x help

fading surge
#

save it as beemovie.txt

little flare
#

on textedit ? or within pycharm ?

fading surge
#

It's the same thing

fading surge
#
import os
print(os.getcwd())

What is your output when you run this?

fading surge
#

that's weird...

#

Try giving the full path once

#

in open()

little flare
#

it WORKED

#

THANK YOU so much !!!

fading surge
#

:)

little flare
#

but seriously, thank you.

grave delta
#

Think I posted this in the wrong channel and this channel would be better:

#

I have a tests directory like:
tests
tests/tool1
tests/tool1/data (testing code on some dummy data)
tests/tool2
tests/tool2/data
and tests within the tool1 and tool2 folders. If I want to run all of my code from tests how can I do that? As my tests are failing due to not being able to find the /data folder I've referenced in my test files under the tool1 and tool2 folders

grave delta
#

if I cd into the tests folder and run python -m unittest discover I get import failures on my test files - but the PyCharm linter isn't giving any errors with the current way I import

rapid grove
#

Is there a way to get supporting files via selenium? Like say the page sends a jpeg or json file. Is there a way to retrieve that data using selenium?

worn stone
#

@rapid grove you could just use requests.get

#

im not so familiar with selenium, but what you should do is get the url where the image comes from

#

then you can download it with open('image.jpg','w').write(requests.get(link).content)

rapid grove
#

Thanks!

fossil crow
#

idk where this is supposed to go but does anybody know anything about generating music patterns

keen badge
#

!code

bitter wadiBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

keen badge
#
import os,time,playsound
import speech_recognition as sr
from gtts import gTTS

def speak(text):
    tts=gTTS(text=text,lang="en")
    filename="voice.mp3"
    tts.save(filename)
    playsound.playsound(filename)
def get_audio():
    r=sr.Recognizer()
    with sr.Microphone as source:
        audio= r.listen(source)
        said=""
        try:
            said=r.recognize_google(audio)
        except Exception as e:
            print("eception"+str(e))
    return said

speak("this works")
get_audio()
#

Traceback (most recent call last):
File "C:/Users/USER/PycharmProjects/untitled5/reddit.py", line 22, in <module>
get_audio()
File "C:/Users/USER/PycharmProjects/untitled5/reddit.py", line 12, in get_audio
with sr.Microphone as source:
AttributeError: enter

#

anyone know why it traggers this error

split field
keen badge
#

Thanks

split field
#

what the error is telling you is that the object you supplied to with doesn't support the context-manager protocol

#

missing () is a wild guess about why, since I don't know that library, but if that's not it it's something else wrong with what you're providing there.

boreal mist
#

when I'm using pytest the test work if it is run individually (per function test) but if it is run as class it will fail. What does it mean?

proper wind
#

Hello anyone have experience with selenium and proxies?

proven swift
#

How do i actually generate reports in selenium-python. Is it just terminal or html reports? What additional library do i have to use, to get reports ? Do any one have a sample code ?

livid frigate
#

is there any source to start learning ai

#

halp

vivid bronze
#

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//input[@name="username"]"} how do i fix this?

keen badge
#

!code

bitter wadiBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

manic axle
#

How can I make a function run for a specific time in a "while True:"?

split field
#

don't use while True:, and instead use something like:

import time
start_time = time.time()
while time.time() < start_time + 30:
    # Keep looping, but stop after 30 seconds
manic axle
#

thank you

twin pier
#

is there any alternative to selenium for automating js webpages?

molten oriole
hollow basin
#

I don't really see the point of fixtures.

vital oyster
#

what you're using fixture for there can be accomplished with a global object

#

fixtures are a form of dependency injection, so the examples of using a database connection or a file handle are to save just a few lines of code to handle the instantiation etc.

split field
#

Fixtures frequently do something, too. If all you're doing is returning some constant data, then the fixture isn't buying you much over a global. The one advantage is that the fixture function is called once per test, so one test can't mutate the data and leave it in a bad state for another test. The real advantage comes from fixtures that call other functions or set up preconditions or set up monkeypatches or mocks or insert dummy data into a database, etc.

#

Think of fixtures in pytest as being analogous to unittest's setUp methods.

#

In pytest, you'd do py def test_thing(a, b, c): whereas in unittest you'd do ```py
class SomeTest:
def setUp(self):
self.a = a()
self.b = b()
self.c = c()

def test_thing(self):
    ...
#

Except that the fixtures can also handle their own tearDown as well, so that's not a perfect analogy; they're more powerful than that would imply.

#

@hollow basin ^

hollow basin
split field
#

I don't think I understand the question

#

There's nothing that you ever need pytest for, it's just a less verbose, more flexible, easier to use, more Pythonic alternative to unittest

#

like, in the example I gave above, pytest is doing in 1 line what unittest takes 7 to do.

#

typical examples of things that you'd use a fixture for are, for instance, opening a connection to a database, inserting some canned data into some table, setting up some environment variables, replacing some global with a mock, etc. And then undoing whatever you did at the end of the test function run.

#

which are all things that in the unittest world you'd do in setUp() and possibly tearDown().

#

and pytest does it with a declarative syntax, so that instead of copy-pasting code between the setUp() methods of several different test classes that need similar things, you only need to declare which types of setup you need.

#

Am I making any sense to you?

#

maybe looking at some of the pytest builtin fixtures will make it clearer:
A test that depends on caplog will capture all logging calls made by the code under test so that assertions can be made about what was logged. At the end of the test normal logging is restored.
capsys works similarly, but for what is written to sys.stdout and sys.stderr instead.
recwarn works similarly, but for calls to warnings.warn() instead of logging.
monkeypatch allows performing monkeypatches that are automatically reverted at the end of the test.
tmpdir creates a temporary directory and passes the path to it to the test function. At the end of the test, the directory is removed.

Most fixtures don't merely return static data, they perform some sort of setup, and often some sort of teardown as well.

#

so if fixtures didn't exist, instead of py def test_something(capsys, caplog, recwarn, tmpdir): assert 1 == 1 you'd wind up doing something like ```py
def test_something():
with (
capture_logs() as caplog,
capture_sys_streams() as capsys,
record_warnings() as recwarn,
create_tmpdir() as tmpdir
):
assert 1 == 1

#

I feel like I'm overexplaining this, so I'm gonna shut up unless you tell me to keep going ๐Ÿ˜„

hollow basin
# split field Am I making any sense to you?

I think so. The one time I went on a unit testing spree, I did everything with unittest.TestCase and didn't wonder if there was a better way beyond thinking it was a weird way to use classes.

split field
#

yeah - unittest is borrowed nearly verbatim from the Java junit library, which is why a bunch of the names and patterns are much more Java-y than Python-y

#

pytest fixtures in a nutshell are a way to perform any necessary setup steps before running the code under test, and/or teardown steps after running the code under test, while allowing those steps to be declared and reused across tests.

hollow basin
#

For the purposes of demonstrating my programming abilities, I'm worried that having two globals and one assertion is going to be underwhelming.

split field
#

fair enough. without knowing anything about what your code does, I'd add a test that covers the mode="lenient" case, and the case where mode="something invalid". Are there any interesting edge cases in the code? Are there other types of invalid input? Are there cases that it took you a few tries to get right, that you want to make sure you don't break in the future?

twin pier
hollow basin
split field
#

A professional - or at least someone who's trying to look good - would probably do it anyway ๐Ÿ˜„

#

from the software engineering point of view, it's pretty normal to have 2x or 3x as many lines of test code as actual non-test code.

magic dawn
#

pytest is actually beautiful

#

the only thing I'd like is the ability to use fixtures in test parametrisation out of the box

#

but I guess you can't have everything

median aspen
#

Hello folks! I'm trying to do TDD python development but struggling to find test frameworks that run automatically in the background of my IDE without needing to interact with them (ie don't want to have to push "run tests" button). Something similar to NCrunch in Visual Studio. Google fu is failing me here, finding plenty of frameworks that need you to click a run button but what I'm looking for is on code change or at least on file save. Does this exist? Anyone know of a good framework and what IDE it plugs into?

vernal spear
#

Or perhaps a pre-commit hook if you're using git for your VCS

median aspen
#

I'll give these a look, thanks for the info. I've been using vscode but not against switching to PyCharm. I'll look into that, it looks promising, thanks!

vernal spear
#

FWIW, I would guess that VS code has similar functionality (or at least a plugin for it).

median aspen
#

Yeah had the same thought and found a plug in for file watching

rough jolt
#

How would one approach testing that โ€œwhen a connection is lost, the API should stop streamingโ€? I want to create a test for this issue, https://github.com/sysid/sse-starlette/issues/7 --- I checked starletteโ€™s tests, then looked at their testclient module. I see there is a WebSocketSession.Close (but Iโ€™m thinking this is the server closing the connection) whereas I need the client to be the one closing the connection. TestClient seems to not have a โ€˜closeโ€™ method or anything similar. Any pointers?

fiery arrow
#

Works with pytest, should work with unittest as well

#

this approach means less button presses, but if you're using hypothesis, it's going to constantly eat your CPU

whole hill
torn mirage
#

I believe those are shown in an environment that's restricted

brazen reef
#

Hello guys. I have a question. Is it possible to add a path and work with two work directories like in matlab?

median aspen
languid rock
#

I'm currently writing a unittest.TestCase implementation and I was wondering if there's a way to make my test_requires_dict method more DRY. Very new to unit testing. Here's the test class:

class TestDynamicObject(unittest.TestCase):
    def test_requires_arg(self):
        """ Should raise TypeError when not passed arg """
        with self.assertRaises(TypeError):
            DynamicObject()

    def test_requires_dict(self):
        """ Should raise TypeError when not passed dict arg """

        """ Test with string """
        with self.assertRaises(TypeError):
            DynamicObject('string_arg')

        """ Test with list """
        with self.assertRaises(TypeError):
            DynamicObject(['list', 'object'])

        """ Test with integer """
        with self.assertRaises(TypeError):
            DynamicObject(1)

        """ Test with float """
        with self.assertRaises(TypeError):
            DynamicObject(1.2)
#

Should I put all my test args in a parent list and then iterate through them within a single with self.assertRaises context or should they be separate like they are now?

vernal spear
#

I personally prefer having them in separate tests so that each component (individual test) focuses on as small of a bit of functionality as possible.

midnight basin
#

Regarding selenium, how can multiple instances of the Selenium driver run at the same time opening different URLs? :)

proper wind
#

Hello

#

People

#

I want to learn all kind of broswer and apps automation, what all to learn with selenium

#

Also web scraping, for that beautiful soup is best ?

rough jolt
proper wind
#

I was using selenium to open a web page, and by xpath find a button and I would get it's href value. How can I efficiently do the same thing through requests instead of selenium?

floral ember
proper wind
#
page = requests.get('https://google.com')

html = html.fromstring(page.text)

soup = BeautifulSoup(html, features="lxml")

for a in soup.find_all('a', href=True):
    print(a)
    print("Found the URL:", a['href'])

@floral ember soup = BeautifulSoup(html, features="lxml") ends up throwing me a TypeError: expected string or bytes-like object, any idea?

floral ember
proper wind
hollow basin
#

@split field to bring relevant discussion over here:
https://github.com/swfarnsworth/bratlib/blob/master/bratlib/calculators/entity_agreement.py#L96

This module has a measure_ann_file function that counts things based on a certain heuristic, so the unit tests for it ensure that it's applying that heuristic correctly. But then there's the measure_dataset function which is just using functools.reduce to merge an arbitrary number of calls to the first function. There's a lot less that can be messed up with the second function. If I wrote a test for it, would that be integration testing?

split field
# hollow basin <@!451976922361102357> to bring relevant discussion over here: https://github.co...

integration testing refers to a test that goes across multiple units. In a unit test, you define what code you're testing, and break dependencies on other components that are not being tested (using mocks or dependency injecting fakes, etc). In an integration test, you allow tests to cross component boundaries. Unit tests validate that a particular component works when used properly. Integration tests validate that one of your components uses others properly.

#

I'm not sure if that answers your question, though ๐Ÿ™‚

hollow basin
# split field integration testing refers to a test that goes across multiple units. In a unit ...

Hmm, let me make my question more specific to what I might do with the answer you give me:

reduce(
    lambda x, y: x.add(y, fill_value=0),
    (measure_ann_file(gold, system, mode=mode)
     for gold, system in zip_datasets(gold_dataset, system_dataset))
)
  • functools.reduce does not need to be tested
  • DataFrame.add doesn't need to be tested
  • measure_ann_file is tested by another test
  • zip_datasets is tested by another test
    But I still want to have a way of finding out if this function were somehow broken, or if a change made in another component didn't necessarily break that component but did break this function.

But what do I really test? Just that it returns a dataframe? (You don't necessarily need to know the exact answer.)

split field
#

I usually consider the "unit test" versus "integration test" line to be drawn based on whether it's testing the code within my module (unit test) or testing how my module interacts with its environment (integration test). So, if measure_ann_file actually opens and reads a file from disk, that's integration test territory. If it's using hardcoded data that has been injected or mocked or faked, it's unit test territory.

As for what to test - I'd say inject known values, and validate that you get the expected outputs, if that's not impractical to do. Not just that you get a dataframe, but that the dataframe's contents are what you expect them to be.

vernal spear
#

For tests that open & read files from disk, would it still be an integration test if you use the tempfile module (or a fixture) to create data just for the test itself?

#

Asking because, I almost always use tempfile when writing tests for functions that open/read/write files.

hollow basin
#

That means I'll need to monkeypatch measure_ann_file to generate a specific set of dataframes, regardless of what is passed to it

#

hmmmmmmmmmmmm

split field
#

I'd say yes, personally, but the line is blurry. Unit tests should be very fast - 1ms as an upper bound on how long it should take to run one, I'd say - and things that interact with the filesystem, even to read a temporary file, are not fast.

#

^ @evilbiologist if that wasn't clear

vernal spear
#

That makes sense/seems reasonable. As a follow up re fast tests, do you have any experience with writing fast PySpark tests? I work on/wrote a service at work that uses pyspark and running the entire test suite is pretty slow. I think ~8 minutes for a couple hundred or so tests.

#

Even individual tests are a bit slow, because one has to instantiate a spark context.

split field
#

nope, never used pyspark, or spark at all. But for the record, I consider a test suite that takes 2 seconds to run 1000 unit tests to be slow, heh

hollow basin
split field
#

Tests are better than no tests, regardless - but I really like being able to rerun the full test suite whenever I make a change to see if I broke something, and if the test suite takes more than a few seconds to run that's really painful to do. If the test suite breaks out unit tests from integration tests, I'll usually only run the unit tests as I'm iterating, and save integration tests for later, just because I want something fast.

hollow basin
#

if my pytest test has monkeypatch as the name of a parameter, does that have unstated magic behavior?

vernal spear
#

It would if you have a fixture named monkeypatch, i think

split field
#

there's a builtin fixture named monkeypatch

#

it's an instance of a class that has methods for patching and unpactching stuff, and that automatically undoes the patches when the function ends.

vernal spear
#

ahh, gotcha. I've only ever used the patch decorator

#

and Mock or MagicMocks

split field
#

so the only "unstated" behavior, I think, is that any patches that you make are automatically reversed when the test function finishes.

hollow basin
#

By "unstated magic behavior" I guess I'm referring to the meta-programming phenomenon we were talking about before.

split field
#

right - well, the same as any other fixture. The monkeypatch fixture does some setup (creating an instance of a class with some specific teardown behavior), then that instance is passed into your test function (with instance methods that let you apply and unapply various monkeypatches), and then after your test ends that fixture has some teardown that happens (any patches that you haven't already unapplied are unapplied)

#

there's nothing magic about it above and beyond the "normal" fixture magic, where the name of the test parameter is introspected, and pytest decides to create and pass you an instance of the monkeypatch fixture because it sees monkeypatch in your parameter list.

floral ember
magic dawn
#

That makes sense/seems reasonable. As a follow up re fast tests, do you have any experience with writing fast PySpark tests? I work on/wrote a service at work that uses pyspark and running the entire test suite is pretty slow. I think ~8 minutes for a couple hundred or so tests.
@vernal spear PySpark is unfortunately slow

#

Iโ€™d suggest isolating as much as possible

stark badger
#

hi all i really need help with selenium

#

this is the xpath that i use but it says that is not a valid xpath

#

//*[@id="pane-side"]/div[1]/div/div/div[24] this is the xpath of that specific div, the thing is dont want the specific one, because the site is dynamic and the path would change

#

the only thing that remains is the style="transform: translateY(72px)" that means is the first one to appear

#

im trying to get it with tah xpath but it doesnt work

sour bone
#

if i want to determine what happens post form submission with selenium how could i do that

#

like some callback

knotty vault
#

hello guys

#

im having some errors at web scraping

#

i just try to use the GET method in a page

#

that wouldnt have to appear because the website works perfectly

#

any ideas?

proper wind
#

@knotty vault, that site seem to require User-Agent. Set it to something to fix the issue.

page = requests.get(url, headers={'User-Agent': 'foobar'})
muted lichen
#

Does anyone one else think pytest fixtures are meh?

#

Maybe it's bc my class that I'm testing but like it seems that if you need to change the input a lot they're not that great

whole shuttle
#

Is it just me; or for pyautogui; the locateCenterOnScreen just replies none to it. Is it just a mac issue; or what exactly is the case. Be sure to dm me if you need ( I will respond tmrw as i am going to bed)

half hemlock
#

hello @proper wind

#

am going headless
and am using this website to test if it's detectable, and its detecting it via plugins length and the hairline feature
any recommendation
?
am using python selenium
Thanks in advanced

mellow elbow
#

hey does simebody know how to disable console log?

chilly yacht
#

where do i start my testing journey

rapid socket
#

Hey guys, what is the best framework to use in Python? I've been just using debugger, and print statements in my IDE for the time being but need to branch out

split field
#

!rule 5 @half hemlock

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.

analog hornet
#

hey, Is there a way in which one can use mechanicalsoup and selenium together?. Basically my issue is that I'm using mechanicalsoup but now there's this particular form (a search form) who's input field doesn't have a name attribute and it needs to be filled so that the form can submit... ..any suggestions

half hemlock
versed kettle
#

Hey, anyone have used selenium and got IE mode working with Edge?

#

I only managed to got either Edge in default/normal mode or actual IE to open. Haven't found anyone actually got it working, people just seem to link to this Microsoft blogpost but never heard anyone say they managed to get it to work.

languid sentinel
#

Hello

#

what should i test in CRUD application that consist of only function do interact with SQLite3

rapid socket
heavy turret
#

Hi guys, are there any web sites contained examples I can do to improve my python skill? Just beginner here

rich jay
#

!resources

bitter wadiBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

rich jay
#

@heavy turret

#

go the the website I think

heavy turret
#

Ooooh

#

They have easy examples or problems?

#

I'm just a beginner.

#

I'll check it out. Thank you so much.

lusty shore
#

im new into testing

#

like 10minutes

#
import unittest
from math import gcd
from main import (
    basic_euclidean_algorithm,
    optimized_euclidean_algorithm,
    recursive_euclidean_algorithm
)


class TestEuclideanAlgorithm(unittest.TestCase):

    def test_basic_euclidean_algorithm(self):
        for i in range(0, 20):
            for j in range(0, 20):
                self.assertEqual(basic_euclidean_algorithm(
                    i, j), gcd(i, j))


if __name__ == "__main__":
    unittest.main()
#

i would like to test mine euclidean alg

#

how it works

#

i would like to use it for running a milion times

#

and is it working?

#

couse it stops on i,j == 1

analog hornet
marble ibex
#

I want to make a python file that can copy itself to system startup, but if it is in the startup folder it should not execute the part of copying itself to the startup else it will duplicate, how to do that, also i want to then hide that file using attrib +h +r +s +a file.name command of cmd

marble ibex
#

i dont know where to send it so i sent it here

proper wind
#

i converted my program into exe but it not running ,why ?.

hollow basin
#
reduce(
    lambda x, y: x.add(y, fill_value=0),
    (measure_ann_file(gold, system, mode=mode)
     for gold, system in zip_datasets(gold_dataset, system_dataset))
)

I need to monkey-patch measure_ann_file so that the whole generator expression returns fixed objects, but since it's already in a generator expression, patching it with another generator just causes that generator to get popped out rather than the type it's meant to return.

#

Silly me: measure_ann_file is a function, so I needed to mock n calls rather than have a generator.

drifting mirage
#

can anyone point me to a direction how to test a single function that asks for multiple inputs using input()?

split field
drifting mirage
tall jacinth
#

when would unit tests succeed but integration tests fail?

#

i've never run into a situation like that, so integration tests have always felt useless

kind meadow
#

Well I suppose you could write a test for unit that depends on the other to mock and assert the calls of the other unit, but I'm not sure if that should still be considered a "unit" test.

#

It's sort of vague what a "unit" even is anyway

tall jacinth
#

@kind meadow that's what i usually end up doing. instead of making an integration test where unit A passes 3 to unit B and I assert that the interaction worked, I make 2 unit tests. One where I assert what A returns is 3, and one where I make a mock returning 3 and assert that B works with that

kind meadow
#

What I dislike about that approach is that the tests tightly couple units to each other

#

Which makes the tests more of a burden when code has to change down the line

#

But it's a trade-off

tall jacinth
#

I think as I get more and more experience, I make "units" more broad. for example at very start, I would always doMock(spec=str) when passing strs to these units as part of testing (to make it so I wasn't testing two "unit"s)

#

but now that seems a bit overboard...

tall jacinth
#

@kind meadow i'm thinking about an objective way I could define a unit, what something outside of the environment? so IO, random numbers, etc. would always be separate units that would be mocked, whereas other units might be better grouped under an integration test instead of doing mocking for the sake of mocking

kind meadow
#

I've not found a good definition

#

I just have some vague idea of what should be a unit from experience and go by gut feeling

#

I've seen plenty of conflicting definitions

#

Like I've seen some say a unit is the smallest testable public part of an interface

#

But I think there's value in testing private helper functions too if they're significant enough

proper wind
#

i installed pygame module when initalize the pygame.init then i an error says module has no variable.
how to fix it ?.

hexed flame
kind meadow
kind meadow
proper wind
#

How can I use selenium's find_elements_by_xpath based on text, when it may or may not have a word?

Example: it can be either #1 here or #1 is here. I want both to be part of the same list, since that func return a list. ATM I have driver.find_elements_by_xpath("//*[contains(text(), '#1 here')]") but that would only find the first case, not the ones with an is. How could I do that?

next falcon
#

Im not sure if this goes here but

#

im new to python

#

and im working on a project with selenium to post some tickets to see if theyre open

#

we usually have to check them at the end of every year

#

its like 5000

#

so im attempting to automate them

#

can you render any assistance

#
# selenium
from openpyxl import load_workbook
import unittest
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.keys import Keys
# pandas data science
import pandas as pd

report = pd.read_excel(r'report.xlsx')
print(report)
# Excel Import
# webdriver
driver = webdriver.Chrome()
# sabre redirect
driver.get("https://accounts.havail.sabre.com/login/srw?goto=https%3A%2F%2Fsrw.sabre.com%2Flogin%2F%3Fts%3D439070&force=true")
# login info
driver.find_element_by_id('username').send_keys('1994')
driver.find_element_by_id('password').send_keys('_______-')
driver.find_element_by_id('pcc').send_keys('_________')
driver.find_element_by_id('submitButton').click()
# wait for page load
WebDriverWait(driver, 25).until(
    EC.presence_of_element_located((By.ID, 'cmdln')))
# enter data
# data values

driver.find_element_by_id('cmdln').send_keys(report)
driver.find_element_by_id('cmdln').send_keys(Keys.ENTER)
# read excel data
proper wind
#

hello I need help

#

with requests.session() as s:
url = "URL"
r = s.get(url, headers=headers)
print(r.content)

#

uhh so I cant get the html

#

even if I added the headers, does anyone have a solution?

robust plank
#

you need the beautifulsoup

#

you can try:

request = requests.get(url)
soup = BeautifulSoup(request.text,'html.parser')
header = soup.header

print header
#

if you type in "requests.get(url)" you will see that your object is: <Response [200]>

#

That is a good response. If it's bad, I don't think you can work with it

#

But you can't read the requests object directly. You need BeautifulSoup to parse the HTML

#

@proper wind forgot to tag you

#

Also FYI: AttributeError: 'Response' object has no attribute 'session'

#

and from bs4 import BeautifulSoup is how to import BeautifulSoup (assuming you already did the pip install)

cobalt locust
#

A colleague of mine and me having a "best practice" debatte about how to write tests. We are using pytest as the testing framework. We both agree that a test has essentially three components: : setup, call and assert. Where we both disagree is, where to put the setup code. One opinion is, the setup code belongs directly in the test so everyone can see in which environment the test is running. The other opinion is, to have as little setup code in the test method itself as possible and use fixtures or normal method calls to do the setup. The benefit of this: Faster recognition of what is tested and expected when reading the code. Knowing about how the environment is set up isn't important in first place, but can be accessed with a few clicks more. Opinions?

leaden nimbus
#

can someone help me am working on a virtual shop but... i need help to add how much you want and multiply it with the price to get the total

vapid spoke
#

Why doesnt it make the folders as intended ? ` import os
import shutil

current_dir = os.getcwd()

for f in os.listdir(current_dir):
filename, file_ext = os.path.splitext(f)

try:
    if not file_ext:
        pass

    elif file_ext in ('.py'):
        shutil.move(
            os.path.join(current_dir, f'{filename}{file_ext}'),
            os.path.join(current_dir, 'Python files', f'{filename}{file_ext}'))
    elif file_ext in ('.jpg', '.png', '.gif'):

    else:
        shutil.move(
            os.path.join(current_dir, f'{filename}{file_ext}'),
            os.path.join(current_dir, 'Andre filer', f'{filename}{file_ext}'))

except (FileNotFoundError, PermissionError)        :
    pass `
candid light
vapid spoke
#

I just fount it online, and adjsuted the name of the folder. I intend, when i run the script that it takes all files in the directionary and sort it out to the specific file types like this https://learndataanalysis.org/how-to-organize-your-files-with-python-python-tutorial/ @candid light

In this tutorial, I will be sharing a very useful Python script I use very frequently when I need to organize my files by file type.

candid light
#

Okay. Seems fine to me. Copied the code and tried it out.
What does not work as you want it to?

vapid spoke
#

It only makes the "else" folder, and not the other folders that are supposed to organizae e.g. the python files in the python folder and so on

candid light
#

You could edit the except statement to:
except Exception as e:
print(e)
And take a closer look at what happens in your script

vapid spoke
#

I aint so sure what you mean, i am totally new in the "space"

candid light
#

At the bottom of your code is the "except" statement. This will catch all Errors that occur during code execution and execute the code inherited.

#

At this time this is "pass" which will not print you anything or give you any other information. This is bad for debugging your code.

vapid spoke
#

Ok. so delet except (FileNotFoundError, PermissionError) : pass

#

and tahn put in except Exception as e: print(e) instead?

candid light
#

yes like this

except Exception as e:
  print(e)
vapid spoke
#

ok

candid light
#

Properly indented as you can tell for sure.

vapid spoke
#

yes

candid light
#

^^ it needs to be the same indentation as try:

vapid spoke
#

ok ๐Ÿ™‚

candid light
#
try: 
  pass
except:
  pass
vapid spoke
#

Yes i understand ๐Ÿ™‚

#

I know this script is different from one i send by start but it still gives me error on the identation

candid light
#

Unfortunately I can't tell what is wrong with the indentation. Make sure you are using no tabs and 4 spaces indentation through your script.
This is a common issue when copying code from the internet.

#

Maybe it is the blank line above the except statement. I'm sure you can figure this out! ๐Ÿ™‚

vapid spoke
#

Okay it was in the except statement

#

i had done a tab instead

#

but it still does not make the directionaries for me ?

#

It on says it does not exist

candid light
#

But that's is good! We are getting closer!

vapid spoke
#

Yes i know ๐Ÿ™‚

#

But i do not undertstand why it does not create the folder and add in the respective files

candid light
#

In the documentation it says:
"Recursively move a file or directory (src) to another location (dst) and return the destination.

If the destination is an existing directory, then src is moved inside that directory. If the destination already exists but is not a directory, it may be overwritten depending on os.rename() semantics."
https://docs.python.org/3/library/shutil.html?highlight=shutil#module-shutil

I think you need to extend your script to create the folders, if they do not exist.

vapid spoke
#

But it automatically create the folder situated in the "else"-statement, why does it not create the other folder than?

#

Okay i created the folders accordingly and now the script works, but i still do not understand my last question

candid light
#

I tried it on my machine and I'm encounting the same issue with the script not creating the folders.
I only can trace the issue so far that shutil.move is not trying to create the directory instead it tries to write to a file which doesn't exist.

vapid spoke
#

Yes okay. But if i make the correct folder it moves it, which is my intention

candid light
#

glad I could help. ๐Ÿ™‚

vapid spoke
#

Thanks ๐Ÿ™‚

kind meadow
# cobalt locust A colleague of mine and me having a "best practice" debatte about how to write ...

It depends on how much set up code there is and whether it can/will be re-used. Keeping code localised can be helpful, but it can also backfire if there is a lot of code. Monolithic functions are terrible for readability.

Furthermore, if the code needs to be re-used, then it should be put into a fixture without exception. If it's a short one off-thing, just throw it into the test function. Could be argued that such inconsistency is bad, but I don't seem to mind it.

#

This arguably goes beyond writing tests. I generally prefer to split code up into logical groupings, even if those functions are only used once. It helps me follow my code. Besides the performance overhead of extra function calls, there is also overhead in having to come up with a good name and possibly add docstrings and type annotations. I think it's worthwhile.

#

If your fixtures have good names then a reader should have a good enough idea of what's going on without needing to see the exact set up code. As you wrote, the setup isn't necessarily important to see in that context.

split field
# cobalt locust A colleague of mine and me having a "best practice" debatte about how to write ...

I picked up a habit from a coworker that I think helps with this. It comes from Behavior Driven Development, originally, but I apply it to pytest tests as well: every single test function gets split into 3 sections, separated by comments: ```py
def test_some_thing(fixture1, fixture2):
# GIVEN
mock_something()
mock_something_else()

# WHEN
do_something_Using_the_mocks()

# THEN
assert effect1
assert effect2
#

And everyone can read it without being told what it is, and worst case scenario they just ignore the comments and read the test from top to bottom anyway. It can be a bit tough to get other people to stick to the style - stopping people from testing multiple things in one test function is hard; they want to do it because those things share common setup code and they don't want to repeat it. But other than that, I like this a lot: it adds clarity to test functions at the cost of a bit of discipline.

#

I wouldn't factor setup code and post-condition checking code out into other functions or fixtures unless they're intended to be reused. Beyond that, it's a judgment call. I don't mind seeing a single line of setup that's copy-pasted into most tests and only tweaked occasionally, but if that becomes 5 or 10 lines I'd almost certainly refactor it into a fixture or helper function.

kind meadow
#

@cedar pagoda I've seen a test suite for a tool that worked with files, and it just used tempfile to create temporary files for tests

#

Is that what you were asking about?

#

Or are you asking how to assert that your code has proper checks for existing files/dirs?

kind meadow
#

I'd approach it by giving it a directory that doesn't exist and then seeing how ti responds (e.g. asserting it raises an exception or returns some alternate value)

cedar pagoda
#

Eventually though, in order to make the assert pass wouldn't you need to point it to a structure that's similar?

#

Would I have to artificially create some example folder structure along in the package?

kind meadow
#

You need to test a complex directory structure?

#

I'm not sure if there's a better way to do that actually

cedar pagoda
#

It sure seems complex to me lol

#

I'm using os.walk to look for a file starting from a path the user will pass in

#

Say I'm looking for a file called "optimization.log". The folder it appears in gets made regardless of whether the pipeline that calls it succeeds or not.
We want to parse that file

kind meadow
#

I can't think of another way than just creating temporary directories

#

Like you can create a temp parent dir and then assert that the folder got created

cedar pagoda
#

Hmm, as in make it on the fly?

#

And then cleanup afterwards

kind meadow
#

Make it in your test, before you call the function.

#

tempfile uses a context manager and can do the cleanup for you.

#

I don't think there's an easy way to mock a directory structure instead of just creating it temporarily on the filesystem

cedar pagoda
#

That's the best approach I've heard so far, since I'm testing a folder structure, I suppose I need an actual folder structure lol

#

And this does not sound like I'm testing the wrong thing, does it? I think it's called the XY problem haha

#

The fact that it's not clear how to test it, it's not some symptom that maybe I'm testing the wrong thing (and there's a better way)

kind meadow
#

I'm not sure. I don't have enough context. But it sounds realistic.

cedar pagoda
#

Thanks for the rubber ducking, I'm a lot happier with the context manager idea than packaging a full folder!

kind meadow
#

You're welcome

proper wind
#

IDK how to fix this. I already turned the str in to a int but it still din't subract?

trail river
#

look at line 16

#

is both an int

#

if not you have to do:

new_var = (int(var_1) - int(var_2))
#

@proper wind

#

Worked?

proper wind
#

nope @trail river

#

I got a new error

trail river
#

can you print pls var

#

@proper wind

proper wind
trail river
#

can you send me the code pls

proper wind
#

from bs4 import BeautifulSoup
import requests

source = requests.get('https://chap.manganelo.com/manga-dr117685').text
soup = BeautifulSoup(source, 'lxml')

for chapter in soup.find_all('li', class_='a-h'):
current_chapter = 134
chap_src = chapter.find('a', class_="chapter-name text-nowrap")['href']

chap_num = chap_src.split('/')[4]
chap_num = chap_src.split('-')[1]
print(int(chap_num) - int(current_chapter))
#

btw solo leveling is a good manga you should read it ๐Ÿ˜„

trail river
#

and please the full code

#

you missed a bit

tulip island
#

@trail river

#

what a wonderful site ๐Ÿ™‚

trail river
#

@proper wind

tulip island
proper wind
#

?

#

I am just new ๐Ÿฅฒ

trail river
#

Give me the full code

#

You missed a bit

proper wind
#

I did

#

from bs4 import BeautifulSoup
import requests

source = requests.get('https://chap.manganelo.com/manga-dr117685').text
soup = BeautifulSoup(source, 'lxml')

title = soup.find('div', class_='story-info-right').h1
print(title.text)
for chapter in soup.find_all('li', class_='a-h'):
current_chapter = 134
chap_src = chapter.find('a', class_="chapter-name text-nowrap")['href']

chap_num = chap_src.split('/')[4]
chap_num = chap_src.split('-')[1]
print(int(chap_num) - int(current_chapter))
tulip island
proper wind
#

oh

tulip island
proper wind
trail river
#

wtf

#

It is still not there

proper wind
tulip island
trail river
proper wind
#

I got a new problem

trail river
#

You should use brain

proper wind
proper wind
trail river
#

Put the print like I did

proper wind
trail river
#

link

proper wind
trail river
#

it makes no sence

proper wind
trail river
#

It's like:

x = 3
x = 4
print(x)

proper wind
#

hahahaha

trail river
#

It is the same as:

x = 4
print(x)

proper wind
#

I guesse there is no solution ๐Ÿ˜ฆ

#

thanks for the help ๐Ÿ˜„

trail river
#

no problem.
Start with something easy

#

Like calculator with input:
number_1 = input("Please write you first number")

proper wind
#

that is bs

#

hahaha

#

to easy

trail river
#

ok, write it

proper wind
#

write what?

trail river
#

calculator with input

proper wind
#

oh sure

#

give me a sec

trail river
#

there you should understand how var work

proper wind
#

try:
num1 = float(input('Enter a number: '))
op = input('Enter the operator: ')
num2 = float(input('Enter another number: '))
if op == '+':
print(num1 + num2)
elif op == '-':
print(num1 - num2)
elif op == '/':
print(num1 / num2)
elif op == '*':
print(num1 * num2)
except ValueError:
print('Invalid Value')
except ZeroDivisionError:
print(f'Cannot divide {num1} with {num2}')

#

look men I was just following someones tutorials

trail river
#

but there you see thing, you made wrong.
There are two var
numb1 and num2
You made 2 numbers on one var in the first script you sent

kind meadow
acoustic kraken
#

Is there a way that I can create a Python script that when running will launch a web browser and capture HTTP requests?

The context of this is for performance testing. A customer describes a flow for their website, ie. Launch URL, login, click button. I need to create a Python script that will simulate this flow. Other tools like LoadRunner allow you to start recording traffic in a browser, and it captures which HTTP requests are being sent, then creates a script that will make these same requests.

I know I could do it manually by examining a network log, or by exporting a har file and converting that to python, but I'm trying to take those steps out of the process.

If you have any ideas, please @ me.

kind meadow
acoustic kraken
#

I thought Selenium was just to replay the requests, but I'll look into it more

kind meadow
#

You're in the wrong channel.

slim echo
#

Sorry

#

I was told by somebody else I should look into science stuff, and I found this channel that seemed more relevant @kind meadow

kind meadow
#

If you read the channel's description, you'll see it's about automated software testing

#

Like unit testing

slim echo
#

Ah.

#

so im in the wrong channel anyways

crimson oasis
#

I am currently scrapping 10+ websites(using chromium separate pages) to notify me when a product is available but it is very taxing on the machine I am running it on. What are some methods I can use to reduce the impact selenium and chromium have on my machine? (I am also using threading to run the multiple chrome pages)

tardy elm
#

How can I write tests for a scraper that determines several things from a url? The status of things on the url may change, so sending the actual request for the test may cause tests to break if any status in the url is updated. Should I just save the html from a request in a static file and read that for the test that way I will always know the expected output from the tests?

molten vapor
#

I want to automate with python basically make robot that itself opens sites and surfs internet. Where I can start and which library I can use for that

tardy elm
#

@molten vapor, I don't think your question is related to the channel topic of "automated testing", but the libraries requests and BeautifulSoup are a great place to start

acoustic kraken
idle brook
#

Hi! I try to test the following function, but I have troubles testing the exception:

def sys_output(command: list, path: Path = None, timeout: int = None) -> str:
    try:
        output = check_output(
            command, cwd=path, text=True, stderr=PIPE, timeout=timeout,
        )
    except CalledProcessError as e:
        raise CalledProcessError(
            f"Command '{e.cmd}' return with error (code {e.returncode}): {e.output}"
        )
    return output

This is my test function. Any quick insights why it doesn't work?

@mock.patch("syscmd.check_output")
def test_sys_output_CalledProcessError_exception(mocked_check_output) -> None:
    mocked_check_output.side_effect = CalledProcessError(returncode=1, cmd=["echo"])
    with pytest.raises(CalledProcessError):
        sys_output(["echo"])
kind meadow
#

My only idea is that your patch didn't work

#

You may have patched the wrong thing

edgy pebble
#

selenium python is opening 2 chrome windows instead of 1

#

can some help me fix this problem

bitter wadiBOT
#

Hey @edgy pebble!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

โ€ข If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

โ€ข If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

edgy pebble
#

!code-blocks

bitter wadiBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

edgy pebble
#

selenium python is opening 2 chrome windows instead of 1
can some help me fix this problem

#

pls find a solution for this

fiery arrow
molten vapor
molten vapor
molten vapor
jolly cape
#

O

#

Beautiful soup?

#

Thn?

molten vapor
#

I never tried?

jolly cape
#

Me too?

molten vapor
jolly cape
#

Yes

#

I think

molten vapor
#

I'm going to test