How to Validate variable can have a vale either NULL or in String format - api

I'm starting to use karate for testing. I need to validate one json response.
JSON Schema Design:
response{
id* Integer Not null
Name* String can be null
}
now i need to verified id and name with below constraints,
id should be integer and should not be null.
Name can either in string or can be null.
what equation we can use in Karate.
Thanks in Advances
def jsonValidate = {name: '#integer',Name: '#present'}
so if i use Present here ,it means Name can be null or can have value of any data type. but i need to check Name can be either String or Null Value only

Read the docs, and try this: https://github.com/intuit/karate#optional-fields
* def jsonValidate = { id: '#number', name: '##string' }

Related

SQLSTATE[22007]: Invalid datetime forma

I try to save some data that it brings me from my view, which is a table, but I don't know why it throws me that error with the insert.
result of insert
this is my view:
table of view
this is my controller:
$checked_array = $_POST['id_version'];
foreach ($request['id_version'] as $key => $value) {
if (in_array($request['id_version'][$key], $checked_array))
{
$soft_instal = new Software_instalacion;
$soft_instal->id_instalacion = $instalaciones->id;
$soft_instal->id_historial = $historial->id;
$soft_instal->id_usuario = $request->id_usuario;
$soft_instal->id_version = $_POST['id_version'][$key];
$soft_instal->obs_software = $_POST['obs_software'][$key];
$soft_instal->id_tipo_venta = $_POST['id_tipo_venta'][$key];
$soft_instal->save();
}
}
id_tipo_venta seems to be an empty string which is apparently not valid.
You can try debugging what you get in :
var_dump($_POST['id_tipo_venta'][$key]);
die;
Your database field expects to receive an integer. Therefore, using the intval() function can solve your problem.
Indeed, I think your code returns an alphanumeric string.
Therefore, the code below will return 0 in all cases if no version is returned (not set, string or simply null):
$soft_instal->id_tipo_venta = intval($_POST['id_tipo_venta'][$key]);
On the other hand, intval() will always convert to int, so a decimal will be converted, example :
intval("1.1") // returns 1
intval("v1.1") // returns 0
If this is not the desired behavior, maybe you should think about changing your database type.
EDIT :
Of course, you can also set the value as null if you prefer to 0. You must allow nullable values in your database.
id_tipo_venta can not be empty, try with some number or change type column to varchar in the database

Limesurvey get combo values of a question

When I perform an export_responses call to the API, I get the questions and values.
For combo type questions, I get the ID of the selected option, but not the description.
How can I access the descriptions of these values?
Thank you in advance!
The parameter sResponseType in the API allows you to choose if you want to get the Answer Codes or the Answer Texts.
Please see https://api.limesurvey.org/classes/remotecontrol_handle.html#method_export_responses
Export token response in a survey.
export_responses_by_token(string
$sSessionKey, integer $iSurveyID, string $sDocumentType, string
$sToken, string $sLanguageCode = null, string $sCompletionStatus =
'all', string $sHeadingType = 'code', string $sResponseType = 'short',
array $aFields = null) : array|string
...
...
sResponseType (optional)'short' or 'long' Optional defaults to 'short'

Where md5 column Laravel 5.4

Please i try to get row where the md5 of column equal to MD5 value:
This is my code
public function xxxx($id_md5){
$x = Model::where(DB::raw("MD5('id')"),$id_md5)->first();
}
Always object is null, Any help please,
Thanks.
When you do DB::raw("MD5('id')"), your database doesn't check the md5 value of the id column - instead, it checks the md5 value of the string id. Remove the quote and it'll work.
Tinker example from a db I had open:
>>> App\User::where(DB::raw('md5("id")'), md5('1'))->first();
=> null
>>> App\User::where(DB::raw('md5(id)'), md5('1'))->first();
=> App\User {#867
id: 1,
username: "testuser1",
}

NSJSONSerialization.JSONObjectWithData changes field type

I'm getting the following JSON response from the server:
{
"userId":"123456789",
"displayName":"display name"
}
When I use NSJSONSerialization.JSONObjectWithData and then prints the result NSDictionary I see in the console the following:
userId = 123456789
displayName = "display name"
Why do JSONObjectWithData changes the userId field type from String to a number?
It doesn't. The JSON deserialisation respects the data type and will maintain it. You can't tell the data type from a simple description log, you need to actually interrogate the class. The description log will quote some things if it makes more sense for the human reader, like spaces in the description, but it also omits quotes in some cases.
It doesn't.
Don't infer a variable type from its log representation, just test. Fire a Playground with this, for example:
let str = "{\"userId\":\"123456789\",\"displayName\":\"display name\"}"
if let data = str.dataUsingEncoding(NSUTF8StringEncoding),
jsonResult = try? NSJSONSerialization.JSONObjectWithData(data, options: []),
jsonObject = jsonResult as? [String:String],
id = jsonObject["userId"] {
print("User ID is " + id)
}

How to convert objectid to string

I want to get the string character from an ObjectId object. I use pymongo.
eg: ObjectId("543b591d91b9e510a06a42e2"), I want to get "543b591d91b9e510a06a42e2".
I see the doc, It says ObjectId.toString(), ObjectId.valueOf().
So I make this code: from bson.objectid import ObjectId.
But when I use ObjectId.valueOf(), It shows:
'ObjectId' object has no attribute 'valueOf'.
How can I get it? Thanks.
ObjectId.toString() and ObjectId.valueOf() are in Mongo JavaScript API.
In Python API (with PyMongo) proper way is to use pythonic str(object_id) as you suggested in comment, see documentation on ObjectId.
ObjectId.toString() returns the string representation of the ObjectId() object.
In pymongo str(o) get a hex encoded version of ObjectId o.
Check this link.
What works for me is to "sanitize" the output so Pydantic doesn't get indigestion from an _id that is of type ObjectId...here's what works for me...
I'm converting _id to a string before returning the output...
# Get One
#router.get("/{id}")
def get_one(id):
query = {"_id": ObjectId(id)}
resp = db.my_collection.find_one(query)
if resp:
resp['_id'] = str(resp['_id'])
return resp
else:
raise HTTPException(status_code=404, detail=f"Unable to retrieve record")
Use str(ObjectId), as already mentined in the comment by #Simon.
#app.route("/api/employee", methods=['POST'])
def create_employee():
json = request.get_json()
result = employee.insert_employee(json)
return { "id": str(result.inserted_id) }
This is an old thread, but as the existing answers didn't help me:
Having run
new_object = collection.insert_one(doc)
I was able to get the ObjectID with the inserted_id property:
print(f"{new_object.inserted_id}")
In python (Pymongo) there's no inbuilt method to do it so iterate over the result you fetched from db and then typecast _id to str(_id)
result = collection.find({query})
for docs in result:
docs[_id] = str(docs[_id])
first you have to assign the Object Id value to a variable
for example:
let objectId = ObjectId("543b591d91b9e510a06a42e2");
then use the toString method like this
let id = objectId.toString();