python click passing multiple key values as options - python-click

I am using python-click and I would like to pass values with a format like this
myprogram mycommand --parameter param1=value1 --parameter param2=value2
I was looking at click option documentation but I can't find any construct that could help with this, the only solution I can find is invoking a callback function and check that the string is properly constructed <key>=<value>, then elaborate the values properly.
Nothing bad in that solution, but I was wondering if there is a more elegant way to handle this since the pattern looks to be common enough.

So, I've had a go at it. I've managed to do it the following ways.
Firstly, I've tried this, though it doesn't satisfy the --parameter criteria.
#click.command("test")
#click.argument("args", nargs=-1)
def test(args):
args = dict([arg.split("=") for arg in args])
print(args)
so when invoking like test param1=test1 param2=test the output is:
{'param1': 'test1', 'param2': 'test2' }
Secondly, I thought about a multiple option, combined with a variadic argument, which seems to be closer to your requirements:
test -p param1=test -p param2=test
#click.command("test")
#click.option('-p', '--parameter', multiple=True)
#click.argument("args", nargs=-1)
def test(*args, **kwargs):
param_args = kwargs['parameter']
param_args = dict([p.split('=') for p in param_args])
print(param_args)
if __name__ == '__main__':
test()
The output will be the same as the previous case.
If you were to print(kwargs['parameter']), you'd get
('param1=test', 'param2=test')
It sounds a bit more cleaner than using a callback, but not by much. Still, hope it helps.

Related

How i get the original variable name for a parameter inside a function call? (Python 3.7)

First, i want to say there are a few questions related to this topic but the answers are not what I'm looking for, those questions are related to files or something else so it shouldn't be count as a duplicated, but if you find a duplicated question makes me know an i will change this.
Description:
I need to print the original variable name passed to a function.
This code is an example to show what i want (Take this code as a starting point if you want):
def print_var_name(var):
original_var_name = do_something_here
print(original_var_name)
var_1 = 'foo'
print_var_name(var_1)
The output should be:
var_1
Thanks you guys!

pytest function without return value

I'm trying to do a pytest on a function without return value, but obviously value is None in pytets. I was wondering if there is a solution for that?
here is function which I'm trying to test:
def print_top_movies_url():
for item in movie_link[:100]:
print item.contents[1]
The best thing to do would be to separate getting the top movies and printing them.
For example, you could have a top_movie_urls which looks like this:
def top_movie_urls():
urls = []
for item in movie_link[:100]:
urls.append(item.contents[1])
return urls
(or make it a generator function)
That's easy to test, and wherever you call it, you can now just do something like print('\n'.join(top_movie_urls())).
If you really want to test the output instead, you can use pytest's output capturing to access the output of the tested function and check that.

Gatling. Check, if a HTML result contains some string

Programming Gatling performance test I need to check, if the HTML returned from server contains a predefined string. It it does, break the test with an error.
I did not find out how to do it. It must be something like this:
val scn = scenario("CheckAccess")
.exec(http("request_0")
.get("/")
.headers(headers_0)
.check(css("h1").contains("Access denied")).breakOnFailure()
)
I called the wished features "contains" and "breakOnFailure". Does Gatling something similar?
Better solutions:
with one single CSS selector:
.check(css("h1:contains('Access denied')").notExists)
with substring:
.check(substring("Access denied").notExists)
Note: if what you're looking for only occurs at one place in your response payload, substring is sure more efficient, as it doesn't have to parse it into a DOM.
Here ist the solution
.check(css("h1").transform((s: String) => s.indexOf("Access denied"))
.greaterThan(-1)).exitHereIfFailed
You can write it very simple like:
.check(css("h1", "Access denied").notExists)
If you are not sure about H1 you can use:
.check(substring("Access denied").notExists)
IMO server should respond with proper status, thus:
.check(status.not(403))
Enjoy and see http://gatling.io/docs/2.1.7/http/http_check.html for details
EDIT:
My usage of CSS selector is wrong see Stephane Landelle solution with CSS.
I'm using substring way most of the time :)

Where are `_stdlib_getTypeName()` & `_stdlib_getDemangledTypeName()` declared? -- Swift

I'm toying with some introspection in Swift and it seems like if you want to get the class of an object in a printable version, these are the best options. (introduced in beta 6.0).
_stdlib_getTypeName(someClass)
_stdlib_getDemangledTypeName(someClass) // A slightly cleaner version
I was hoping to find other introspection methods, but unfortunately, command clicking the methods take me to the Swift header and they're not declared there.
My other option would be to type _stdlib and wait for autocomplete or control space to see my options. Unfortunately, none of these methods autocomplete.
Is there a file where these and other stdlib functions are declared, or is there documentation for these methods anywhere?
I found the answer to my question via a tips and tricks blog post from realm here -- notably, the post by JP Simard.
The best way to see other methods along these lines is to go to your terminal and type:
cd `xcode-select -p`/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx
And then enter the following:
nm -a libswiftCore.dylib | grep "T _swift_stdlib"
This will give you a readout of all available functions that looks something like this:
00000000001a43c0 T _swift_stdlib_NSObject_isEqual
00000000001a4490 T _swift_stdlib_NSStringHasPrefixNFD
00000000001a44f0 T _swift_stdlib_NSStringHasSuffixNFD
00000000001a4450 T _swift_stdlib_NSStringNFDHashValue
00000000001a2650 T _swift_stdlib_atomicCompareExchangeStrongPtr
00000000001a2670 T _swift_stdlib_atomicCompareExchangeStrongUInt32
00000000001a2690 T _swift_stdlib_atomicCompareExchangeStrongUInt64
00000000001a2700 T _swift_stdlib_atomicFetchAddUInt32
00000000001a2710 T _swift_stdlib_atomicFetchAddUInt64
00000000001a26f0 T _swift_stdlib_atomicLoadPtr
00000000001a26d0 T _swift_stdlib_atomicLoadUInt32
00000000001a26e0 T _swift_stdlib_atomicLoadUInt64
00000000001a26b0 T _swift_stdlib_atomicStoreUInt32
00000000001a26c0 T _swift_stdlib_atomicStoreUInt64
00000000001a4410 T _swift_stdlib_compareNSStringDeterministicUnicodeCollation
000000000017c560 T _swift_stdlib_conformsToProtocol
00000000001a5a80 T _swift_stdlib_demangleName
000000000017c8e0 T _swift_stdlib_dynamicCastToExistential1
000000000017c6f0 T _swift_stdlib_dynamicCastToExistential1Unconditional
00000000001a5910 T _swift_stdlib_getTypeName
I haven't found any documentation, but a lot of these function names are fairly explanatory and one can always discover a lot through trying them out!
All answers are good, but the result of second step that we can not use. We dont even know is this function usable or correct...
I've been trapped in these result about 1 day.
Finally I dump all funcitons & symbols for stdlib from libswiftcore.dylib, i found this..
command:
nm libswiftcore.dylib | grep "_stdlib_"
We can find one line from result:
00000000000b2ca0 T __TFSs19_stdlib_getTypeNameU__FQ_SS
Remove first underscore "_" then we get this:
_TFSs19_stdlib_getTypeNameU__FQ_SS
Maybe we can view this website to understand the meaning of "_TFSs19_stdlib_getTypeNameU__FQ_SS",
But I think we can get the correct function description faster!!
So, we demangle like this below in xcode lldb window:
(lldb) p _stdlib_demangleName("_TFSs19_stdlib_getTypeNameU__FQ_SS")
(String) $R0 = "Swift._stdlib_getTypeName <A>(A) -> Swift.String"
Finally we can expose more undocumented functions in swift that we never seen before, we can try another one that we never heard like this:
(lldb) p _stdlib_demangleName("_TFSs24_stdlib_atomicLoadARCRefFT6objectGVSs20UnsafeMutablePointerGSqPSs9AnyObject____GSqPS0___")
(String) $R1 = "Swift._stdlib_atomicLoadARCRef (object : Swift.UnsafeMutablePointer<Swift.Optional<Swift.AnyObject>>) -> Swift.Optional<Swift.AnyObject>"
All clear~ Thank god!!
Share this to you, wish it can help~
:D

Parsing options that take more than one value with scopt in scala

I am using scopt to parse command line arguments in scala. I want it to be able to parse options with more than one value. For instance, the range option, if specified, should take exactly two values.
--range 25 45
Coming, from python background, I am basically looking for a way to do the following with scopt instead of python's argparse:
parser.add_argument("--range", default=None, nargs=2, type=float,
metavar=('start', 'end'),
help=(" Foo bar start and stop "))
I dont think minOccurs and maxOccurs solves my problem exactly, nor the key:value example in its help.
Looking at the source code, this is not possible. The Read type class used has a member tuplesToRead, but it doesn't seem to be working when you force it to 2 instead of 1. You will have to make a feature request, I guess, or work around this by using --min 25 --max 45, or --range '25 45' with a custom Read instance that splits this string into two parts. As #roterl noted, this is not a standard way of parsing.
It should be ok if only your values are delimited with something else than a space...
--range 25-45
... although you need to split them manually. Parse it with something like:
opt[String]('r', "range").action { (x, c) =>
val rx = "([0-9]+)\\-([0-9]+)".r
val rx(from, to) = x
c.copy(from = from.toInt, to = to.toInt)
}
// ...
println(s" Got range ${parsedArgs.from}..${parsedArgs.to}")