Implement custom assert for string matching - pytest

I'm implementing a unittest to check if certain strings in an application start with a legal prefix. For example as a test function body I now have:
strings_to_check = ['ID_PRIMARY','ID_FOREIGN','OBJ_NAME', 'SOMETHING_ELSE']
for s in strings_to_check:
assert s.startswith('ID_') or\
s.startswith('OBJ_')
But the AssertionError that is returned is quite verbose (the real code has more legal prefix option). I found this in the documentation, but that focusses on assertion between (custom) objects. Is there a way to write you own custom assertion function that returns a easier to read message?

You could do something like this:
def test_myex1(myfixture):
myfixture.append(1)
strings_to_check = ['ID_PRIMARY','ID_FOREIGN','OBJ_NAME', 'SOMETHING_ELSE']
for s in strings_to_check:
failing_string = f'variable s: {s} does not start with valid string'
assert s.startswith('ID_') or s.startswith('OBJ_'), failing_string
Which produces a traceback like:
> assert s.startswith('ID_') or s.startswith('OBJ_'), failing_string
E AssertionError: variable s: SOMETHING_ELSE does not start with valid string
raisetest.py:6: AssertionError

Related

FSharpLint, how to use the rule "InterfaceNamesMustBeginWithI" in SuppressMessageAttribute?

[<SuppressMessage("NameConventions","InterfaceNamesMustBeginWithI")>] //No effect
[<SuppressMessage("NameConventions","InterfaceNames")>] //It's working
module Test=
type [<AllowNullLiteral>] MutationEvent =
abstract attrChange: float with get, set
...
Also, failed to search source code about "InterfaceNamesMustBeginWithI".
The name of the rule is InterfaceNames, so you can suppress it thus:
[<SuppressMessage("","InterfaceNames")>]
module Test =
...
Also note that the first argument to SuppressMessage is not used by fsharplint, so it can be anything (although not null, strangely enough!)
There are pointers to InterfaceNamesMustBeginWithI in the documentation, but this is not correct.

Method invocation may produce 'NoMethodError' in Ruby

I have some code:
# frozen_string_literal: true
require 'httpclient'
client = HTTPClient.new
response = client.get 'https://httpbin.org/get'
body = response.body
puts body
Why RubyMine have warning about Method invocation may produce 'NoMethodError'?
There's a corresponding issue on the RubyMine's tracker so you can follow it:
https://youtrack.jetbrains.com/issue/RUBY-24592
Basically, any object that doesn't respond to the method that's being invoked will raise a NoMethodError.
class Response
def body
'hardcoded body'
end
end
class ResponseWithoutBody; end
p Response.new.body
# "hardcoded body"
p ResponseWithoutBody.new.body
# `<main>': undefined method `body' for #<ResponseWithoutBody:0x00007fe903028e08> (NoMethodError)
In your case, if response returns nil, or any other object which doesn't implement body, then you're going to have a NoMethodError.
If you're pretty sure, you're never going to get nil after invoking get on client, then you can omit that warning message.

How to pass parameters to a Progress program using database field dynamic-based rules?

I have in my database a set of records that concentrates information about my .W's, e.g. window name, parent directory, file name, procedure type (for internal treatments purposes), used to build my main menu. With this data I'm developing a new start procedure for the ERP that I maintain and using the opportunity in order to rewrite some really outdated functions and programs and implement new functionalities. Until now, I hadn't any problems but when I started to develop the .P procedure which will check the database register of a program that was called from the menu of this new start procedure - to check if it needs to receive fixed parameters to be run and its data types - I found a problem that I can't figure out a solution.
In this table, I have stored in one of the fields the parameters needed by the program, each with his correspondent data type. The problem is on how to pass different data types to procedures based only on the stored data. I tried to pre-convert data using a CASE clause and an include to check the parameter field for correct parameter sending but the include doesn't work as I've expected.
My database field is stored as this:
Description | DATATYPE | Content
I've declared some variables and converted properly the stored data into their correct datatype vars.
DEF VAR c-param-exec AS CHAR NO-UNDO EXTENT 9 INIT ?.
DEF VAR i-param-exec AS INT NO-UNDO EXTENT 9 INIT ?.
DEF VAR de-param-exec AS DEC NO-UNDO EXTENT 9 INIT ?.
DEF VAR da-param-exec AS DATE NO-UNDO EXTENT 9 INIT ?.
DEF VAR l-param-exec AS LOG NO-UNDO EXTENT 9 INIT ?.
DEF VAR i-count AS INT NO-UNDO.
blk-count:
DO i-count = 0 TO 8:
IF TRIM(programa.parametro[i-count]) = '' THEN
LEAVE blk-count.
i-count = i-count + 1.
CASE ENTRY(2,programa.parametro[i-count],CHR(1)):
WHEN 'CHARACTER' THEN
c-param-exec[i-count] = ENTRY(3,programa.parametro[i-count],CHR(1)).
WHEN 'INTEGER' THEN
i-param-exec[i-count] = INT(ENTRY(3,programa.parametro[i-count],CHR(1))).
WHEN 'DECIMAL' THEN
de-param-exec[i-count] = DEC(ENTRY(3,programa.parametro[i-count],CHR(1))).
WHEN 'DATE' THEN
da-param-exec[i-count] = DATE(ENTRY(3,programa.parametro[i-count],CHR(1))).
WHEN 'LOGICAL' THEN
l-param-exec[i-count] = (ENTRY(3,programa.parametro[i-count],CHR(1)) = 'yes').
OTHERWISE
c-param-exec[i-count] = ENTRY(3,programa.parametro[i-count],CHR(1)).
END CASE.
END.
Then I tried to run the program using an include to pass parameters (in this example, the program have 3 INPUT parameters).
RUN VALUE(c-prog-exec) ({util\abrePrograma.i 1},
{util\abrePrograma.i 2},
{util\abrePrograma.i 3}).
Here is my abrePrograma.i
/* abrePrograma.i */
(IF ENTRY(2,programa.parametro[{1}],CHR(1)) = 'CHARACTER' THEN c-param-exec[{1}] ELSE
IF ENTRY(2,programa.parametro[{1}],CHR(1)) = 'INTEGER' THEN i-param-exec[{1}] ELSE
IF ENTRY(2,programa.parametro[{1}],CHR(1)) = 'DECIMAL' THEN de-param-exec[{1}] ELSE
IF ENTRY(2,programa.parametro[{1}],CHR(1)) = 'DATE' THEN da-param-exec[{1}] ELSE
IF ENTRY(2,programa.parametro[{1}],CHR(1)) = 'LOGICAL' THEN l-param-exec[{1}] ELSE
c-param-exec[{1}])
If I suppress the 2nd, 3rd, 4th and 5th IF's from the include or use only one data type in all IF's (e.g. only CHAR, only DATE, etc.) the program works properly and executes like a charm but I need to call some old programs, which expects different datatypes in its INPUT parameters and using the programs as described OpenEdge doesn't compile the caller, triggering the error number 223.
---------------------------
Erro (Press HELP to view stack trace)
---------------------------
** Tipos de dados imcompativeis em expressao ou atribuicao. (223)
** Nao entendi a linha 86. (196)
---------------------------
OK Ajuda
---------------------------
Can anyone help me with this ?
Thanks in advance.
Looks as if you're trying to use variable parameter definitions.
Have a look at the "create call" statement in the ABL reference.
http://documentation.progress.com/output/ua/OpenEdge_latest/index.html#page/dvref/call-object-handle.html#wwconnect_header
Sample from the documentation
DEFINE VARIABLE hCall AS HANDLE NO-UNDO.
CREATE CALL hCall.
/* Invoke hello.p non-persistently */
hCall:CALL-NAME = "hello.p".
/* Sets CALL-TYPE to the default */
hCall:CALL-TYPE = PROCEDURE-CALL-TYPE
hCall:NUM-PARAMETERS = 1.
hCall:SET-PARAMETER(1, "CHARACTER", "INPUT", "HELLO WORLD").
hCall:INVOKE.
/* Clean up */
DELETE OBJECT hCall.
The best way to get to the bottom of those kind of preprocessor related issues is to do a compile with preprocess listing followed by a syntax check on the preprocessed file. Once you know where the error is in the resulting preprocessed file you have to find out which include / define caused the code that won't compile .
In procedure editor
compile source.w preprocess source.pp.
Open source.pp in the procedure editor and do syntax check
look at original source to find include or preprocessor construct that resulted in the code that does not compile.
Okay, I am getting a little bit lost (often happens to me with lots of preprocessors) but am I missing that on the way in and out of the database fields you are storing values as characters, right? So when storing a parameter in the database you have to convert it to Char and on the way out of the database you have convert it back to its correct data-type. To not do it one way or the other would cause a type mismatch.
Also, just thinking out loud (without thinking it all the way through) wonder if using OOABL (Object Oriented ABL) depending on if you Release has it available wouldn't make it easier by defining signatures for the different datatypes and then depending on which type of input or output parameter you call it with, it will use the correct signature and correct conversion method.
Something like:
METHOD PUBLIC VOID storeParam(input cParam as char ):
dbfield = cParam.
RETURN.
END METHOD.
METHOD PUBLIC VOID storeParam(input iParam as int ):
dbfield = string(iParam).
RETURN.
END METHOD.
METHOD PUBLIC VOID storeParam(input dParam as date ):
dbfield = string(dParam).
RETURN.
END METHOD.
just a thought.

Cannot use mandatory uuid (or other pattern-related must-be type) as rpc argument

I have webservice like this:
class ExampleService(ServiceBase):
__tns__ = 'http://xml.company.com/ns/example/'
#rpc(Mandatory.Uuid, _returns=Unicode)
def say_my_uuid(ctx, uuid):
return 'Your UUID: %s' % uuid
#classmethod
def dispatch(cls):
application = Application([cls],
tns=cls.__tns__,
interface=Wsdl11(),
in_protocol=Soap11(validator='lxml'),
out_protocol=Soap11(cleanup_namespaces=True)
)
return csrf_exempt(DjangoApplication(application))
I can use Uuid as an argument, but when I'm trying its mandatory version then server response with error:
XMLSchemaParseError at /
simple type 'MandatoryUuid', attribute 'base': The QName value '{http://www.w3.org/2001/XMLSchema}MandatoryString' does not resolve to a(n) simple type definition., line 12
Exception Location: D:\Program Files\Python27\lib\site-packages\spyne\interface\xml_schema\_base.py in build_validation_schema, line 183
Why I can't customize Uuid type? If I remove pattern from its definition then everything is ok, but there must be a pattern for UUID anyway. Is there any workaround? Maybe another soap framework?
I have just released Spyne-2.9.5 which contains the fix for this issue.

Early return from a Scala constructor

I am writing the constructor for my "main" class. The first thing it does is call a method to use commons-cli to parse the command line. If the parseOptions method returns false, an error has occurred, and the constructor should exit.
I tried writing the following code
if (!parseOptions(args)) return
but the compiler complains that I have a "Return statement outside method definition".
Short of calling System.exit(1) or inverting the boolean (and putting all of the rest of my logic inside the if statement, is there any way to return "early" from a constructor?
I suppose I could have the parseOptions method throw an IllegalArgumentException and catch that in my Main object.
Thanks.
Dont try to do a early/premature return, this makes your code harder more complex, since the side effects of the return can be hard to understand. Instead use a exception to signal that something is wrong.
You can use require in the constructor. This doesn't return. But it seems like throwing an exception actually fits his situation better.
As in:
class MyTest(
private var myValue: Int ){
require(myValue > 0) // Connected to constructor
}
defined class MyTest
scala> val x = new MyTest(10)
x: MyTest = MyTest#49ff4282
scala> val y = new MyTest(-10)
java.lang.IllegalArgumentException: requirement failed
at scala.Predef$.require(Predef.scala:133)
is there any way to return "early" from a constructor
No. But in your case it sounds like bad design, anyway.
If the parseOptions method returns false, an error has occurred
In this case the constructor should throw an exception, not return normally.
A constructor should always either complete fully, or abort (throw an exception). Anything else leaves your object "half constructed" and thus impossible to reason about.
If in your case, the object is valid even if parseOptions failed, then you can change the condition and continue:
if (parseOptions(args)) {
// rest of constructor
}