#unit-testing
1 messages · Page 16 of 1
Does anyone else feel like selenium moves too fast sometimes?
it is for automating testing, in what ways do you think it’s too fast?
Hello guys, I am asking myself some questions about testing, specifically functional testing. I have encapsulated complex user-processes into service functions. For instance, this:
class FooTest(unittest.TestCase):
def test_foo(self):
response = client.post(url, data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
response = client.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertIn("bar", response.data['text'])
self.assertEqual(response.data['value'], 1.23)
Gets refactored into
class FooTest(unittest.TestCase):
def test_foo(self):
client.post_and_get_result(url).assertInText('bar').assertValueEqual(1.23)
(this refactor obviously actually applies to long and repetitive occurrences of these scenarii)
My question is: do you find chaining assertions like this (thanks to a helper class) a bad practice or should I instead do something more like?
result = client.post_and_get_result(url)
result.assertInText('bar')
result.assertValueEqual(1.23)
Which would vastly decrease readability of my tests imo.
My opinion is that chaining is fine and preferred, as long as the ordering is basic => complex
In other words, basic assertions (such as "yes this is a dict") fail before more advanced ones ("this dict has these keys and these values")
That helps with clarity when the tests fail
It's a waste of time to hunt down a data interpretation issue when it was simply a case of a stray None
@calm sky ^
Also, you should check out pytest
I just got a job as a QA Automation Engineer and tbh I’ve never really worked with large scale tests at this level. I’ve used unittest, pytest, and selenium but haven’t really used them as much as i will he now. Do you guys have any resources or videos you recommend i check out to learn more about it
@tawny wave ^^ woop woop
@tawny wave yes, I of course have tested behavior encapsulated in my user-defined assertions beforehand, these are mainly to reduce the size of my functional tests which otherwise get huge and very painful to read and refactor functional test functions.
I was only "worried" about the "non-idiomatic" nature of chaining assertions like that, but I came to the conclusion that it still is the best option in my situation.
Yeah I also know about pytest, but do not use it in this project because the whole test architecture is already relying on "classic" TestCase classes, which is pretty ok to be honest, it just sometimes needs a bit more explicit directives.
@pure crystal I do not know about how advanced you are in that subject but I found Obey the Testing Goat an awesome read for beginners and intermediate level TDD. Very easy to read, very practictal, detailed, with real-world examples, all of this for free (the book is publicly readable online).
Thank you so much! I will be sure to check it out now @calm sky
@pure crystal Congrats man! You should ask your employer if they'd be willing to buy a few books for you. One I'm about a third of the way though is Python Testing with pytest: https://www.amazon.com/Python-Testing-pytest-Effective-Scalable/dp/1680502409
I've also heard Obey the Testing Goat is good, if you're doing web development.
@tawny wave how's the Pytest book so far?
It's alright
Lots of stuff I didn't know about Pytest and you might not learn from the docs
consider me sold
@calm sky this guide is amazing!
What sources would you recommend to someone who has not done any type of standard testing?
Skimming the unitest and pytest docs (https://docs.pytest.org/en/latest/getting-started.html#install-pytest)
Looking at how well-established open-source projects like requests, django, etc. test their code
PyData Carolinas 2016 Testing software is just as important in Python as it is in any other programming language. Rather than treat testing as a “necessary e...
@spice holly ^
Thank you again @tawny wave
is there a way to automate building the build file
there's a way to automate anything if you try hard enough
The mocks for my tests are absolutely disgusting right now. I'm copy-pasting the mock.patchcalls between tests and changing the flag values (True/False). Is there a better way to be setting these variables in pytest using fixtures or paramaterization or something?
Example of a test (note the mock.patch calls):
def test_linux_ifconfig(mocker, get_sample):
mocker.patch('getmac.getmac.WINDOWS', False)
mocker.patch('getmac.getmac.DARWIN', False)
mocker.patch('getmac.getmac.BSD', False)
mocker.patch('getmac.getmac.OPENBSD', False)
mocker.patch('getmac.getmac.FREEBSD', False)
mocker.patch('getmac.getmac.LINUX', True)
mocker.patch('getmac.getmac.WSL', False)
content = get_sample('ifconfig.out')
mocker.patch('getmac.getmac._call_proc', return_value=content)
assert '74:d4:35:e9:45:71' == getmac.get_mac_address(interface='eth0')
Full code here: https://github.com/GhostofGoes/getmac/blob/master/tests/test_samples.py
At the end of the day, you have to supply true or false for each of those somehow
so you're really just moving it somewhere else with other solutions
at most you're saving typing mocker.patch() a bunch
That being said, is the rest of the test the same besides setting those variables? In that case, I can see how it could help to move them out
as it'd leave you with essentially only 1 test function, which is what you seem to want, right?
You could use a fixture and parameterise the fixture, but if these only need to be set for one test then I don't see a point in a fixture - you can parameterise the test function itself if it wont get in the way of other things
I should have just looked at the full code. Doesn't look like all the tests are exactly the same. I don't think a parameterised fixture will work as, for a given test function, the fixture would get called with each of the possible parameters the way I understand it.
I don't really see how this can be addressed without making your test function(s) more generic
What are your tips for linting a flask backend application? What should i focus on. For some context, we have 2 full flask backends. On one side we have 3 different apps under the same endpoint which work in unity. The other is a single app but still the entire backend API. What should I focus on when linting these projects? My IDE constantly yells at me about imports but i know they are right because it just cant read the PYTHONPATH correctly. So i guess im asking apart from max-length lines and imports what should I focus on when linting python?
I used ESLint for our react frontend to help guide me and fix a lot of shit for me but python linting seems to be so different.
Also if you know anyways to get VSC/PyCharm to shut up about our imports and how they are absolute id love that
How can I inject pytest fixtures for whole test class and have them accessible as attributes? Like this:
@pytest.mark.usefixtures('user')
class TestSomething:
def test_lol(self):
self.user
Thanks @kind meadow
Hmm, I'm not sure neumond, still learning pytest myself
Just realized I could just do mocker.patch('platform.system', return_value='Linux') instead of all the manual patches of the variables
I was able to find how to do this, e.g.
https://hackebrot.github.io/pytest-tricks/fixtures_as_class_attributes/
but I'm curious why pytest developers didn't make this a part of core functionality.
now that's a hack if I've ever seen one
Actually, patching platform.system isn't workingt, because the variables are being set at import time...
wow that is a hack
I am having some problems with json.load()
Here is my current code
with open(os.path.dirname( 'data.json', 'w+') as json_file:
data = json.load(json_file)
data.json contains for now
{"data":{}}
I am getting the error, Expecting value: line 1 column 1 (char 0)
Any suggestions?
@tranquil ridge You're opening it in write mode. Try replacing 'w+' with 'r'
ye i got it, thanks
@chilly raft hello I recently made a snake in python I'm a noob with this language but I did it, I compile it to an .exe with pyinstaller, but I have the font that I use in a separate directory and I do not know how to compile it together with the game. can you help?
@plucky rose It's similar to your problem I hope it helps https://stackoverflow.com/questions/21800218/pygame-font-not-working-after-py2exe
I've got a Django project that calls celery tasks. Every time I run unit tests, it schedules hundreds of tasks. How can I make it not do that?
Other than mocking out all my signals (most of those tasks are triggered through signals) in all of my test cases...
To be clear: I'm not interested in the results or side effects of the celery tasks in those tests.
does anyone need help with pygame im the right person to ask
How do I clear selenium chrome history?
Hmm. Bumping old q but @granite burrow Maybe you can try navigating to chrome://history ?
https://intoli.com/blog/clear-the-chrome-browser-cache/ @granite burrow
@timber tree I have seen that already, it didn't locate the button for me, but thanks. :)
But I have already solved it just by pressing Tab.
Hey guys, my company purchased a license for Squish Qt to automate some of their Qt GUI before I joined the company. I've been tasked to pick up that project and work on it.
I'm wondering if anyone here has experience with Hooq or Funq, two libraries that do a similar thing (hook into the Qt layer to pull out widget data and pass Qt events into the app).
The main thing I already dislike about Squish Qt is how much they try to keep you in their ecosystem of tools, so I was looking around for alternatives.
Is it possible to run unittests in a watch type mode? if you are familiar with jest for js testing you can pass the --watch flag and it will run tests on the files changed when theyre saved
I should mention im using the actual unittest library as well
@pure crystal would something like this help? http://eradman.com/entrproject/
I recently packaged my PyQt5 program as an executable using pyinstaller and I am getting notifications that it is a virus/trogan and programs are quaratine the .exe file.
Any suggestions to go about fixing this issue?
A few sources suggest to find an alternative compiler while others suggest it may be due to my code .
Thoughts?
i think sometimes stuff like pyinstaller will be generating executables that scanners havnt seen before and that they pick up on the scripting/'self modifying code' like behavior. if you can sign pyinstaller generated apps it might help, or see if you can submit it to the main scanners to get it cleared
@keen willow what doean by "sign"? I was contimplating about exploring putting it on the windows store in the future. That might help with the windows defender marking it.
So 'signing' something generally means that you use cryptography to mark a file by using whats called a certificate. for app signing, youll need to mark it with who made it and also get another trusted source to say that you are who you said you are and then figure out how to include that certificate with your program.
I dont know much about how windows does signing, but for stuff like web pages there are a lot of 'trusted sources' call certificate authorities that are willing to authenticate your certificate and that most people already trust.
i know that windows complains when you try to run software that is not signed, so getting a Certificate Authority that Windows trusts to sign it is likely what youll have to look in to.
its possible it costs money however
Thanks for the information. Good to know in the future if I take my project in that direction.
Yes, you need to get a code signing certificate
They can be a bit spendy, cheapest for personal use I've seen is ~$85
There used to be a CA that provided free code signing certs for open-source projects. However, that went away fairly recently unfortunately.
I guess I could drop this here.
So with the rise of AI, is Python a huge proponent in it? I heard C++ and Python could be used. I was wondering if Python could create behavioral attributes in AI?
First every language can be used its just maths, youre just getting recommended python because its support for that type of stuff library wise is good
Second if you can create behavioral attributes in an AI somehow python can for sure do it too (however I dont know wether thats possible so thats a clear "depends" from me)
It's important to note that a lot of the machine learning libraries: scikit, tensorflow are not using pure python but using C and C++ backends (or libraries which have those backends)
so yeah, C++ is used for machine learning but Python is able to bind to those libraries
Is there a best practice way to test REST API clients/wrappers? Obviously I can't test the api methods themselves and I should only test that the code I wrote works as intended. Does anyone know of any good examples of this, to see how to go about it?
Is it ok to start with tests that actually hit the api endpoints and then later mock things out?
[Wall-of-text]
Main Question:
- Has anyone had experience with figuring out how to use Selenium to correctly click on Vue.js dropdown options?
Background:
- MULTIPLE dropdown elements on the page uses Vue.js.
- Because of the way Vue.js is implemented on the page, each dropdown's selectable option elements do NOT appear near where the actual dropdown element is, within the HTML.
- Instead, they are added at into the bottom of the HTML, dynamically as each dropdown is expanded.
- Each one does NOT appear to have any unique attribute identifier that I can use to piggy back off via an XPATH locator method.
Example test steps:
- Navigate to the page on the UI.
- View the HTML, and verify the dropdown element exists in the HTML, and can be located properly. - Observe no option elements appear for the dropdown element yet in the HTML.
- Click on the dropdown element on the UI.
- Observe the dropdown's options elements now appear.
- BUT, observe the option elements do NOT appear near it within the HTML code.
- Instead, observe the option elements instead appear at the bottom of the HTML.
- Observe there do not appear to be any unique identifier attributes within the option elements' HTML code, so that where there are multiple dropdown fields expanded, they appear to be indistinguishable.
Additional Questions:
- Is the answer just to tell my DEVs to add some kind of identifier to those options elements?
- Is this possible, with the way Vue.js works, by auto-generating the HTML code for the option elements at the bottom of the HTML?
My ideas:
- One of the ways I can currently see of doing it, would be to use an XPATH locator, with text() value attributes to click on the expected option.
- However, I would prefer not to use this method, since the text values are not always the same either. :S
- Another way, could be to search for a count of the number of the parent options elements, before clicking the dropdown. - This way, after clicking the dropdown, an XPATH locator for the '//div[@class="vue_dropdown_options"][count+1]' could be used. - But this second method seem convoluted…
Let me know if y'all have an answer, or if you'd like a screenshot as an example! Thanks!!!
[End-of-wall-of-text]
.
Is using doctest instead of unittest for unit testing seen as unprofessional?
@lyric rose I wouldn't call it "unprofessional" per se, but it's definitely seen as an inferior testing tool
doctest is only really ok for the simplest of functions. For anything else, doctest will make your docstring very long very quickly.
So, because you need unittest or pytest for everything else, it just makes sense to ditch doctest completely.
+1
It's a shame because I like the idea behind it - it's trying to force developers to write more helpful, meaningful docstrings
Hi
Hello @proper wind
I like doctest for libraries, and pytest for any edge cases in those libraries, non-libraries, or anywhere else
It's definitely made some of my code clearer.
@celest vapor isn't it difficult if the library doesn't produce simple types like ints and strings?
I've been using it for pytorch, so that's matrices and tensors...
Things like images though, I'm not really able to test, but I'm not actually sure how to test those in a nice looking way in any framework
what about floats in the matrices?
don't you run into problems with textual comparisons?
Yeah, it's a bit annoying. I set it to ignore spaces.
There were some differences with the decimals after numbers in different versions of numpy too
how do you deal with that in doctest?
There's the #doctest: +NORMALIZE_WHITESPACE comment command
but that doesn't help with differing float digits, does it?
Nope. I have to use assertIsClose or something for those, or just stick to a specific version of numpy or whatever is generating the float strings
It's definitely not the best option, but it is useful for some library functions
Also, I'm struggling to figure out how to test this sound engine I'm making...
just listen to see if it sounds right! 😃
Heh. Well, that's what I've been doing, but I kind of wonder if I'd annoy someone maintaining servers for travis-ci.
Actually, that sounds like it'd be hilarious. I might enable tests on that and see if they have any audio at all. Maybe they have computer beep things?
someone test this?
https://github.com/aadesousa/Text-Based-Rome-Game
@wise crag This channel is more about writing your own tests, not getting others to test your code :)
yeah
Is there really no way whatsoever to make a post requests with selenium?
You might want to look into requestium
It's an integration tool that allows you to transfer cookies from a selenium driver object to a requests session and vice versa
when makeing alot of requests with this and than transfering to selenium it requires captcha after some time, but not when just uisng selenium and manually flling in forms
is this just the way these things work or is it fixable
if they are giving you a captcha eventually then you prob should check their ToS to see if they allow automation
if not youll need to see if they have an api or ask for them to stop.
basically it sounds like they are detecting your automation and intentionally blocking you
does anyone have any experience in testing flask?
(pls ping if you do)
I am trying to test a file upload to flask but I can't do a requests post
And currently the files is always empty
most likely you are sending wrong content type header so then flask does not know what kind of body that is
has anyone here had success with using python and selenium on angularjs pages? there's a lot of hassle involved with waits, there's some abandoned projects like pytractor, but I'm not sure if it's worth continuing to dig deeper if the end results is basically "use Java instead"
ping me btw
@limber saddle nope that was not the case.
But I ended up just feeding in the raw stream and that fixed it
Anyone familiar with pytest-cov and coverage?
@river pilot Is there any reason to use pytest-cov over coverage? Isn't pytest-cov just a package for the same thing?
Hi, I've been trying to use tox and it's pretty useful, but I have a major issue, for some reason I can't test with the py35 venv because every time I try to install the deps it will throw this error py ERROR: Complete output from command python setup.py egg_info: ERROR: Download error on https://pypi.org/simple/setuptools_scm/: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:719) -- Some packages may not be found! Download error on https://pypi.org/simple/setuptools-scm/: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:719) -- Some packages may not be found! Couldn't find index page for 'setuptools_scm' (maybe misspelled?) Download error on https://pypi.org/simple/: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:719) -- Some packages may not be found! No local packages or working download links found for setuptools_scm>=3.3.1
This is a known problem with pip >9.0.x but on py3.5 but on my installation I have the latest version, I don't get why this is happening, can anybody help?
Did you try to install it manually within the venv?
Yup, it works there
I found a momentary solution, for some reason manually activating the py35 venv actually make it works
@proper wind pytest-cov is a pytest plugin to make it more convenient to use coverage.py. It's using coverage.py under the covers to do the actual work.
@river pilot I am aware of this but are there any cons to using it over just vanilla coverage?
It's possible that pytest-cov will do something a little wrong, and you might want more direct control. But I don't know of real circumstances like that.
Hello all. I'm new here. If I have a question about pytest mocking is this an appropriate channel? Specifically, I've got a mock setup and working but I have a feeling my approach is a little odd and I'd like to see if there's a better way to do what I'm doing.
@rigid hill yeah go ahead. This channel isn't too active but with some patience someone will hopefully help
Thanks @kind meadow . I'm patching the boto3 module to mock out a call to the s3 Client list_objects_v2. It looks like this: ```python
from collections import namedtuple
s3 = namedtuple('Client', 'list_objects_v2')
client = s3(list_objects_v2=lambda **kwargs: {'Contents': [{'Key': 'some-s3-key'}]})
mocker.patch('my_module.boto3.client', return_value=client)
I'm pretty sure I shouldn't need to build up the response with namedtuple
The docs had me scratching my head on how else to do this
Any suggestions for more idiomatic approaches would be much appreciated!
Here's a gist with a full runnable example: https://gist.github.com/jamesBrennan/dec7cc46d85508556a3e67e4c5734b12
(you can edit your message to add angle brackets <> around the link to prevent an embed)
Thanks for the tip
I don't know if this is more idiomatic but using a normal class definition seems cleaner to me
Or take a look at https://github.com/pytest-dev/pytest-mock
Kinda follows what I had in mind with mocking classes
The examples I mean
Hi, i have a quick question. i have need to run python 2.7 and 3.6 simulatnaously i know i need to adjust environment variables to accomplish this (windows 7 enterprise OS). Is there an easy way to accomplish this, been looking on stack overflow but information hasn't really been solid.
How is this related to testing?
Are you trying to run tests for multiple py versions?
There's tox for that
And in general, Python on Windows comes with a Python launcher named py
It can be used to specify the version to use when running the command
@pulsar nova please stick to just one channel at a time.This goes especially for the help channels.
ok, sorry
hm i just noticed that microsoft stoped detecting a file as trojan just by changing name from keylogger to oniichan
Yikes ^
Is there a way i can reuse a fixture inside another fixture?
(In pytest)
Like can i define a fixture foo() then another fixture bar(foo) and have the fixture bar receive foo as an argument?
yes
that is exactly the way you will do it
@pytest.fixture
def foo():
return 42
@pytest.fixture
def bar(foo):
return foo*2
What is mean of fixture??
@nocturne torrent https://docs.pytest.org/en/latest/fixture.html
@limber saddle excellent thank you
pytest magic is creepy
i know how it works, but it still makes me uncomfortable
lol
So, what do fixture do exactly?
In what kind of situation can you implement fixtures?
@stark verge If you have a lot of tests that have very similar set up or tear down, you can use one fixture to prevent you having to repeat all of that
Hello, i am using the library call pyautogui , i want the program to interact with my game is it possible ?
IIRC pyautogui doesn't work well with fullscreen applications
What are you trying to automate?
Hi all! Is there someone who might have the chance to help me with an issue using docker, django, and some failed migrations that only happen in the container
like dude you don't have to spam in 4 channels same question
Right on
I'm really not sure how to do this better
I wasn't sure if people would look in multiple channels is all
I look in every channel like a maniac until every channel is on read
I'm sure there are others
Cool. I'll keep that in mind
@night wolf or @exotic stone Would either of you be able to offer your thoughts on an issue I'm having?
i don't use django and docker
Nope don't have any experience with those. You might try to ask your actual question it might attract someone who knows and is willing to help.
what db and orm are you using
I'm asking in #databases, sorry for double posting
Hello everyone!
I'm trying to Mock an object and inject it into another one to kinda make it plug and play if one day i want to change how i fetch some info.
The injected object has a property called 'value' which is a dict; Yet when trying to get a value from it, I'm receiving TypeError: 'Mock object is not subscriptable'
The repo is: https://github.com/rmiguelac/mtg-django-collection-manager/tree/dependency_injection_decouple/collection_app
The card.py makes use of cards_api.py in its constructor and the test that fails is any of the last 3
Could you help me out? I've tried PropertyMock, patch and MagicMock without any success
I can take a look
Though for starters you should be using unittest.mock instead of mock. The latter is a backport meant for older versions of Python
I see, i'll make sure to do the change 😃 Thx
Can you share the full traceback for the error you get when testing?
Sure
=============================================================================================== FAILURES ================================================================================================
___________________________________________________________________________________ TestCard.test_card_price_is_float ___________________________________________________________________________________
self = <test_card.TestCard object at 0x7f8a6fa9fda0>, mock_external_api = <Mock spec='ScryfallAPI' id='140232565043776'>
def test_card_price_is_float(self, mock_external_api):
card = Card(name='Mox Opal', external_api=mock_external_api)
mock_external_api.value = GOOD_RESPONSE['prices']
print(mock_external_api.value)
> assert isinstance(card.value, float)
collection_app/tests/unit/test_card.py:37:
@value.getter
def value(self):
"""
Card value in USD
:return: return float object which represents the card price
"""
card = self._external_api(name=self.name)
price = card.value
if self.foil:
self.value = price['foil']
return self._value
else:
> self.value = price['non-foil']
E TypeError: 'Mock' object is not subscriptable
collection_app/cards.py:65: TypeError
The problem is that when you mock an object, everything in that object becomes a mock too
Every function and property
while debugging I was able to see that the property I wanted to get was indeed a Mock object. Yet, since i'm injecting the object into the constructor of the Card class, when i try to patch it, i'm unable to.
Given the fact that i'm already using a mock object. :/
You need to change the return value of the value property
Tried something like this
def test_card_price_is_float(self, mock_external_api):
card = Card(name='Mox Opal', external_api=mock_external_api)
mock_external_api.get_card.return_value = GOOD_RESPONSE
mock_external_api.value.return_value = GOOD_RESPONSE['prices']
assert isinstance(card.value, float)
and it didn't work
i'm just not able to grasp how to use PropertyMock, if that's the case, while already passing mock_external_api as a mock object, since the value is in it
I normally just use unittest I'm not sure how to mix mock and pytest
I'll look into it
meanwhile i'm reading the docs all over again, might have something missing...
Well your original mistake is that you changed the return value of the wrong thing
cause the value property became a mock so it would never end up using get_card internally anyway
So like I said you need to patch the value property instead
There we go py @pytest.fixture def mock_external_api(): m = Mock(spec=ScryfallAPI) m.get_card.return_value = GOOD_RESPONSE p = PropertyMock(return_value=GOOD_RESPONSE['prices']) type(m).value = p return m
I thought it would only work with patch so I was confused how to do that with pytest
But you can do it with a mock object with that weird type() stuff too
i saw that on the docs, yet it does not work
Same
@value.getter
def value(self):
"""
Card value in USD
:return: return float object which represents the card price
"""
card = self._external_api(name=self.name)
price = card.value
if self.foil:
self.value = price['foil']
return self._value
else:
> self.value = price['non-foil']
E TypeError: 'Mock' object is not subscriptable
collection_app/cards.py:65: TypeError
Even with that fixture and
def test_card_price_is_float(self, mock_external_api):
card = Card(name='Mox Opal', external_api=mock_external_api)
assert isinstance(card.value, float)
I'll try to find what i'm doing wrong
Thx for all the help Mark, really appreciate it 😃
Any1 expert in Appium who can help me with my project?
I am trying to measure users QOE on using an Youtube app in android.
I am trying to measure the buffers,stalls, bandwidth, resolution changes etc.. while the user is watching the video.
Is there a way to change where coverage looks for the source files when generating a report?
I ran coverage and then copied the coverage file elsewhere
That's not an option for coverage report
The .coverage file has already been generated. Just that once I run coverage report it gives errors about missing sources because it looks for them in a different directory
Right now I solved it by just making the docker volume mount to the same path as it is found locally
It works but isn't a fully safe solution I suppose
is possible to do something like this with unitttest ? https://phpunit.de/manual/3.7/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit.data-providers.examples.DataTest.php
the dataProviders bit
That looks a lot like a pytest fixture
I don't think there's something similar in unittest
But it's in pytest if you're fine with that
is this what you mean? https://docs.pytest.org/en/latest/parametrize.html
Actually yes. I misunderstood what the PHP thing was doing
You could parameterize a fixture and then re-use the fixture, that would act more like the PHP thing
pytest.mark.parametrize works fine too
Does anyone have a good intro to Unit testing guide?
are there any good documents or tutorials out there for stubbing/mocking apis? im writing a client library and its almost totally untested right now cause i just dont have a sense of how to proceed w/ testing it
I'd like to know this too actually. I tried to find stuff half a year ago when I was working on a wrapper but had no luck.
@pearl cliff
Unittest and functional tests
Right... but at some point i have to test the api querying code itself
Probably use unittests
@pearl cliff There are two approaches you can use to test your client.
First approach is to abstract how you request the API endpoints. Instead of calling the HTTP library directly wrap it in your own interface and then in your tests swap that interface out for a mock interface which feeds test data and doesn't even necessarily make a web request.
Second write a super simple WSGI server. You can use something like Flask which should have you up and running in no time. Doesn't need to be fancy, just use the builtin dev server Flask ships with and hardcode route URLs and responses that are your mock API endpoints.
Personally I'd probably take both approaches. The request interface is super easy to test with but doesn't give you coverage over your request interface/library. The second approach takes more effort when testing since you'll need to spin up a dev server, but it gives you the ability to have full test coverage.
thanks for the detail @digital violet !
in my case, the api works something like this:
- submit a collection of records to be processed (
/submit) - receive a collection of "tracking detail" objects that contain processing status and some other metadata
- for each tracking detail object, poll for status updates until the status is either "failed" or "success" (
/status) - if "success", download the processed result (
/output)
so you're saying i might 1) abstract over the HTTP part (using e.g. dependency injection), or 2) actually spin up a fake HTTP server and change the url in the client? and in both cases, i'd populate the fake API with some kind of dummy data, covering as many edge cases as i find in my real-world testing.
Yep, exactly.
Would be cool if someone had a testing library for this but I haven't found one... Project idea 🤔
i mean, there are pytest fixtures and unittest.mock
also someone wrote a library for mocking aiohttp responses https://github.com/pnuckowski/aioresponses
i kinda regret going the async route for this client. i should have done it synchronous and just used threading
i might still do it, its proving to be more trouble than its worth
I'm writing a package which relies on psycopg2. When I create my tests and push the commit to gitlab, the CI picks up the commit and runs the tests.
that package can't be imported for various reasons, so i am curious as to whether i could instruct pytest to mock the package so it doesn't break the tests?
i need hq trivia bot pls give me script
No
I suggest you re-read the rules you agreed to when joining this server
And the terms of service of HQ
This also has nothing to do with software testing
pytest question:
I'm writing some tests for a custom class that reads several pickles. To mock these pickles my thinking as of now is to create a fixture, for each type of pickle, that returns nothing but writes a pickle file to the tmpdir fixture. Is this possible or even a good solution?
Is there a clean way to do an assert_called_with on a mocked object that will be called from another thread?
I have a test case for a function that pushes a request to queue, then a child thread will pop the request and send it.
Hi can someone take a look at my code and tell me why the timer is not working as it should and how can I get it to work
https://paste.pythondiscord.com/ihorogiwiy.py
For context
I am making a GUI for some lab equipment
There will be a button for locking and unlocking the settings for both temperature and humidity individually
and when these settings are locked
The user should be able to run the program
and the time should actively be displaying the hours : minutes : seconds that the program has been runnning
and when the user presses stop, it should pause the timer and display that number unti the program is runned again (in which it should reset to 00:00:00)
rn I have no clule what its doing
I'd appreciate if someone would run this code (there is an image involved but you should be able to delete those lines or comment them bc its only server and aesthetic purpose
Please and thank you, I'm stumped
@pale pollen try asking in one of the help channels
What does the msg kwarg do? https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertRaises
It explains it exists but not what it's for. I thought it may be to match the exception's message but that doesn't seem to be it based on my testing
msg and params are optional, arbitrary values which are displayed whenever a subtest fails, allowing you to identify them clearly.
Hi guys
What is a clean way to do teardown on a pytest test function ?
Would you write a unit test to test if a function's parameter can be optional?
Feels excessive to me but what do I know
All my classes subclass a main class which actually does the bulk of the work. The other classes are just shallow wrappers which add some arguments to the main class's function. I've tested that the main class properly handles optional args but not the all the "wrappers"
The wrappers are just wrappers so really what I'd be testing for is if they are defined with optional args, not if they actually handle them. Then again with the latter I make the assumption that they are calling the main class.
It's kind of overwhelming. How extensive and paranoid should the tests really be?
If it's easy to implement and run the test, I don't see why you shouldn't. If it's literally just an optional parameter, I'd tend not to, but if you're implementing some kind of logic (if it's not supplied, do blah), then it might be worth testing.
The reason not to I suppose would be that you end up with a lot more tests
If I have to write 2 tests for each function, 1 for giving the args and one for not.
See I use a special default value: ```py
class Undefined:
pass
UNDEFINED = Undefined()
Because I want to consider None to be an acceptable value
So not only would the test ensure that it's an optional arg, but it would ensure its default value is UNDEFINED
But for something relatively trivial I wound up asking myself if it's worth it when I have like 50 functions to test
I should probably go out and read a book on this stuff 😩
class Undefined:
def __new__(cls):
return UNDEFINED
UNDEFINED = object.__new__(Undefined)
[anyway, for the optional arg case, i normally just use an object() for the default sentinel rather than making a special class]
ty for the idea
I was overthinking it
Well the custom class is useful for type annotations
hey
What's the most highly recommended mocking library for 2.7?
i only ever used mock, it does the job
What's the best way to run automated coverage tests?
Your CI
That's Travis
Do you use coverage.py?
Yes
Codecov
@celest bough
ty
@blazing dragon no, it is for testing as in “unit tests“, “integration tests“, quality acceptance, etc.
@blazing dragon you are probably looking for #303934982764625920 and #360148304664723466 instead
Cool thanks!
@lime night Ok, good to know, thanks.
Hi, does anyone here have experience with php unit tests, I need to port my code to Python's unittest.TestCase?
here is a reference to my problem: https://gist.github.com/gnud/b78dc54fd16ee6c0679dbfb5943773b7 if anyone is interested, will post the solutions here http://www.php2python.com/ for future reference 😃
decimal = 0
tens = 0
hundreds = 0
thousands = 0
ten_thousands = 0
hundred_thousands = 0
millions = 0
ten_millions = 0
hundred_millions = 0
billions = 0
ten_billions = 0
hundred_billions = 0
trillions = 0
ten_trillions = 0
hundred_trillions = 0
accumulation = 0
while accumulation != i:
accumulation += 1
if decimal < 1:
decimal += 1
else:
decimal = 0
tens += 1
if tens > 1:
tens = 0
hundreds += 1
if hundreds > 1:
hundreds = 0
thousands += 1
if thousands > 1:
thousands = 0
ten_thousands += 1
if ten_thousands > 1:
ten_thousands = 0
hundred_thousands += 1
if hundred_thousands > 1:
hundred_thousands = 0
millions += 1
if millions > 1:
millions = 0
ten_millions += 1
if ten_millions > 1:
ten_millions = 0
hundred_millions += 1
if hundred_millions > 1:
hundred_millions = 0
billions += 1
if billions > 1:
billions = 0
ten_billions += 1
if ten_billions > 1:
ten_billions = 0
hundred_billions += 1
if hundred_billions > 1:
hundred_billions = 0
trillions += 1
if trillions > 1:
trillions = 0
ten_trillions += 1
if ten_trillions > 1:
ten_trillions = 0
hundred_trillions += 1
if hundred_trillions > 1:
print("limit breached")
quit()
print(str(hundred_trillions)+str(ten_trillions)+str(trillions)+str(hundred_billions)+str(ten_billions)+str(billions)+str(hundred_millions)+str(ten_millions)+str(millions)+str(hundred_thousands)+str(ten_thousands)+str(thousands)+str(hundreds)+str(tens)+str(decimal))
but why
How can I improve this?
@ancient spear No idea but it was fun to figure out. Yeah I know I'm dumb
you should start with how to turn an int to a binary, the algorithm / way you do it
think of dividing to 2 and get div / mod
close, you get the idea
I get the idea, but I have no clue how to print it out in the end
this should be in one of the help channel not here
Everything related to testing your Python applications and libraries, and discussion of testing as a whole.
In the channel description
unittesting, intergration testing, sanity testing, interface testing, ... what kind of test you want to talk about
Cool @ancient spear
What Python 3 compatible debuggers can I use on Ubuntu? How can I attach it to a Python 3 process running on a remote machine? Or, specifically: inside of a container?
Maybe there's an extension to pdb for it
pdb is nice, because it's in the stdlib, but i prefer to use pudb, it shows the stack on the side, the code on top, and allow to execute at the bottom, you can add watched variable, etc, all the things you can do in pdb, but taking better advantage of the screen space.
I'm currently writing a flask REST API, the main purpose of which is just to stick on github to demonstrate a degree of competence, as such I'd kinda like to do as much stuff "correctly" as possible. So does anyone have a suggestion for a tutorial/guide on writing unit tests?
Like, I'm aware of the concept and have done them a little with React/Redux, but I haven't really written a huge amount of them
I'm looking into learning QA testing. Currently playing with selenium, testing to see that websites work. Just wanted to ask if anyone has any suggestions on where to look for more information on it or things in particular to test for?
@wild roost Pycharm and VS Code do remote debugging. PyCharm does out of process debugging too. Not durxabout VSCcode though
What is out of process designing?
he probably meant debugging
@patent oasis @wild roost Yes, I meant debugging
points for me!
Writing a "snapshot" helper function for REST API json responses. Is there any way to more automatically iterate over sub dicts in a response rather than writing like 10 nested if in this so that I can assume 10 is the deepest they'll go? I want to be able to scale to even 100 subdicts without the need for changing the function:
Python 3.6.8 (v3.6.8:3c6b436a57, Dec 24 2018, 02:04:31)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def create_snapshot(endpoint, method, data):
... snapshot = {
... "endpoint": endpoint,
... "method": method,
... "snapshot_data": {}
... }
... if type(data) != dict:
... raise BaseException("Error, data variable not passed as dict!")
... for k, v in data.items():
... if type(data[k]) == dict:
... sub_dict = {}
... for ksub, vsub in data[k].items():
... sub_dict.update({ksub: str(type(vsub))})
... snapshot['snapshot_data'][k] = sub_dict
... else:
... snapshot['snapshot_data'].update({k: str(type(v))})
... print(snapshot)
...
>>> test = {'test1': 'string', 'test2': 2, 'test3': { 'sub1': 'string', 'sub2': 2}}
>>> create_snapshot('test_endpoint/', 'POST', test)
{'endpoint': 'test_endpoint/', 'method': 'POST', 'snapshot_data': {'test1': "<class 'str'>", 'test2': "<class 'int'>", 'test3': {'sub1': "<class 'str'>", 'sub2': "<class 'int'>"}}}
>>>```
basically im just type checking the responses and then ill be storing to a json file which we will match against in future unittests
Is there a way to mock all the functions in a module in one statement?
Suppose I'm testing a function main() in script.py and it imports a util.py module and calls util.delete(x) and util.rename(y).
Instead of doing:
mock.patch("util.delete")
mock.patch("util.rename")
can I do something like:
mock.patch("util", autospec=True)
Basically looking for a more concise way of mocking all functions in a module because my util file has a lot of functions.
I think that would work fine if it was a class but not sure about modules
Figured I'd post in here b/c I'm not getting any help in the help channels...
Question: I'm trying to unit test with calls to mock async calls, and I'm doing this by having my MagicMock return a Future. Is there a way to determine, at testing, whether the Future was awaited as opposed to just called?
Test passes, but at run time the method doesn't work properly because I forgot to await my call.
well, I guess you can check if __await__ was called on your Mock
same as you would do with any other function of a mock object
asset mock.__await__.called
Hey, I asked this in help but this place might be a better fit.
I'm getting into TDD and I was wondering if any of you could recommend some resources for me to read up on best practices, etc.?
I'm looking to learn more about writing Unit & Integration tests in general, less about creating testable code.
"strict" TDD probably isn't worth your time
there are many good posts about unit testing and other forms of testing on https://softwareengineering.stackexchange.com
I don't know why the negative_search isn't executing while the positive one is
Btw im very new to that subject so please keep it simple
it should, can i see the output?
@cunning lake
you probably hovered over the test and pressed f10
change it to test the entire class
Can pls you guys help me to convert python kivy code to apk
If you have buildozer working perfectly on your system
Is it worth writing significant documentation for pytest unit tests?
If you follow a more verbose naming convention I don't think it's useful for the most part
There can be exceptions of course
Like tests for obscure edge cases
They are reasonably detailed cases though, it's some scientific code where I'm constructing a velocity field, etc.
Well you can leave some comments if you'd like but significant documentation probably not worth it
I don't have experience with scientific programs though
Yeah, fair enough. I'm probably going to have to make some documented examples (and see if they'll run in CI), so they can fill that role
Most of that should be covered by the documentation for the unit itself
If people can read that doc and already have an idea of what it does and how to use it, then you should be set
I'm not saying it's inherently bad to have more documentation, it just a matter of managing time wisely
Well maybe you could argue docs for tests would be bad since it increases maintenance efforts for tests
Agreed, that'd be the opposite of what I want
Tests can take up enough time to write as it is
You're welcome
How would I go about testing this? Should I test it at all even? Let's say that create_json_file and get_url are already tested. ```py
@atexit.register
def execute():
if os.getenv("ALGORITHM_VISUALIZER"):
create_json_file()
else:
url = get_url()
webbrowser.open(url)
I admit I don't even like this whole atexit business but I plan to discuss its removal in the future (maybe another reason not to bother testing it).
seems not worth testing
How can I mock.patch() something that is in __init__.py?
Well I instinctively asked here before just searching online
gonna try patch.object()
@kind meadow
@patch('yourpackage.somefunction')
def testing_foo(mock_somefunction):
# do something with mock_somefunction
Thanks, but I ended up with this. My mistake was not using patch.object because what I wanted was to patch an attribute. It being in __init__ actually had nothing to do with it ```py
def setUp(self):
self.commands = [
{
"key": "abc123",
"method": "foo.bar",
"args": [1, 2, 3],
}
]
self.cmd_patch = mock.patch.object(
algorithm_visualizer.Commander,
"commands",
new_callable=mock.PropertyMock
)
self.cmd_mock = self.cmd_patch.start()
self.cmd_mock.return_value = self.commands
self.addCleanup(self.cmd_patch.stop)
If someone can come up with a cleaner way to write that let me know.
I should probably use __init__ instead of setUp though since I don't need to mock it again for every unit test I have
I don't think setUpClass is appropriate since it's a classmethod, right?
@torn mirage Try asking here instead
Yeah was wondering if it isn't too basic since I never really did any tests.
Never done tests, but how would I go about creating some for a GUI app? Happened a few times now that I released a version that had a few bugs I didn't notice because the code never got executed in my hand tests.
Would just like some pointers as I can't test code on my pc now
I am not experience with GUI testing but at the least I can say you should separate your tests into unit tests and gui tests
so business logic stuff should be tested independently from your gui
If they're too tightly coupled then you'd need to rethink your architecture and design
Instead of trying to test "untestable" code
Yeah I only have basic logic that serves for updating the windows in the GUI part so that shouldn't give any trouble
Oh I love discord at a crappy connection. Only need stuff like opening all popups and then testing the things in there; thanks for the link
Hi,
I"m struggling my way through learning how to setup a very simple project, so that I can start writing tests for it. I do have some tests written, but I don't have the directory structure configured correclty so that the tests can access the file being tested.
Can someone provide a clear, easy to understand reference on how to setup the directory stucture for PyTest?
@sand turret it's highly recommended to:
- use a venv
- use a setup.py so that you can use Pip to install your code into your venv
have you done either of those things?
I use anaconda, which has its own virtual environments
However, I was able to get my test to find the file being tested, I just needed to use a different import path. Pytest now runs on the desired file, as expected.
I've never used setup.py for my own projects though
@pearl cliff Why would I want to pip install my code, when my code is in Bitbucket?
My code isn't on github/PyPi
You pip install from the local directory
Modifying sys.path is messy
Better to use the tools for the purpose
Once you have your setup file, you just need to pip install -e .
Thanks- that's something new. Not sure why you need to change sys.path, I don't
depends on your setup
If what you have works, it works
But its hard to support beyond the simplest setups
Thanks
I'm using PyCharm to run my py test files, and I've started using Coverage.py .
At the moment, I have only 1 test file, but Coverage is running from the project root directory. Pytest is running from the directory where the test is, because I point Pytest to that directory.
I don't see any options for Coverage in PyCharm to tell it where to start checking for code coverage. Does anyone know how I can do this?
You can configure which files it will cover using a .coveragerc file
The documentation for coverage.py explains this
Are you saying that even though I can tell PyCharm where to start running tests, that I can't tell pycharm where to start running coverage?
Perhaps I misunderstood your question
Well, coverage "support" is a pro-only feature
If you make a normal python configuration that invokes coverage.py you can also pass command line arguments to it
For example coverage run -m unittest will just use unittest to auto discover tests.
I think you asked about pytest earlier so that doesn't apply
I see most, if not everyone, using pytest-cov for that
Apparently you could just do coverage run -m pytest though 🤷
I believe through that you can pass any arguments you want to pytest
and I think options that are configurable in .coveragerc can also be passed to coverage.py as command line arguments if you need them
I have pycharm pro
In that case it just uses whatever the current run config you have is set to
I've been reading the Coverage website about the .coveragerc file. I've added it to the project root, and only have 1 line in it
under [run]
source=Path To My test directory
However, Coverage still looks at all of the files under project root, and shows a low covergae percentage as a result
Does it work correctly if you run coverage through a terminal?
Also, setting the coverage.py source to be your tests is incorrect
After all, you want coverage to be on your actual code, not on the tests
I haven't run coverage from the terminal. I wasn't able to find out how to run pytest and coverage at the same time, from the command line. That's why I was using Pycharm. Usually Pycharm gives you a lot of flexibility when running programs and tests, but not with coverage
Ok- I've run coverage from the command line. It shows very different coverage stats than when I run inside of Pycharm
Will coverage elaborate as to which lines are not being tested?
I've commented out the source=Line in the .coveragerc file. When running from the command line, .coveragerc has no effect.
The basic command to run it in the terminal should just be this as I said earlier coverage run -m pytest. Just in case you were still having trouble with that
.coveragerc should be picked up automatically, but it depends where you put it and what the cwd is when executing the command. This is what the documentation states:
The default name for configuration files is .coveragerc, in the same directory coverage.py is being run in.
And also
A different name for the configuration file can be specified with the --rcfile=FILE command line option.
I put it in the root of my project and also execute the command at the root of my project. That has worked for me.
By not being tested do you mean uncovered lines or ignored lines?
For the former you can do coverage run -m. The latter I suppose you can see with an html report coverage html and then open ./htmlcov/index.html in your browser
Yeah, I got the missing lines displayed now- don’t know why that’s not the default.
Thanks- I’m learning a lot- I’ve read the docs on coverage more than once- it could use an overhaul
can someone help me, i'm learning the basics of selenium but a lot of simple tasks aren't working. I get error when trying to select a drop down, radio button, check box etc.
I've tried the help channels but had no reply, I assume they are probably more focused towards programming in python rather than selenium.
for example, simple piece of code -
from selenium import webdriver
driver = webdriver.Chrome(executable_path= 'E:\Drivers\chromedriver_win32\chromedriver.exe')
driver.get('https://fs2.formsite.com/meherpavan/form2/index.html?1537702596407')
status = driver.find_element_by_id('RESULT_RadioButton-7_0').is_selected()
print(status)
driver.find_element_by_id('RESULT_RadioButton-7_0').click()
status = driver.find_element_by_id('RESULT_RadioButton-7_0').is_selected()
print(status)
driver.find_element_by_id('RESULT_CheckBox-8_0').click()
driver.find_element_by_id('RESULT_CheckBox-8_6').click()```
I expect the status to change from false to true when the radio button is selected, but my code throws an error says the element is not interactable
Not interactable means the page hasn't fully loaded at the time you are trying to get the element. Try added a second or two of time.sleep() after you make the get request.
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
elem = WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.NAME,'session[username_or_email]')))
a better way to handle page/element loading
webdriver will wait for either 30 seconds or for the element to show up in the dom structure, whichever happens earlier in above example.
Currently I use VScode as my editor when writing python; whenever I need to test my code I open terminal and run the python file with print statements. Sometimes if im stuck enough i'll just run python in the terminal.
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>```
So my question, is there a way to have VScode run in a similar manner to jupyternotebook or python in the terminal?
Im on Ubuntu 18.04
(if there is a better channel for this please let me know and i'll move it there.)
So my question, is there a way to have VScode run in a similar manner to jupyternotebook or python in the terminal?
what does this mean?
something like this:
pycharm has an option for jupyter notebooks
if that's what you mean?
vscode probably has an extension for that aswell
@cunning lake Thanks i'll poke around with it
Does anyone know a card terminal model which maybe has an API? I wanna do something like setting it's pay price and knowing when it has been paid from the PC. Sorry if something is unclear. I'm not sure how to explain it will in english. Just let me know if you have any questions. (Sorry if this is the wrong channel)
Pycharm Atom or VS code
Pycharm if you want everything out of the box. VSCode if you want to configure things just how you like it. Atom is similar to VSCode but not as good, in my opinion.
cries in sublime text
Do you know of any signal processing software apart from openmodal?
open source i mean
Hey, I'm looking to implement end to end testing with cypress for an app with a django backend.
How should I approach creating test data?
Currently we are using selenium with python, so we can access the django models directly, but that's not the case with cypress as it's JavaScript based. It's possible to run command line stuff from within cypress though.
Question about pytest cleanup and SSHTunnelForwarder.
I have a test file:
from python.common.sql.basesqlalchemy import BaseSQLAlchemy
class TestSomething(object):
def test_01_something(self):
# Test that it even works.
test_object = BaseSQLAlchemy()
raise ValueError('error in test')
The test fails as expected when it hits raise ValueError('error in test'). BUT, the code does not finish execution and hangs indefinitely and must be manually stopped. This appears to be due to the SSHTunnelForwarder server not being closed. Whats the best way to deal with this?
This is the BaseSQLAlchemy code file:
The relevant lines of code in that file should be:
class BaseSQLAlchemy(object):
def __init__(self):
self.server = self.create_tunnel()
self.engine = self.create_engine_connection()
def __del__(self):
if self.engine:
self.engine.dispose()
print('Closed Engine.')
if self.server:
self.server.close()
print('Closed SSH Tunnel to Server.')
def create_tunnel(self):
"""Checks if code is running locally or if running on servers.
If running locally, then we need to create a tunnel to the server
first. Else, code is running on servers, and there is no need to
create a tunnel.
:return: obj, the tunnel. Can be 'None'.
"""
print('Connecting to SSH Tunnel to Server...')
# if envconfigs.IS_RUNNING_LOCALLY:
if True: # Manually emulate previous line, for debugging.
# Account for if the normal private key is not supported.
if envconfigs.SECONDARY_PRIVATE_KEY:
private_key = envconfigs.SECONDARY_PRIVATE_KEY
else:
private_key = envconfigs.SSH['rsa_key_path']
server = SSHTunnelForwarder(
(envconfigs.SSH['host'], envconfigs.SSH['port']),
ssh_pkey=private_key,
ssh_username=envconfigs.SSH['user'],
ssh_password=envconfigs.SSH['password'],
remote_bind_address=(
envconfigs.DATABASE['host'], envconfigs.DATABASE['port'])
)
server.start()
print('SSH Tunnel to Server successful!')
else:
server = None
print('No need to tunnel in, as the test is running on the servers.')
return server
The reason I'm not using the SSHTunnelForwarder in context (with ...) is that I need the Tunnel and DB object to be able to be used in the test multiple times within the test to limit connection resets to the database?
Is this the correct approach?
Note, that the test runs fine if it does not fail.
Depending on your test runner there's ways to execute code before and after your tests.
With pytest a fixture with yield would be used, with unittest you'd have def setUp(self) and def tearDown(self)
I'll look into yield fixtures.
I don't think the pytest setup_method() and teardown_method() will be relevant unless I instantiate the BaseSQLAlchemy object within them though.
Yes, same with the yield fixtures though
If you do want to create it in the test, i dont see why with ... wouldnt work
In my situation, my tests:
- want to run the SQL to verify all pre-req database values,
- then mess with a web UI page to create a web item via Selenium,
- then finally call the SQL again to verify everything was saved properly.
This can sometimes be like 20 different SQL calls, so I was looking to limit the number of times I would actually connect to the DB, and was looking to just keep the SSH Tunnel and DB connection alive and re-usable throughout the test.
As a result, I also don't think it would be great to wrap this logic that code in a with... context.
I have everything working, EXCEPT if a failure occurs, then the SSH Tunnel is not closed.
The SQL alchemy IS closed properly in this instance, which is confusing. (but likely because SQL Alchemy has built-in clean up?)
Yea i'd just do the close manually / explicitly.
With pytest it'd be like
import pytest
class TestSomething(object):
@pytest.fixture()
def base_sql_alchemy(self):
try:
base_sa = BaseSQLAlchemy()
yield base_sa # Your test will run here
finally:
base_sa.close()
def test_01_something(self, base_sql_alchemy):
# use base_sql_alchemy
base_sql_alchemy.engine.something()
raise ValueError('error in test')
awesome, i'll give that a try!
The fixture has a scope parameter that you could set to scope="class" and then it will setup the server connection at the beginning of the class, run all tests in the class, close it at the end after all tests.
Without scope, by default, the scope is function which will act as:
- create connection, run test 1, close connection
- create connection, run test 2, close connection
Haha! That worked perfectly, with a bit of finagling.
@buoyant latch ++
Hm, anyone know the reason why self. declarations do not work with pytest fixtures when the fixture is set at class scope?
Example:
import pytest
class TestFixtures(object):
#
# This first fixture and test is a function level.
# It works as expected.
#
@pytest.fixture(scope='function')
def set_variable_hello(self):
self.variable_hello = 'hello'
def test_01_print_hello(self, set_variable_hello):
print('Got into hello', self.variable_hello)
#
# This second fixture and test is a class level.
# It will throw an AttributeError, as it appears the "self.variable_world"
# is NOT the same between the fixture and the test?
#
@pytest.fixture(scope='class')
def set_variable_world(self):
self.variable_world = 'world'
def test_01_print_world(self, set_variable_world):
print('Got into world', self.variable_world)
AttributeError: 'TestFixtures' object has no attribute 'variable_world'
Has anyone here used the capture network traffic feature that has selenium has? I'm trying to capture network traffic after the user has submitted the form but it only gives network traffic when the page first loads.
How do I get pytest to not print anything from pytest? All I want is the output from each test. I don't care if every tests' output is concatenated. In fact that is fine. I just need pytest to get the !@#$ out of the way so I can do work
I tried adding the -s switch which didn't do anything helpful
also pytest backtraces are literally 2.5 pages long wtf
You're saying you only want to see the stdout of the tests themselves?
e.g. if the test did a print call somewhere
Yes
Right so according to this pytest -s # disable all capturing pytest --capture=sys # replace sys.stdout/stderr with in-mem files pytest --capture=fd # also point filedescriptors 1 and 2 to temp file
just -s would disable that
Have you tried redirecting stdout using one of those?
No, this doesn't seem to be useful at all actually
Yes, pytest still writes its own crap to stdout
hmmm
literally no idea, I've never used pytest before last week 😐
I dunno. I don't see anything obvious
You could write a pytest plugin though
but that seems annoying
@wild roost did you try pytest -q?
you can also suppress captured log output with pytest --no-print-logs
Nope, I didn't know about -q. Looks like that's close to what I want though.
When I do python3 -m pytest path/to/tests, the tests are executed and I see pytest clutter, but I don't see print statements. When I do python3 -m pytest --capture=no path/to/tests, the tests are executed and I see both pytest clutter and print statements. When I do python3 -m pytest --capture=no -q path/to/tests, the tests are executed and I see less pytest clutter but it's still there and I see print statements too.
https://docs.pytest.org/en/latest/example/simple.html
The examples in here give -q and provide example output. All of the output is from pytest and it's literally garbage that idgaf about. Write that to a file would be fine. But stdout should belong to meeeeee :'(
What gets me is this from the example:
assert 0 # to see what was printed
which implies that pytest captures and prints things only if something bad happens. I need the output regardless of whether the test failed or not.
Is there a way to get pytest to write the stdout/stderr of each test to separate files?
maybe you just dont need pytest?
-s should work regardless of whether the test fails
that said if you want to log the standard inputs and outputs see here https://docs.pytest.org/en/latest/capture.html
pytest -s # disable all capturing
pytest --capture=sys # replace sys.stdout/stderr with in-mem files
pytest --capture=fd # also point filedescriptors 1 and 2 to temp file
The capsys, capsysbinary, capfd, and capfdbinary fixtures allow access to stdout/stderr output created during test execution. Here is an example test function that performs some output related checks:
maybe you just dont need pytest?
Maybe that is so. What other test frameworks are there? I already mentioned doctest is too limiting.
unittest
Hmmm. I searched Google for pytest vs unittest, and found this: https://stackoverflow.com/a/28009926/1111557
I must say: the question and accepted answer basically describes a lot of the gripes I have with Pytest so far
If I understand correctly, unittest comes with the Python standard library but Pytest provides more features? Hmmmm
If you're literally just running methods and dumping their standard out (print statements?), then just use unittest
pytest is useful if you're actually running tests and care about things like exceptions, asserting correctness, generation and parameterization of test cases, test environment configuration, etc.
For a simple project with a single or handful of source files there isn't a huge difference between the two, other than pytest being a bit easier to setup and less typing.
Anyone know a nice way to test python code in markdown files? I have several markdown files with code snippets in them. I would like to have some way to verify that they run without error.
It's not a simple product. But there's no reason to have tons of complicatedness in testing. Pytest makes complicated what should be simple.
Hi All, can I automate flex we application via python
I have a question, for example when im doing my end to end tests and i want to mock my database, how can i do it effieciently when the size of the db is around 150 tables
I looked at fixtures or likewise alternatives like factory_boy
But it seems like it would still be alot of work to write a few objects at each table as a controlled group
any suggestions?
Trying to build NumPy from source. I'm running python setup.py build -vvv but it seems to be stalling at some point after showing the gcc command-line options. Is there a way I can debug the setup.py file? (I am running this on an Alpine Linux VM on iOS via https://github.com/tbodt/iSH so it's not a standard setup, I just want to see where the error is.)
What the output?
And maybe you should open an issue on numpy (or search for existing issues when building on alpine)
(Don't think I need to put output here as I don't think I could replicate it on a standard machine), but I can't find it on similar issues. Best bet for me is to trace through setup.py somehow.
Stalls after gcc compile options.
...
C compiler: gcc -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Os -fomit-frame-pointer -g -Os -fomit-frame-pointer -g -Os -fomit-frame-pointer -g -DTHREAD_STACK_SIZE=0x100000 -fPIC
compile options: ‘-Inumpy/core/src/common -Inumpy/core/src -Inumpy/core -Inumpy/core/src/npymath -Inumpy/core/src/multiarray -Inumpy/core/src/umath -Inumpy/core/src/npysort -I/usr/include/python3.7m -c’
This is where it stalls. I'm running with python3 -vv -m pip install . -vvv in the numpy source directory.
@kind meadow
Well, that output doesn't say much unfortunately
@kind meadow Agreed. I'd like to find out where in the code it reaches that point so I can investigate further.
It could be cause alpine is musl based?
Could be, I'd like to know for sure though. I'm not familiar enough with setuptools / distutils though to get much further.
I'm not either honestly, I don't know how to step through that
Like I said, if you run out of ideas, open an issue on numpy's repo
they may help you out
worst thing happens is they say no and close it
does anyone have ever used winafl?
hello
how should I test an app, correct output of which i have in a csv file
basicallt whenever i make a change i wanna make sure the results dont get messed up
not sure if going into unittest is too much
what have you tried
sure, you can have your app generate CSV then compare against the correct output
i can
but the thing is I am not sure what's the better way of doing it. I can write a function that compares 2 excel files
but then there are tons of libraries that offer testing
unittest, pytest, etc
cuz I have never used any tesitng library before
not even sure where to start and even if i need to use one
testing libraries just give you a fancy way to run tests
you still need to write the functions and the tests
of course it's good to know them but it's your time you're spending
but are they used for simple tests?
like using django to create a web page seems like an overkill
pytest isn't overkill
If it's 3rd party stuff that's spooking you, If you're using python3 the built in unittest lib is pretty good now. It's also about as simple as you can get.
Here’s my view of unittest/pytest/etc:
-
It’s used to structure and run tests.
-
The test classes should be step-by-step method calls to performing a test.
-
It is not required if you just want to create a script to compare some csv outputs.
-
You can also just create the standalone script now, and then expand it later to be included as part of a unittest/etc.
@mossy hatch If you have a situation where you are continously making changes to some code, and you want to have a way of verifying the correctness of the code after each change, that's the perfect situation to use a unit test framework.
It's absolutely not overkill.
unittest is easy to use and is part of the standard Python library
You may as well start with that
is there any sane way to enforce data contracts on pandas dataframes either at runtime or static-typecheck-time
or even during testing?
i suppose i could use https://pypi.org/project/pycontracts
@mossy hatch they both have sub-packages for testing purposes
things like numpy.testing.assert_arrays_equal pandas.testing.assert_frames_equal
they do
beyond that... its the usual with unit testing
they have hypothesis integrations too
but tests didnt run as in unittest
I inherited from unittest
basically using unittest, but with np asserts
you have to wrap it the function with the assertion in a unittest.FunctionTestCase
or subclass TestCase
I did
they code looks like
class TestStocks(unittest.TestCase):
def __init__(self):
self.stock_list = ["AA", "AAPL", "DDD", "DY", "JPM", "T", "XOM"]
def compare_dfs(self, baseline, new):
npt.assert_equal(baseline.values, new.values)
TestStocks is later then passed to more specific tests
class TestSMA(TestStocks):
what I am stuck with now is I am not sure whether I need to call my test located in Tests\ or create another master_test.py file in the project root folder
somebody told me to do the 2nd one
now I am trying to figure out how to run my tests from another file
Anyone used python mock?
I have been trying to design a mock test for my python server and I am having a really tough time trying to mock the websocket variable in this class
import asyncio
import websockets
import json
import db_flask
class JsonWrapper:
def __init__(self, data):
self.data = data
def get(self, key):
if(key in self.data):
return(self.data[key])
class Server:
async def handle(websocket, path):
data = await websocket.recv()
print(f"data received: {data}")
data = json.loads(data)
action = data["Message"]
if(action == "!join"):
username = db_flask.new_user(JsonWrapper(data))
data_to_send = db_flask.get_user_by_username(username)
print(f"sending data:{data_to_send}")
await websocket.send(json.dumps(data_to_send))
def run_server():
db_flask.create_database()
s = Server()
start_server = websockets.serve(s.handle, "localhost", 5555)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever() # // disable this when testing?
if __name__ == '__main__':
run_server()
I want to do something like websocket.recv.return_value = "some string"
However, the way handle is called is kind of odd. Although that wouldn't matter if I could just get the mock the websocket variable
You'd need to use an AsyncMock, which is a Python 3.8 feature
If you understandably can't be on 3.8 yet then you could write your own
then you should be able to set a return value as normal
@hazy mist
class AsyncMock(MagicMock):
async def __call__(self, *args, **kwargs):
return super().__call__(*args, **kwargs)
also easily found on SO I believe
we probably copied it from there 😄
return dict_in[key] if key in dict_in else filler```
Hey TDD advocates, at glance is this alarming ?
not sure why TDD would have anything special to say about it
it is redundant though - dict.get() exists
Is there a way to show exact mismatch in unittest when test case fails?
in pytest it'll show you the exact diff when run with -vv, not sure about the built in unittest
yeah just use pytest
You can run unittest tests with pytest with no changes
pip install pytest
pytest -vv tests/
I am not familiar with pytest
i am runnine the file itself now
not from cmd
@tawny wave actually i jus realized I am using numpy.testing for asserts
dont think it makes a difference whether I use pytest or unittest in that case>
Yeah, but pytest will show the diff
@kind meadow Thanks for answering my question! I will try this now
@kind meadow I have installed a virtualenv for 3.8 and am trying this out, still a bit lost though
If the handle method the coroutine? or is the async call ?
Should be something along the lines of the following to mock the websocket object: ```py
mock_ws = AsyncMock(WebSocketCommonProtocol)
mock_ws.recv.return_value = "whatever you want"
I think WebSocketCommonProtocol is good enough to mock but it's very likely what is actually passed to the handler by the server is some object that is actually subclassing WebSocketCommonProtocol
no need for a patch then?
Depends on how you want to do it
If you call the handler function yourself in the test then you don't need to patch
And IMO that is how your test should be written, since it's a unit test after all
from websockets.server import WebSocketServerProtocol
class ServerTest(unittest.TestCase):
def test_add_user(self):
mocked_socket = AsyncMock(WebSocketServerProtocol)
mock_path = MagicMock()
s = Server()
mocked_socket.recv.return_value = '{"Message": "!join", "Username": "test", "UserId": "123", "Email": "test@sad.com", "Color": "FireBurn", "IsModerator": "False", "IsSubscriber": "False"}'
mocked_socket.send.assert_awaited_once()
s.handle(mocked_socket, mock_path)
If you have 3.8 you do not need to define asyncmock yourself
Oh
Also I am not sure if it's OK to use a string for the name of the spec
Pretty sure it has to be the object
Ah no, it can be a string
But if it's a string it says it has to be a list of strings
WebSocketServerProtocol is just the type that I got back when I used type(websocket)
Just seeing this: AttributeError: Mock object has no attribute 'recv'
I have updated the snippet above
Like I said, I think you should import the class and pass it as the spec instead of using its name as a string
oh as in import WebSocketServerProtocol
Also you should be using assert_awaited_once() at the end there
or any variant of that
Well sort of, but that import isn't exactly correct
probably from websockets.server import WebSocketServerProtocol
AssertionError: Expected send to have been awaited once. Awaited 0 times.
Isn't this because I am not awaiting the handle method?
So, I need to make my test async and then await the return of handle?
Yeah I would think that is why
Disclaimer that I have not much experience tested async code specifically
You probably can use asyncio.run()
so your actually unittest isn't a coroutine just to be clear
You're welcome
There was a lot of things wrong, but here is the final result:
class ServerTest(unittest.IsolatedAsyncioTestCase):
async def test_add_user(self):
mocked_socket = AsyncMock(WebSocketServerProtocol)
mock_path = MagicMock()
s = Server()
mocked_socket.recv.return_value = '{"Message": "!join", "Username": "test", "UserId": "123", "Email": "test@sad.com", "Color": "FireBurn", "IsModerator": "False", "IsSubscriber": "False"}'
await s.handle(mocked_socket, mock_path)
mocked_socket.send.assert_awaited_once()
why is the formatting being so lame lol
the py should be on the same line as the backticks
and without any space between then
Yeah
Now you can improve on that test
like checking which argument is used with send()
I think you were already gonna try to do that but didn't get around to it
mocked_socket.send.assert_called_with("some result")
Yeah it is done! :D
Mark I owe you one man. Anytime you need help I got you. Just send me a PM :)
I currently work as a .Net dev but I am trying to specialize in python because python is life
Don't mention it I don't do this with any expectations
But I fancy .NET so I'll keep that in mind if I have some issues
If you would like to pm your linkedin I will give you an endorsement :P @kind meadow
what's the best practice for using "structured" data in fixtures? right now i have something like this
@attr.s(slots=True)
class AdditionTestCase:
input1 = attr.ib()
input2 = attr.ib()
output_expected = attr.ib()
@pytest.fixture
def addition_test_case():
# make up some data
return AdditionTestCase(1, 2, 3)
def test_add(addition_test_case: AdditionTestCase):
input1 = addition_test_case.input1
input2 = addition_test_case.input2
output_expected = addition_test_case.output_expected
output_actual = input1 + input2
assert output_actual == output_expected
https://stackoverflow.com/q/58436712/2954547
asked the above on SO
Currently I have a setup like this:
./
src/
mylib.py
tests/
init.py
conftest.py
test_mylib.py
mylib.py contains:
def add(x, y):
return x + y
conftest.py contains:
i...
i need help witch option do i choose
if you have installed pycharm before or have another jetbrains ide which you've configured, select the first option
otherwise select the second option
if you're asking which im guessing you'd wanna pick the second
Why does this not work eventhough i type Athena//#This python code will request for what actions the user would like to take
code = raw_input("Good Day, what would you like to do today?: ")
while code >= "Athena":
if code is "Athena":
print ("Success")
else:
print ("Fail")
don't use is for equality checking
>>> f = input()
foo
>>> f
'foo'
>>> f is "foo"
False
>>> f == "foo"
True
>>>
also, use python3 it's almost 2020
hey guys anyone familiar with unittest?
use pytest
but for my assignment i have to use unittest
give me your professor's contact details I'll convince them to allow pytest also
hahah whats the difference though between the two?
i have a class and main function, i just need to implement unit testing for each function in the class
I think this might be the right place
I am stuck trying to understand pytest for my 2-3 compatible code
I am fairly new to python and unit testing has me quite in a loop
no one? :((
Sorry, you didn't really ask a question
You should specify what specific problem you have
!t ask
Asking good questions will yield a much higher chance of a quick response:
• Don't ask to ask your question, just go ahead and tell us your problem.
• Try to solve the problem on your own first, we're not going to write code for you.
• Show us the code you've tried and any errors or unexpected results it's giving.
• Keep your patience while we're helping you.
You can find a much more detailed explanation on our website.
So I fixed a script to be compatible in both 2.7 and 3.x. Now I must do a unit test, but I do not not how to interpret some of the functions into a test. Can anyone help me oversee some of these functions using pytest?
Hi guys, so I have this Signal class: https://paste.pydis.com/iyihugeqod.py
and Im running unit testing using this TestSignal class: https://paste.pydis.com/elilufozap.py
but when I run the test_comp function I get this error:
diff = Signal.compute_distance(self.signal,self.signal)
AttributeError: 'TestSignal' object has no attribute 'signal'
any idea why?
your compute_distance function only accepts one parameter
you're calling it as if it were a class method
yet it is an instance method
signal_1 = Signal(...)
signal_2 = Signal(...)
diff = signal_1.compute_distance(signal_2)
not python Signal.compute_distance(signal_1, signal_2)
oh, and that is not the problem anyway
your class TestSignal has no attribute signal
so hat goes into SIgnal()?
Hi all, I'm trying to test (using pytest) a class which uses class attributes for memoization. Tests are organised in classes. I've tried to use a fixture with scope class to avoid tests interfering with each other, especially between those classes but I haven't found a way yet. Does anyone know what I'm missing and maybe point me into a direction?
Running the test with -k "testname" succeeds, but running all tests fails as the previous tests interfere with the class attributes.
Can you just manually reset the class attributes
Hi Mark, that's what I'm doing as a workaround
e.g. with setup_class or setup_method
Hm. I'm doing it the very manual way myclass._classattr = {}
I'll look into setup_class, thanks
I'm not that familiar with pytest. In unittest there are functions you can use which will run before or after every test case
so it's convenient to place the resets in there
I think what I mentioned is the equivalent for pytest
though they suggest using fixtures, I'm not sure how that really compares
Cause you need to pass the fixture to every test case...
Might be an answer.. which uses fixtures. That's probably how I should do it. setup the class, yield it, then destroy it again
I'll look into it. If any pytest pro is reading this and knows a better way I'm eager to learn about it 🙂
@kind meadow : Thanks!
Np
Hi everyone, has any one here worked on puppeteer?
@maiden pawn I did quite a bit yes
ahh gt thanks @brazen void , i have query regarding it
what is it?
@brazen void there is another python api pyppeteer released for chromium
any idea on it ? and also for puppeteer , can we copy data into text file while running in headless mode?
currently i am using clip-boardy for copying data but it doesn't work in headless mode
I don't know about the new python api
but you can definitely write to files
you just have to do it asynchronously
or pipe your program stdout to a file
in headless too ?
yes
ok cool ,let me have a look by any chance you have any pointers ?
Hi all, I'm trying to remember the name of a service that's used for testing webhook endpoints. You run a proxy tool on your local dev box, and it gives a public endpoint that you can use with your 3rd party services. They poitn to this public provider, and the call is passed through to your local development environment. Anyone can tell me what I'm thinking of?
Sort of, but it doesn't require opening firewall. Client runs on your local workstation and connects to the public server and passes the requests in. I may be thinking of something that I saw with another language or cypto project.
I think it was https://ngrok.com/ @zinc coral
ngrok secure introspectable tunnels to localhost webhook development tool and debugging tool
hello any robot framework user @here ?
@proven flint please don't attempt to mass ping members just for an answer to a question
Github says here that they now support testing on multiple architectures https://github.com/features/actions
Has anyone found in the docs how you specify this in the configuration (.yml) files for a workflow?
@round cipher https://help.github.com/en/actions/automating-your-workflow-with-github-actions/workflow-syntax-for-github-actions
You can add a workflow file to your repository to create custom automated processes to automate your software development life cycle.
for each job, you can specify the environment you want (runs-on)
Yes, but how do I specify the architecture?
Here is how it's done in travis: https://docs.travis-ci.com/user/multi-cpu-architectures/
there is no github-provided environment for a different arch; they are all the same azure VM internally
so either 1) a self-hosted runner, or 2) the run-on-arch action in the marketplace
run-on-arch seems interesting, thanks!
a somewhat related question, how do I setup a matrix that creates one job for multiple values on the same environment variable?
Hi, is there anyone who read TDD with Python book?
I would have a question about Qunit
@tight geyser https://pypi.org/project/QUnitSuite/
oh cool didn't know that
I have a question regarding automation. is this the right channel to ask?
not unless it's test automation
Hello, anyone here versed in Pytest?
im running into some issues and hoping to get unblocked
im getting
Failed: Fixture "setUpClass" called directly. Fixtures are not meant to be called directly,
Here is my setUpClass:
@pytest.fixture
def setUpClass(cls):
cls.driver = webdriver.Chrome('/Users/me/PycharmProjects/website_automation/resources/drivers/chromedriver'
) #, options=chrome_options)
cls.driver.implicitly_wait(5)
driver = cls.driver
driver.get('https://www.google.com')
soup = BeautifulSoup(cls.driver.page_source, features="html.parser")
yield soup
The setup methods are called automatically and don't need to be fixtures. It therefore also doesn't make sense to yield anything from there.
@kind meadow Thanks for the reply. I guess whats weird is im getting three browser instances with my code
I only expect one
Hey everyone; little problem with pytest. So the problem is, I have something like client.run(client.login(user, password)) in the global scope. This function should update attributes of a client, however, this doesn't happen if I run a file with pytest command. Am I doing anything wrong?
wouldn't that code have then already been executed by the time you've imported the module?
I am doing client.run thing in the same file where the tests are @kind meadow
oh ok
Not exactly sure how the pytest command loads tests
IIRC there is a setupmodule function
Which is from unittest support
It recommends using fixtures instead of all that but not sure how they'd be use for module-level stuff
ok thanks, will have a read
Eh I dunno about that last link, doesn't seem very relevant. Cause to use fixtures you still gotta use it as a parameter for something
lol can’t figure it out
I am feeling dumb
client = gd.Client()
client.run(client.login('...', '...'))
def test():
...``` like why does it say that client is not logged in if it should?
did you try using setup_module?
If you can't get that to work then I suppose resort to fixtures
I'm trying to unit test a flask app with SQLAlchemy/Marshmallow. Is there some standard way of setting up a temporary SQLite DB following the schema that I'm missing
no - sqlalchemy should make that easy for you
it's been a while but when I used that setup I just used sqlite in-memory db as the driver and everything else worked the same
as long as you don't use db-specific features; I remember the sqlite version I had was ancient and didn't support CTEs so I couldn't test that feature in the same way
hi every one i have query regarding post JSON query
i am trying something like Request body is a JSON object containing a "text" field, for
example: {"text": "a new quote"}. The response data will contain the text
and the new ID.
Example response data:
{"id": 3, "text": "a new quote"}
i have tried json.dumps but some how not sure why it is not working
it throws error TypeError: list indices must be integers or slices, not str
will appreciate any help or pointers
i am able to do post query but now whenever i am trying to POST multiple value it is just posting last value and not other values i tried to use for loop
payload = {'text': 'What am i missing','text': 'Beautiful day','text': 'everyday is beautiful'}
for value in payload:
print (value)
response = requests.post(url,data=json.dumps(payload))
print(response.json())
dictionaries are not indexed and need the .key(), .value(), .item() methods to iterate through a dictionary:
for v in paload.value():
no; you are using the same key for multiple values
true. If you want just the value though and not the key, a method is needed.
otherwise, looping though will give you the tuple of each key : value pair
>>> payload = {'text': 'What am i missing','text': 'Beautiful day','text': 'everyday is beautiful'}
>>> payload
{'text': 'everyday is beautiful'}
@tight geyser @wet jacinth thanks for your replies but my req is riting POST query which Accepts a string as the "text" field, e.g. {"text": "I have a dream"}.
The response data contains a new ID and the text as provided in the
request
"id": 4,
"text": "py testing is cool"
},
{
"id": 5,
"text": "Awesome"
but i think yeah i got the point
seems i would have to post one by one if i have to keep key value as constant
I have selenium and im trying to have it switch to another tab to run code in that. I was able to get it to open a new tab and switch to it but the actual code running wont change and it will keep running in the other tab please help
how im i able to jump to a function definition in vscode in python?
ctrl + left click
but the best hot key is ctrl + shift + p. You can search everything from there.
ty @hallow hawk
Which test runner is considered best these days?
Unittest or pytest
Is it possible to program a Discord bot entirely with Python?
I've seen the inclusion of JavaScript of which I wish to avoid until I learn it, which I won't until I am comfortable with Python.
Yes
Our bot is written in Python; it uses the discord.py package. See #discord-bots for more info.
Normally I'd patch my function with @patch, like this:
def function_to_test():
return uuid.uuid4().hex
@patch('myfile.uuid.uuid4')
def test_uuid_hex(mock_uuid):
mock_uuid.return_value.hex = '704ae5472cae4f8daa8f2cc5a5a8mock'
assert '704ae5472cae4f8daa8f2cc5a5a8mock' == function_to_test()
How would I do this with monkeypatch? Or should I just keep with unittest mock?
In Pytest that is
Or do I use mocker?
i'm working on a PR for django-celery-results package, and having some issues with pip in the context of tox -- celery packages all have a dependency on sphinx-celery, which currently requires Sphinx>=2.0.0 , which exists according to PyPI.org but not according to my pip. plain pip install gives me 1.8.5; running tox test results in an error for the docs test that requires those deps because the requirement cannot be met ( DistributionNotFound error). pip in this virtualenv is up-to-date.
What version of Python does your env use
the virtualenv and the host system still default to python2.7 but my limited understanding was that tox creates its own envs
in order to get the tests running, this system has 2.7, 3.5, 3.6, 3.7 all available
oh, and pypy/pypy3
ok, i see, sphinx>=2 requires python >= 3.5 or so
anyone know a good way of using pytest along with assert statements inside the code? I would like to test multiple statements. This works, but its tedious to add with pytest... every time
assert x>0, "wrong"
return x+1 ```
``` test_func():
with pytest.raises(AssertionError):
func(-1)
with pytest.raises(AssertionError):
func(-2)
You can use the parameterisation decorator
Guys can anybody recommend good open source selenium python framework which supports similar features like testng (like suite, tag level execution and extensible).
I checked out seleniumbase which is good so far but it's containing too much base code for customizing. I have csharp and Java background. Looking for python solution for the new requirement to extend to it our needs. Thanks
@modern rain you can go with pytest, behave, robotframework
@pastel copper . Behave looks interesting and matches the criteria we need. Will try it. Thanks 👍
@modern rain 👍
Just finished my first program at home and not at school!
eggsMin = int(3) sugarMin = int(1) milkMin = int(240) flourMin = int(225) bakingPowderMin = int(1) vanillaSugarMin = int(1) import time print("Hello") time.sleep(2) print("Pancake Recipe is starting up....") time.sleep(2) eggsAmmount = int(input("How many eggs do you have? (You need three!)")) if eggsAmmount < eggsMin: time.sleep(2) print("Sorry, you don't have enough eggs!") time.sleep(2) exit() else: time.sleep(2) print("Next ingredient!") time.sleep(2) sugarAmmount = int(input("How much sugar do you have (tbsp)? (You only need one tablespoon!)")) if sugarAmmount < sugarMin: time.sleep(2) print("Sorry, you don't have enough sugar!") time.sleep(2) exit() else: time.sleep(2) print("Next ingredient!") time.sleep(2) milkAmmount = int(input("How much milk do you have (ml)? (You need 240ml!)")) if milkAmmount < milkMin: time.sleep(2) print("Sorry, you don't have enough milk!") time.sleep(2) exit() else: time.sleep(2) print("Next ingredient!") time.sleep(2) flourAmmount = int(input("How much flour do you have (g)? (You need 225g!)")) if flourAmmount < flourMin: time.sleep(2) print("Sorry, you don't have enough flour!") time.sleep(2) exit() else: time.sleep(2) print("Next ingredient!") time.sleep(2) bakingPowderAmmount = int(input("How much baking powder do you have (tsp)? (You only need one!)")) if bakingPowderAmmount < bakingPowderMin: time.sleep(2) print("Sorry, you don't have enough baking powder!") time.sleep(2) exit() else: time.sleep(2) print("Next ingredient!") time.sleep(2)
`vanillaSugarAmmount = int(input("How much vanilla sugar do you have (packets)? (You only need one!)"))
if vanillaSugarAmmount < vanillaSugarMin:
time.sleep(2)
print("Sorry, you don't have enough vanilla sugar!")
time.sleep(2)
exit()
else:
time.sleep(2)
print("Time to begin the creation of the pancake batter in ten easy steps!")
time.sleep(2)
print("Step one, separate the eggs.")
time.sleep(3)
print("Step two, add a pinch of salt to the egg whites and beat until stiff, you can either use an electric mixer or mix by hand but an electric mixer is reccomended.")
time.sleep(3)
print("Step three, in a separate bowl, add the yolks and the regular sugar and mix until you cannot feel the bits of sugar and they are not visible anymore.")
time.sleep(3)
print("Step four, add the milk and flour to the yolks bit by bit and mix by hand until the ingredients have been incorporated.")
time.sleep(3)
print("Step five, add the baking powder and mix.")
time.sleep(3)
print("Step six, add the vanilla sugar and mix.")
time.sleep(3)
print("Step seven, mix the egg whites and your other mixture slowly with a wooden spoon or silicon spatula to not pop any air bubbles in the egg whites until the mixtures have been fully incorporated.")
time.sleep(3)
print("Step eight, put about two tablespoons of cooking oil (sunflower oil) in a pan and let it heat up.")
time.sleep(3)
print("Step nine, put a ladle of batter on the pan, wait until there are lots of air bubbles on the top and on the bottom, it has browned a bit, then flip the pancake, be sure that it is ready to flip before flipping, you only want to flip it once!!")
time.sleep(3)
print("Step ten, enjoy! :)")`
It's very long and probably very inneficient but It's my first and I'm proud of it!
The recipe actually works if anyone would like to try it out
lol gj
Thanks
😀
Any tips on cutting a bit of writing out of it?
This isn't the correct channel for that. You can post it I #303934982764625920
Just be sure to read the channel's description first
Sorry @kind meadow
does anyone know a good video about how the PATH in python works?
I'd be surprised if such a thing existed; it's pretty simple
PATH works the same way in all UNix programs: when your program goes to run some other program, and if the name of that other program doesn't begin with a /, the calling program looks in each directory named in PATH until it finds the named program.
that's pretty much it
Here's the authoritative reference: https://www.gnu.org/software/libc/manual/html_node/Standard-Environment.html#index-PATH-environment-variable
Standard Environment (The GNU C Library)
@rain wigeon ^^
thank you @marsh raft
@grizzled terrace
I see, thanks @wild roost
can someone test my project and give feedback? the username and password are username and password https://github.com/Nightarcher3677/OASIS
I know this has been asked a lot, but what are the best QA testing tools/software ?
@marsh raft pytest is good? is it not a bit annoying to add "." to the pythonpath in order to test?
You don't have to do that
I never had to do that, but I use it through a proprietary harness
You don't have to do that
@halcyon zodiac not? what am i doing wrong?
I don’t know
@rain wigeon what does your dir structure look like
tree -d .
you can run pytest via python python -m pytest
or add __init__.py files wherever you have python source files
@tight geyser nice, ty
Hey all, anyone have an idea how I can post json while testing in flask?
self.app.post(API_ENDPOINT, json={'size': 'Medium'}) isn't working
@teal harbor , json should be passed as data
@teal harbor u mean, u are trying to post this data in ur flask app ?
What's the difference between an engine and an IDE, and can games be created solely with one or the other?
I've seen people talk about Python libraries to aid in the development of games but I'm curious whether there is some specific mediums in which such games must be developed in, such as an engine perhaps?
I'm not entirely sure, I'd appreciate any clarifications about the matter; thank you.
This is a question probably better suited to #tools-and-devops or probably #game-development. But the little information I can provide on it is that a game engine is closer to a programming language than an IDE, an IDE is like a really powerful text editor, a game engine is like a software library (but not quite) that does things like graphics and ounds for you
engine - a program somebody made for physics calculations that is commonly used as a foundation for game mechanics(movement, bullets, hitboxes etc etc)
ide - a program that is used to edit code. IDE has a ton of features like interactive debugger, class inspector, definition finder etc etc
to make a game, you will almost certainly use a some kind of game engine if you are building 3d game or some indie 2d game
and to edit the code and develop your game, you'll probably use an ide that is compatible with your language of choice
for more info, head over to #game-development
guys and gals over there have more knowledge on this topic and how it interacts with one another :))
Quick question, I use selenium to test my employers website. Now we are planning to move to apps. I am looking for a solution to test on an adroid/ios app. Do you know of any good frameworks ?
If not what should I Google ??
Something along the lines of "App testing framework" or "selenium equivalent for apps" - Appium was one of the things I found in a couple of minutes on Google @fierce ocean
appium looks like what I was looking for. For anyone else interested I found froglogics' squish. However it doesn't seem to be open source. Have you had experience with it. I am just wondering whether it is worth splash money on it.
Hi am looking to learn about python am new to programing
@vernal jungle Hey, nice! This channel is more for a specific subject though (tests programs). You'll have more replies by posting here: #python-discussion 😉
Thx
I have this sort of set up ```py
thing.py
from x import y
class Thing:
pass
init.py
from thing import Thing
In my tests I'm using `init.Thing()` rather than the more direct `thing.Thing()`. I need to patch `thing.y`. But specifying `thing.y` for the patch does not correctly patch it. Is it possible to somehow patch `thing.y` while using `init.Thing()`?
Never mind, it was patching properly
I just messed something up elsewhere
Hi Guys, I have a testing scenario where i need to send a notification to mobile device and accept the notification once after its reaches the mobile device.
- in this scenario sending notification part is done
- I have a script which intercepts the notification and accepts the notification, but currently its on a physical mobile device.
Would like to explore some option to replace that physical device with a emulator / any other suggestions ?
maybe a web service? I don't know how mobile devices work
I'd guess the mobile device is either a web service, or (more likely) a long-polling client of something like a queueing system
Push notifications are small messages that can reach audiences anywhere and anytime. While pop-ups appear only when audiences are on the site they belong to, push messages are independent of sites. They are associated with web browsers and apps.
Push technology, or server pu...
not exactly a push
or a web service
assume that i receive whatsapp notifications on my mobile
i would like to delete the notification as soon as it arives
oh, then you probably need to have your app somehow talk to whatsapp, or the mobile OS
I really don't know
we generally use tasker app to do automation in our devices
like intercepting notification, read messages redirect things etc.
tasker - mobile app
yeah I've used tasker
im looking for some emulator which acts like a real mobile device
so that i can redirect all the notifications to that particular device
and get it automated
well if the emulator has to run WhatsApp, I dunno how to do that.
I know that the Android developer kit comes with an emulator, but I don't know if you can control it via an API
iOS presumably is similar
ya even i was thinking about android sdk
but still that is last option
if i can find something like browserstack or some other online based emulators
it really helps me
thanks for ur suggestion @marsh raft
👍
i will do a little research around it and go with the best
is there a tool that can detect useless python tests?
Here's the use case: someone fixes a bug and also adds tests that allegedly demonstrate that the bug is fixed. The tool will then run the new tests but on the original source code. If they pass, the tests are found to be useless
That seems to be the wrong way around.
You'd normally start writing a failing test, and only then fix the bug.
I'm not understanding why such a test would be useless
Isn't that a regression test?
yes in some flavors of TDD you would commit a failing test first, that would be one solution
I suppose you could also write tautological tests
which would be useless
Hi everyone! I'm running into troubles with pytest.
I need to print some information for test cases with long execution. I found that pytest-print library will help me.
So I'm trying something like this (simple example):
import pytest
run test script
def test_myTestCase(printer, spark_session):
# test case logic here
printer("Print my Message")
# assert
printer("Print successfull step result")
But, when I run
$pytest test_myfile.py - I'm not getting any printed out messages
when test case success...
already found the solution. I had to run:
$pytest test_myfile.py -v
-v attribute did the magic 🙂
i am in a hurry to write boat loads of tests, what's the best library/framework to write tests with?
i am thinking between pytest and unittest
In my experience pytest didn't feel any faster to write tests with. In fact, sometimes it was harder to understand how to use the library.
unittest is native library and you can use it out of the box with python. But it involves boilerplate of code for tests.
Pytest on the other hand is additional library installed through pip. Tests are alot more compact, as additional library it adds additional dependancies to your test framework
I prefer unittest for its simplicity but it's just that - a preference ultimately
yeah it took for me some time to get into pytest functionality
but in the end - I was able to do all the neccessary things
plus pytest - has extension to run your tests in parallel
for unittest - you will have to implement parallelisation logic on your own
Surely there's a library for that
so in my case I chose pytest just because of parallelism
yeah but it is again - one more dependency 🙂
I agree with the statement - it's just that - a preference ultimately
If you've not used pytest before then I would not recommend it if you are in a hurry as it is a bit steeper learning curve
Surely there's a library for that
Apparently it's very easy to run unittest tests with pytest and achieve the same parallelism
i've personally not had to use testing of any kind quite yet (but will soon actually) however i did find that one of our members actually made a very impressive test suite.
https://github.com/darrenburns/ward
i'm honestly not sure if it actually is any better or offers any more simplicity or complexity versus pytest or unittest, it just seems fairly promising
I'm doing QA Engineering for my life. And would never pick some random testing framework. You want your framework to be viable after 2-3-5 years. And what should I do if he abandons support of his "brand new framework"? 🙂