In my test I want multiple users to be created and the last one logged in.
So here is my code:
test "add_answer to ad" do
user = newuser
text = "mytext mytext mytext mytext mytext mytext mytext"
post :savenew, cityId: City.last.id, text: text , maxPrice: "1", subscribe: false
$stdout.puts "#{assigns(:current_user)} CURUSER"
#ad = assigns(:ad)
user = newuser(0, 'new2#new.com')
post :add_answer, id: #ad.id, text: text
$stdout.puts "#{assigns(:current_user)} CURFIRM"
assert_equal "Ответ успешно добавлен.", flash[:success]
user.destroy
end
How I create new users:
def newuser(rank = 2, email = 'new#new.com')
user = User.new
user.password = '123456'
user.newpassword = true
user.email = email
user.contact = 'new_user'
case rank
when 0
user.urank = URank.firm.id
when 1
user.urank = URank.admin.id
when 2
user.urank = URank.user.id
end
user.save
$stdout.puts "#{user} NEW"
this_controller = #controller
#controller = MainController.new
get :logout
post :login, email: email, pass: '123456'
#controller = this_controller
return user
end
And my logout:
if cookies[:id]
Rails.cache.delete(cookies.signed[:id][0])
cookies.delete(:id)
end
#current_user = nil
(There is no cache it Test)
So as a result when I create new users I can see this:
As you can see the first user is just another user and second == first. What is happening there and how can I fix this?
Thank you!
I don't know why, but the problem was
#current_user ||= User.auth_with_salt(*cookiesId)
In test just do
#current_user = User.auth_with_salt(*cookiesId)
Related
I have a code which the bot needed to read the both reactions of the user on a message but with this code, the bot doesn't print the "second check" which is meant by like bot not reading the second reaction and stopping after the first one come true
reacttn = True
def check(reaction, user):
return user == members.users[members.leader].user and reaction.message.id == ttreact.id
while reacttn == True:
reaction, user = await client.wait_for("reaction_add", check=check)
if len(members.users) == 2:
if str(reaction.emoji) == "1️⃣":
print("first check")
if str(reaction.emoji) == "2️⃣":
print("second check")
await asyncio.sleep(5)
reacttn = False
You can do something like this:
from collections.abc import Sequence
def sequence(seq):
if seq is None:
return ()
if isinstance(seq, Sequence) and not isninstance(seq, str):
return seq
else:
return(seq,)
def reaction_check:(message=None, emoji=None, author=None, ignore_bot=True):
message = sequence(message)
message = tuple(m.id for m in message)
emoji = sequence(emoji)
author = sequence(author)
def check(reaction, user):
if ignore_bot and user.bot:
return False
if message and reaction.message.id not in message:
return False
if emoji and reaction.emoji not in emoji:
return False
if author and user not in author:
return False
return True
return check
In the command:
msg = await ctx.send("react to this message!")
await msg.add_reaction("1️⃣")
await msg.add_reaction("2️⃣")
check = reaction_check(message=msg, author=member, emoji=("1️⃣","2️⃣"))
reaction, user = await client.wait_for("reaction_add", check=check)
if reaction.emoji == "1️⃣":
#first logic
if reaction.emoji == "2️⃣":
#second logic
I am using fetch on the frontend to send data to my flask backend in order to make a movie seat booking. The whole process works fine until the client awaits the response, which is "undefined" . So , basically the database saves the data , the only problem is the response which is sent to the client. I used jsonify which usually works fine. Can anybody tell me what I am missing? Thanks in advance.
Here is the JS code :
function sendReservationToServer() {
const selectedSeats = sessionStorage.getItem('selectedSeats')
const reservation = { userId, selectedSeats, showTimeId, movieHallId }
fetch('/bookSeats', {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(reservation)
}).then(response => {
response.json()
}).then(data => {
theatreHall.innerHTML = `${data} <br> <a href='/home'>Back to main menu</a>`
console.log(`${data}`)
}).catch(err => infoMsg.textContent = err)
sessionStorage.clear()
}
And this is the flask controller which handles the request:
#app.route("/bookSeats", methods=["POST"])
def book_seats():
selected_seats = request.json
user_id = selected_seats.get('userId')
seats = json.loads(selected_seats.get('selectedSeats'))
movie_hall_id = selected_seats.get('movieHallId')
seat_ids = []
showtime_id = selected_seats.get('showTimeId')
for seat in seats:
seat_ids.append(db.session.query(Seat).filter(
Seat.seat_number == seat).filter(Seat.movie_hall_id == movie_hall_id).all()[0].stid)
for seat in seat_ids:
reserved_seat = ReservedSeat(
seat_id=seat, show_time=showtime_id, user=user_id)
db.session.add(reserved_seat)
db.session.commit()
reservation = Reservation(
user=user_id, show_time=showtime_id, number_of_tickets=len(seat_ids))
db.session.add(reservation)
db.session.commit()
message = f'{seats} booked successfully'
return jsonify(message)
data is undefined because the first then does not return anything. Either make it return response.json() or move everything in the second then to the first and replace data with response.json().
I am using auto submit in my forms.
Form gets automatically submitted when 10 digits are entered in the number field. This actually comes from USB RFID card reader upon scannig the card (It works as keyboard emulator).
I compare the number with the existing numbers in the database and then identify the user and perform some database transactions.
What happens is that the card reader reads the number multiple times, and due to that before all the database transactions complete for that input, another input is accepted (same number) within 1s and the consistency is lost before the first transaction is fully completed.
Kindly advise.
VIEWS.PY File:
#login_required
def markattdview(request):
# for val in studmst.objects.filter(ccownerid=request.user.id)
# TO DOooo
# select studid from attddetail where studentID= (select student ID from studmst where ccownerid = currentuser.ID)
# lastattd=attddetail.objects.filter()
# Showing last 10 users whose attendance have been marked by the logged in user
#
form_attd = markattdform()
attdsuccess = ""
identified_user = ""
identified_studname=""
loggedin_userid=request.user.id
loggedinuser=request.user.username
print("Logged in User : " + loggedinuser)
if request.method == 'POST':
studmstobj = studentmaster()
attdform = markattdform(request.POST)
unknown_cardno = request.POST.get('cardno')
if attdform.is_valid():
# form_attd.punchtime = datetime.datetime.now()
# attdform.save(commit=True)
obj = attdform.save(commit=False)
obj.punchtime = datetime.datetime.now()
attdsuccess = "Card not assigned. Kindly verify if the card has been registered."
#studlist = studmst.objects.filter(ccownerid = request.user.id)
#print (studlist[0])
# for usr in studlist(cardnumber = obj.cardno):
# Identifying the user who swyped the card
for usr in studentmaster.objects.filter(cardnumber = obj.cardno):
#WORKING FINE AFTER REMOVING WORKER AND REDISTOGO
#saving the details for identified User
identified_studname= usr.studentname
identified_cardno=usr.cardnumber
identified_studid = usr.studentid
punchdatetime=obj.punchtime
obj.studentname=identified_studname
obj.studentid_id=identified_studid
print('User Identified for card number '+ identified_cardno)
print( "Identified user - " + identified_studname)
databasetransactions(identified_studid,identified_studname,punchdatetime)
JAVASCRIPT FOR AUTO FORM SUBMISSION:
$(function () {
console.log(thetext);
$('#thetext').bind('change keyup', function () {
if ($(this).val().length >= 10) {
$('#Form').submit();
}
})
});
I would add two variables: formSubmitted and previousInput. And every time the length of the text is > 10, I would check if the form was submitted and also if previous input is equal to the current input.
When you submit the form - you set the value of formSubmitted to true.
And in this case your form will be submitted if it wasn't submitted already, or if the previous input is different than the current one which means that another text was entered and it should also be submitted.
And finally on ajax success or error you set the formSubmited to false back to allow new form submitions.
Remember that your form will be also submited if the current input is different than the previous input!
$(function () {
var formSubmitted = false;
var previousInput = null;
$('#thetext').bind('change keyup', function () {
if ($(this).val().length >= 10 && (!formSubmitted || previousInput != $(this).val())) {
var formData = new FormData($('#Form')[0]);
previousInput = $(this).val();
formSubmitted = true;
$.ajax(
url: '/endpoint.php',
method: 'POST',
processData: false,
contentType: false,
data: formData,
success: function(data, status, xhr) {
formSubmitted = false;
},
error: function(data, status, xhr) {
formSubmitted = false;
}
});
}
})
});
I am trying to save a user id to a new biz. I keep getting a 400 error and can not figure out why. I am using django for the backend with graphql and apollo client for the front with vue js. I am able to get the owner id but not able to save it for some reason.
Create Biz Mutation Apollo
export const CREATE_BIZ_MUTATION = gql`
mutation CreateBizMutation($name: String!, $owner: ID!) {
createBiz(name: $name, ownerId: $owner) {
name
}
}`
Create Biz mutation Django
class CreateBiz(graphene.Mutation):
id = graphene.Int()
name = graphene.String()
code = graphene.String()
owner = graphene.Field(UserType)
class Arguments:
name = graphene.String()
def mutate(self, info, name):
user = get_user(info) or None
code = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for _ in range(6))
biz = Biz(
code = code,
name = name,
owner = user
)
biz.save()
return CreateBiz(
id= biz.id,
name = biz.name,
code = biz.code,
owner = biz.owner
)
Create Biz Component
createBiz () {
const owner = localStorage.getItem(DJANGO_USER_ID)
if (!owner) {
console.error('No user logged in')
return
}
const { name } = this.$data
this.$apollo.mutate({
mutation: CREATE_BIZ_MUTATION,
variables: {
name,
owner
}
}).catch((error) => {
console.log(error)
})
}
}
Presently trying to test a Grails service (Experience with Geb functional testing)
Trying to mock the necessary required data that the service will need (e.g. User,etc.) ... no matter how I seem to declare/initialize the domains of interest they all appear as NULL in all my tests methods
I'm trying to set this required information once, so it can be reused through the test methods.
#TestFor(ReminderService)
#Mock([Reminder, User, Subscriptions, Organisation, UserOrganisation, OrganisationRole, Ref, Role, Title])
class ReminderServiceTests extends Specification {
#Shared user, org, userOrg, roleUser, sub, orgRole, ti, refVals, reminder
def mailService
def setup() {
def refSubStatus = new Ref(value: 'Current').save()
def refSubPublic = new Ref(value: 'No').save()
def refSubType = new Ref(value: 'Subscription Taken').save()
def refRemUnit = new Ref(value: 'Month').save()
def refOrgRole = new Ref(value: 'Subscriber').save()
def refRemMethod = new Ref(value: 'email').save()
def refRemTrigger = new Ref(value: 'Subscription Manual Renewal Date').save()
reminder = new Reminder(user: user, active: true, amount: 1, unit:refRemUnit, reminderMethod:refRemMethod, trigger: refRemTrigger, lastRan:null).save()
refVals = [refSubStatus,refSubPublic, refSubType, refRemUnit, refOrgRole, refRemMethod, refRemTrigger]
roleUser = new Role(authority: 'BASIC_USER', roleType:'global').save()
ti = new Title(title: "A random title....", impId: UUID.randomUUID().toString()).save()
sub = new Subscription(name:"A random subscription name",
status:refSubStatus,
identifier:UUID.randomUUID().toString(),
impId:UUID.randomUUID().toString(),
startDate:new LocalDate().minusYears(1).toDate(),
endDate: new LocalDate().plusMonths(1).toDate(),
isPublic: refSubPublic,
type: refSubType,
renewal: new LocalDate().minusMonths(3).toDate()).save()
org = new Organisation(name: "new org", impId: UUID.randomUUID().toString()).save()
orgRole = new OrganisationRole(sub: sub, roleType: refOrgRole, org: org).save()
user = new User(username: 'j_doe', firstname: "John", lastname: "Doe", email: 'example#googlemail.com', defaultDash: org).save()
userOrg = new UserOrganisation(org: org, user: user, formalRole: roleUser, status: 1).save()
mailService = new MailService()
// mockDomain(Ref, refdataValues)
// mockDomain(Title, ti)
// mockDomain(OrganisationRole, orgRole)
// mockDomain(Organisation, org)
// mockDomain(User, user)
// mockDomain(UserOrganisation, userOrg)
// mockDomain(Reminder, reminder)
}
def "Getting subscriptions for a user"() {
when:
def subscriptions = service.getAuthorisedSubsciptionsByUser(user)
then:
subscriptions != null
subscriptions.size() > 0
}
Everything is null, I've tried using mockDomain (See commented out section in setup(), including using setupSpec() something is not quite right)
Have you tried not using #Shared? AS I see it now, you don't need it. Your references are shared throughout the lifecycle of the Spec, but you put your init code in setup, which is called before each spec. That does not seem right. #Shared variables are internally stored in a different instance than the normal variables, so there may be some kind of mixup. Also, you might try to use setupSpec() instead of setup() for #Shared variables.
#TestFor(SomeService)
#Mock([DomainClass])
class SomeServiceSpec extends Specification {
def "test someMethod"() {
given:
def x = new DomainClass(attr1: 'a', attr2: 'b').save(flush: true)
when:
def result = service.someMethod() // returns that saved Domain instance
then:
result instanceof DomainClass
result.attr1 == 'a'
result.attr2 == 'b'
}
}
.save() has proven insufficient in my unit tests, while .save(flush: true) produces the desired results.