Django REST with pytest fixture integrity error - django-rest-framework

I am trying to create a fixture with pytest, but when I run it, I get the following error:
django.db.utils.IntegrityError: NOT NULL constraint failed: authtoken_token.user_id
I found information on it, but I am not sure how to handle it when it comes to fixtures.
My code:
#pytest.fixture
def client(db):
api_client = APIClient()
token = Token.objects.get_or_create(user__username='testuser')
api_client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)
return api_client
#pytest.mark.django_db
def test_get_list_test(client):
url = reverse('api/lists')
response = client.get(url)
assert response.status_code == 200

Generally speaking, i don't think your error related to pytest here.
I think the main issue here related to django db migrations look here
So first, Make sure you fix it, regardless to any framework (pytest)
django.db.utils.IntegrityError: NOT NULL constraint failed: authtoken_token.user_id
And after you have successfully validated that the error passed away (check manually also), try to run the fixture.

Related

MockMvc perform, array response assertion fail

I am implementing integration tests for Spring Boot. One of my endpoint gives back all the users, even the deleted ones. Here deleted means the deleted boolean attribute is set to true on AppUser Entity (~soft delete).
The endpoint works perfectly, I have manual tested with Postman (you can see below the response). The code:
#Test
void testGetAllAppUsers_whenAuthorizedOnlyActiveFalse_gotDeletedUser() throws Exception {
String token = jwtProvider.generateToken(TestUtils.ACCOUNT_MANAGER_USERNAME);
String url = "/api/account/user";
mvc.perform(get(url)
.header("Authorization", token)
.param("only-active", "false"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[*].deleted").value(Matchers.arrayContaining(true)));
}
the response:
...
Body = [{"id":7,"username":"ablabadmin#account.com","fullName":"Alpha Beta Lab Admin","deleted":false,"labsAsUser":[],"labsAsAdmin":[],"roles":[],"managedLabs":[]},{"id":11,"username":"ablabdeleteduser#account.com","fullName":"Alpha Beta Lab Deleted User","deleted":true,"labsAsUser":[],"labsAsAdmin":[],"roles":[],"managedLabs":[]},{"id":4,"username":"ablabman#account.com","fullName":"Alpha Beta Lab Manager","deleted":false,"labsAsUser":[],"labsAsAdmin":[],"roles":[],"managedLabs":[{"id":1,"key":"alab","name":"Alpha Lab","deleted":false,"createdAt":"2021-06-09","updatedAt":null,"labManagerUsernames":["alabman#account.com","ablabman#account.com"]},{"id":2,"key":"blab","name":"Beta Lab","deleted":false,"createdAt":"2021-06-09","updatedAt":null,"labManagerUsernames":["blabman#account.com","ablabman#account.com"]}]},{"id":10,"username":"ablabuser#account.com","fullName":"Alpha Beta Lab User","deleted":false,"labsAsUser":[],"labsAsAdmin":[],"roles":[],"managedLabs":[]},{"id":5,"username":"alabadmin#account.com","fullName":"Alpha Lab Admin","deleted":false,"labsAsUser":[],"labsAsAdmin":[],"roles":[],"managedLabs":[]},{"id":2,"username":"alabman#account.com","fullName":"Alpha Lab Manager","deleted":false,"labsAsUser":[],"labsAsAdmin":[],"roles":[],"managedLabs":[{"id":1,"key":"alab","name":"Alpha Lab","deleted":false,"createdAt":"2021-06-09","updatedAt":null,"labManagerUsernames":["alabman#account.com","ablabman#account.com"]}]},{"id":8,"username":"alabuser#account.com","fullName":"Alpha Lab User","deleted":false,"labsAsUser":[],"labsAsAdmin":[],"roles":[],"managedLabs":[]},{"id":1,"username":"aman#account.com","fullName":"Account Manager","deleted":false,"labsAsUser":[],"labsAsAdmin":[],"roles":[{"id":1,"role":"ACCOUNT_MANAGER"}],"managedLabs":[]},{"id":6,"username":"blabadmin#account.com","fullName":"Beta Lab Admin","deleted":false,"labsAsUser":[],"labsAsAdmin":[],"roles":[],"managedLabs":[]},{"id":3,"username":"blabman#account.com","fullName":"Beta Lab Manager","deleted":false,"labsAsUser":[],"labsAsAdmin":[],"roles":[],"managedLabs":[{"id":2,"key":"blab","name":"Beta Lab","deleted":false,"createdAt":"2021-06-09","updatedAt":null,"labManagerUsernames":["blabman#account.com","ablabman#account.com"]}]},{"id":9,"username":"blabuser#account.com","fullName":"Beta Lab User","deleted":false,"labsAsUser":[],"labsAsAdmin":[],"roles":[],"managedLabs":[]}]
Forwarded URL = null
Redirected URL = null
Cookies = []
java.lang.AssertionError: JSON path "$[*].deleted"
Expected: [<true>]
but: was a net.minidev.json.JSONArray (<[false,true,false,false,false,false,false,false,false,false,false]>)
Expected :[<true>]
Actual :a net.minidev.json.JSONArray (<[false,true,false,false,false,false,false,false,false,false,false]>)
...
I have tried out many other arguments: "true", false I have tried out contains method, and I ave tried out with "$[*].username" regex with an existing username, but every time I got AssertionError.
Can you please help me? There is definitely something I am missing. Also any advice is welcomed, since I am relatively new in Spring integration testing. Thanks in advance!
arrayContainingInAnyOrder(true,false) should work in this case.
But,
The test case would not have any value, even if it works with arrayContainingInAnyOrder(true,false).
As you can see, that [*].deleted returns value of deleted for all objects present in the response. The test must verify specific value.
For Example, If you are expecting that first user should have true then assert that $.[?(#.id ==1)].deleted is true.

MIP SDK fails to protect files

I'm using MIP file sample command line interface to apply labelling.
When trying to apply a label that has protection set, i got "Label requires ad-hoc protection, but protection has not yet been set" error.
Therefore, I tried protecting the file using "--protect" option and got the following error message:
"Something bad happened: The service didn't accept the auth token. Challenge:['Bearer resource="https://aadrm.com", realm="", authorization="https://login.windows.net/common/oauth2/authorize"'], CorrelationId=ce732e4a-249a-47ec-a7c2-04f4d68357da, CorrelationId.Description=ProtectionEngine, CorrelationId=6ff992dc-91b3-4610-a24d-d57e13902114, CorrelationId.Description=FileHandler"
This is my auth.py file:
def main(argv):
client_id = str(argv[0])
tenant_id = str(argv[1])
secret = str(argv[2])
authority = "https://login.microsoftonline.com/{}".format(tenant_id)
app = msal.ConfidentialClientApplication(client_id, authority=authority, client_credential=secret)
result = None
scope = ["https://psor.o365syncservice.com/.default"]
result = app.acquire_token_silent(scope, account=None)
if not result:
logging.info("No suitable token exists in cache. Let's get a new one from AAD.")
result = app.acquire_token_for_client(scopes=scope)
if "access_token" in result:
sys.stdout.write(result['access_token'])
else:
print(result.get("error"))
print(result.get("error_description"))
print(result.get("correlation_id")) # You may need this when reporting a bug
if __name__ == '__main__':
main(sys.argv[1:])
I tried to change the scope to ["https://aadrm.com/.default"] and then I was able to protect the file, but when I try getting the file status or try applying label on it I get the same error message with bad auth token.
These are the permissions as configured in azure portal:
Thank you
I think that scope you have is incorrect: https://psor.o365syncservice.com/.default
It should be https://syncservice.o365syncservice.com/.default.
A good way to handle this is to just append .default to whatever resource the AcquireToken() call gets in the resource param. Something like this.

Testrail API Ruby add_result_for_case error

I am executing the code below as a cucumber step. The test case id is
C70. I tried a run ID and it gave the same error.
The code and error are below -
-----------------
require 'testrail-ruby'
client = TestRail::APIClient.new('https://xxxx.testrail.net')
client.user = 'xxxxxxxxxx.com'
client.password = 'xxxxxx'
r = client.send_post(
'add_result_for_case/C270',
{ :status_id => 1, :comment => 'This test worked fine!' }
)
puts r
The Error:
TestRail API returned HTTP 400 ("Field :run_id is not a valid ID.")
What am I doing wrong? I have researched this topic and have not resolved it Please advise....
I found my problem . I should have used the full Test Case ID. The ID that found when running the actual test case . The issue is resloved.
Extra suggestion.
Do not use characters other than numbers when giving the ID information. For example, when giving the case Id, it shows up as C270 in Testrail. But you have to give it as 270 in Api. In another example, let your RunId be R150. You only need to give it as 150.

PG::ERROR: another command is already in progress

I have an importer which takes a list of emails and saves them into a postgres database. Here is a snippet of code within a tableless importer class:
query_temporary_table = "CREATE TEMPORARY TABLE subscriber_imports (email CHARACTER VARYING(255)) ON COMMIT DROP;"
query_copy = "COPY subscriber_imports(email) FROM STDIN WITH CSV;"
query_delete = "DELETE FROM subscriber_imports WHERE email IN (SELECT email FROM subscribers WHERE suppressed_at IS NOT NULL OR list_id = #{list.id}) RETURNING email;"
query_insert = "INSERT INTO subscribers(email, list_id, created_at, updated_at) SELECT email, #{list.id}, NOW(), NOW() FROM subscriber_imports RETURNING id;"
conn = ActiveRecord::Base.connection_pool.checkout
conn.transaction do
raw = conn.raw_connection
raw.exec(query_temporary_table)
raw.exec(query_copy)
CSV.read(csv.path, headers: true).each do |row|
raw.put_copy_data row['email']+"\n" unless row.nil?
end
raw.put_copy_end
while res = raw.get_result do; end # very important to do this after a copy
result_delete = raw.exec(query_delete)
result_insert = raw.exec(query_insert)
ActiveRecord::Base.connection_pool.checkin(conn)
{
deleted: result_delete.count,
inserted: result_insert.count,
updated: 0
}
end
The issue I am having is that when I try to upload I get an exception:
PG::ERROR: another command is already in progress: ROLLBACK
This is all done in one action, the only other queries I am making are user validation and I have a DB mutex preventing overlapping imports. This query worked fine up until my latest push which included updating my pg gem to 0.14.1 from 0.13.2 (along with other "unrelated" code).
The error initially started on our staging server, but I was then able to reproduce it locally and am out of ideas.
If I need to be more clear with my question, let me know.
Thanks
Found my own answer, and this might be useful if anyone finds the same issue when importing loads of data using "COPY"
An exception is being thrown within the CSV.read() block, and I do catch it, but I was not ending the process correctly.
begin
CSV.read(csv.path, headers: true).each do |row|
raw.put_copy_data row['email']+"\n" unless row.nil?
end
ensure
raw.put_copy_end
while res = raw.get_result do; end # very important to do this after a copy
end
This block ensures that the COPY command is completed. I also added this at the end to release the connection back into the pool, without disrupting the flow in the case of a successful import:
rescue
ActiveRecord::Base.connection_pool.checkin(conn)

MtGox Gem Failing to Login

I am trying to use the MtGox gem to cancel orders, however, I only get the following error message:
{"error":"Must be logged in"}
I am using the following code to make the call:
MtGox.configure {|c| c.key = user.mtgox_key; c.secret = user.mtgox_secret}
MtGox.cancel('oid'=>'a3c348d9-36c3-4927-b84d-206f421907f5', 'type'=>1)
I have also tried getting all of the open orders for a specific user using the following:
MtGox.post('/api/0/getOrders.php', {})
Alas, every call returns the same error message. Am I missing something?
This issue was resolved by using a smaller nonce for v1 api calls. Interestingly, a nonce of length 22 was causing subsequent v0 api calls to fail, but not subsequent v1 calls. I compute my nonce by simply using:
var nonce = ((new Date()).getTime()*1000).toString(); // microseconds since epoch

Resources