As discussed in this answer, I have written code for checking a unique key violation:
if err, ok := err.(*pq.Error); ok {
if err.Code.Name() == "unique_violation" {
fail(w, http.StatusBadRequest, 0, "Item already exists")
return
}
}
For writing unit-testcases, I need to mock this error. I have written the mock for the error like this:
return pq.Error{Code: "unique_violation"}
But this does not matches with the code. How do I mock the pq.Error?
As noted in the Godoc, ErrorCode is a five-character error code. err.Code.Name() gets the human-friendly version of the error, but the error itself should be represented, and thus constructed, by the error code, which in this case is 23505.
Related
Just wondering, why with argo-workflow, as seen here:
https://github.com/argoproj/argo-workflows/blob/master/workflow/executor/executor.go#L783
func (we *WorkflowExecutor) reportResult(ctx context.Context, result wfv1.NodeResult) error {
if !result.Outputs.HasOutputs() && !result.Progress.IsValid() {
return nil
}
...
err := we.upsertTaskResult(ctx, result)
Why when there is output, the upsertTaskResult is not called?
(took me a while to debug "k8s API denied" error because a wrong serviceAccount, the dirty solution found by developers was to no more use "output" ....)
I have a block of try-exception code and I want to test if the block works properly? I wonder if there is a way to test this block with a unit test using pylint? This is the snipent I have:
class data_type(Enum):
SESSIONS = 0
RUNS = 1
def find_filter(data_type)
try:
if data_type.name == 'SESSIONS':
return {}
elif data_type.name == 'RUNS':
#Filter out rerun jobs
filter = {
"filter":{
"attName":"is_rerun",
"operand":"IN",
"#c":".InFilter",
"values":["FALSE"]
}
}
return filter
except AttributeError as erro:
loghandler.critical('Error in creating count query: {}'.format(erro))
I want to test if the data_type is not a valid enum member, the exception catches it before the execution goes to if statement. For example if:
find_filter('')
is called I like to see that the except AttributeError as erro captures the error and the error is logged.
Is there a way to do that?
PS: I know with pytest.raises() I can test if a raised error is really raised? But as far as I understand pytest.raises() does not work for testing the exception block of a try-exception case.
Any suggestion please?
Thanks.
I am trying to use verify method of mockito using scala as a language. However for my case verify method is always successful, even if that method is not being called.
Below is the codeline where getDetailsBySkus calls method getPriceAndAvailability just once internally. How can I make this work ?
Below is the code snippet.
Code:
doReturn(Future(TestConstantsSpec.PNA_RESPONSE), Nil: _*)
.when(distributorService).getPriceAndAvailability(ArgumentMatchers.any())(ArgumentMatchers.any())
"empty part number" should "not execute calls-1" in {
purchaseOrderService.getDetailsBySkus(purchaseOrder.distributor, Seq("KJH"))
.flatMap(output => {
verify(distributorService, Mockito.atLeast(10))
.getPriceAndAvailability(ArgumentMatchers.any())(ArgumentMatchers.any()) // successful
Future(output)
}
)
}
"empty part number" should "not execute calls-2" in {
purchaseOrderService.getDetailsBySkus(purchaseOrder.distributor, Seq("KJH"))
.flatMap(output => {
verify(distributorService, Mockito.atLeast(100))
.getPriceAndAvailability(ArgumentMatchers.any())(ArgumentMatchers.any()) // successful
Future(output)
}
)
}
Your test cases are not waiting for the completion of the Futures, if you are using ScalaTest or similar, here's where you can read up on your options: https://www.scalatest.org/user_guide/async_testing
I have two Actions with the same input/output/error types, and I'd like to compose them into a single Action that runs whichever of the two is enabled (with an arbitrary tie-breaker if they both are).
Here's my first, failing, attempt:
let addOrRemove: Action<MyInput, MyOutput, APIRequestError> = Action(enabledIf: add.isEnabled.or(remove.isEnabled)) { input in
if add.isEnabled.value {
return add.apply(input)
} else {
return remove.apply(input)
}
}
This fails because the inner add.apply(input) can't see that I checked add.isEnabled, so it wraps an additional ActionError<> layer around the error type. (This might be legit, as I'm not sure how thread-safe this approach would be, or might be a case of us knowing something the type system doesn't.) The corresponding type error is:
cannot convert return expression of type 'SignalProducer<MyOutput, ActionError<APIRequestError>>' to return type 'SignalProducer<MyOutput, APIRequestError>'
What should I do instead?
Github user #ikesyo provided the following answer on the ReactiveSwift issue I opened to ask the same question:
let producer: SignalProducer<MyOutput, ActionError<APIRequestError>>
if add.isEnabled.value {
producer = add.apply(input)
} else {
producer = remove.apply(input)
}
return producer.flatMapError { error in
switch error {
case .disabled: return .empty
case let .producerFailed(inner): return SignalProducer(error: inner)
}
}
If they show up here I'll happily change the accepted answer to theirs (credit where it belongs).
Warning: If I'm reading this answer correctly, it's not watertight. If add changes from enabled to disabled between the apply() and the start() of the wrapping Action, we'll get "success" (no values, but .completed) instead of the .disabled we should get. That's good enough for my use case, but YMMV.
I'm simply unable to retrieve the error code number when I get an error in postgres.
In the test of my program I know I'll get the following error
" pq: duplicate key value violates unique constraint "associations_pkey"".
Looking in the postgres docs this is most likely an pq error code of 23505.
I need to get that number in my Go program so that I can check on different types of errors and respond to the end user in a helpful way.
However, I can't seem to get hold of the error code in Go, only the error message. My code is as follows:
stmt, _ := DB.Prepare("INSERT INTO table (column_1) VALUES ($1)")
_, err = stmt.Exec("12324354")
if err != nil {
log.Println("Failed to stmt .Exec while trying to insert new association")
log.Println(err.Error())
fmt.Println(err.Code())
} else {
Render.JSON(w, 200, "New row was created succesfully")
}
You need to type assert the error to the type *pq.Error:
pqErr := err.(*pq.Error)
log.Println(pqErr.Code)
This is written in the documentation. As you see you can extract it in this way:
if err, ok := err.(*pq.Error); ok {
fmt.Println(err.Code)
}
Do not forget to remove the underscore from your import _ "github.com/lib/pq". As you see err has a lot of information about the error (not only Code but many others).
Notice that you can't compare it directly to some code (it is of ErrorCode type).
So you have to convert it to string and compare against a string.
https://godoc.org/github.com/lib/pq#Error