How i can fix this strange bug in my unit tests? - python

I was trying to create some unit test for my tweeter editor and i had a problem when i run the code. My unit test is this so far:
%%file test_twitter.py
import unittest
class TestTwitterEditor(unittest.TestCase):
"""Populate catalog"""
def setUp(self):
self.tweet[1] = tweet('Business Tax Accountant openings','Thu Sep 13 01:30:23 +0000 2012')
self.tweet[2] = tweet('Watching #XFactor USA beat show ever !!!', 'Thu Sep 13 0:30:23 +0000 2012')
self.tweet[3] = tweet('Random3', 'Thu Sep 18 5:30:23 +0000 2012')
self.tweet[4] = tweet('Random4', 'Thu Sep 17 5:30:23 +0000 2012')
self.tweet[5] = tweet('Random5', 'Thu Sep 18 7:30:23 +0000 2012')
def tearDown(self):
pass
def test_delete_tweet(self):
self.assertNotEqual(self.delete_tweet(0,0,0,5),'Random5')
def print_current_tweet(self):
self.assertEqual(self.print_current_tweet(tweet[5] , 0, 5),print(f"The current tweet is the number {tweet[5]} : \"{tweet[5]}\" Made at {tweet[5]}") )
if __name__ == '__main__':
unittest.main()
My delete_tweet function is this:
def delete_tweet(temp , temps , del_tweets , TOTAL_TWEET):
"""This function receives as input two temp.variables,a variable callled del_tweets"""
"""which will delete the current Id,and the number of total tweets which will be used"""
"""to track properly the current Id which is going to be deleted."""
"""It returns the temp.variables,the deleted tweet and the num of total tweets. """
tweet_id = int(input("Enter the id of the tweet you want to delete: "))
if (tweet_id <= TOTAL_TWEET):
del_tweets.append(tweet_id)
elif (tweet_id <= TOTAL_TWEET + temp):
for i in range(tweet_id + 1 , temp , 1):
temps[i] = temps[i + 1]
return temp , temps , del_tweets , TOTAL_TWEET
And the "error" thaty i receive is this:
Ran 0 tests in 0.000s
OK
Where is the problem?
I don't understand why I receive this red message. If the assertNotEqual was wrong or non valid i should receive a message like:Error οr something similar.

Related

How To Run A Python Cron Job That Runs Manually But Not With CRON In Ubuntu 20.04?

I am trying to run a python cron script that will batch convert all video files inside a directory.
The python script is based on MoviePy and is working seamlessly when triggered manually.
But when triggered in Cron Job, its not running/working as estimated.
I have set a Shell Script inside which i have kept the Python script for any error crash handling.
I am calling the shell script from the cron.
Here are my codes:
Crontab -e:
# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').
#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h dom mon dow command
# * * * * * /usr/bin/python3 /var/www/html/cgi-bin/in.py /var/www/html/cgi-bin/log.txt
# * * * * * /bin/bash -c "/var/www/html/cgi-bin/cron.sh"
* * * * * cd /bin/bash /var/www/html/cgi-bin/cron.sh > /var/www/html/cgi-bin/log.txt 2> &1
Cron.sh is my Shell File that Cron will run.
#!/bin/sh
echo $(date) >> /var/www/html/cgi-bin/log.txt
/usr/bin/python3 /var/www/html/cgi-bin/in.py >> /var/www/html/cgi-bin/log.txt
Here is my Python File - In.py :
import moviepy.editor as mp
import sys, getopt
import requests
from datetime import datetime
from random import randint
import os, os.path, random
import shutil
rand_aud = str(randint(0, len(os.listdir('aud/'))))
inputfile = ''
keypass = ''
def main(argv):
inputfile = ''
keypass = ''
try:
opts, args = getopt.getopt(argv,"hi:k:",["ifile=","key="])
except getopt.GetoptError:
print ('in.py -i <inputfile> -k <user_key>')
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print ('in.py -i <inputfile> -k <user_key>')
sys.exit()
elif opt in ("-i", "--ifile"):
inputfile = arg
elif opt in ("-k", "--key"):
keypass = arg
# print(inputfile)
# print(keypass)
directory = r'in/'
for filename in os.listdir(directory):
inp = os.path.join(directory, filename)
#if inp == '':
# inp = 'in/f.mp4'
now = datetime.now()
value = randint(0, 10)
dt_stamp = now.strftime("%d%m%Y%H%M%S") + str(value)
out = 'out/' + keypass + '_' + dt_stamp + '.webm'
# aud = 'aud/' + rand_aud +'.WAV'
aud = 'aud/' + random.choice(os.listdir("aud/"))
print(out)
logu = 'logo.png'
video = mp.VideoFileClip(inp)
# if video.rotation == 90:
video = video.resize(video.size[::-1])
video.rotation = 0
logo = (mp.ImageClip(logu)
.set_duration(video.duration)
.resize(height=50) # if you need to resize...
.margin(right=8, top=8, opacity=0) # (optional) logo-border padding
.set_pos(("right","top")))
if aud != '':
audioclip = mp.AudioFileClip(aud).set_duration(video.duration)
new_audioclip = mp.CompositeAudioClip([audioclip])
video.audio = new_audioclip
final = mp.CompositeVideoClip([video, logo])
final.write_videofile(out)
if os.path.exists(inp):
os.remove(inp)
url = 'https://get-data.worlds.com.au?Auth=SSSOSXSQSSSXSQSXSOSSSOSS&Sender_key=' + keypass + '&handle=stream_response'
# print ('Posting Data To ' + url)
userdata = {"loc": out, "stamp": dt_stamp, "Auth": keypass, "handle": "stream"}
resp = requests.post(url)
# files = {'file': open(out, 'rb')}
# userdata = {"loc": out, "stamp": dt_stamp, "Auth": keypass, "handle": "stream"}
# resp = requests.post(url, files=files, params=userdata)
# r = requests.get(url, headers={"Auth":keypass, "handle":"stream"})
# print ('Call Response:')
# print (resp)
if __name__ == "__main__":
main(sys.argv[1:])
Here is the log.txt file. Please note that the MoviePy Done was the one i performed manually. Rest are CRON calls. The ones that have only time in them shows the cron job is running but the python script isnt :
Mon Apr 12 08:38:17 UTC 2021
out/_120420210838183.webm
Moviepy - Building video out/_120420210838183.webm.
MoviePy - Writing audio in _120420210838183TEMP_MPY_wvf_snd.ogg
MoviePy - Done.
Moviepy - Writing video out/_120420210838183.webm
Moviepy - Done !
Moviepy - video ready out/_120420210838183.webm
out/_120420210838374.webm
Moviepy - Building video out/_120420210838374.webm.
MoviePy - Writing audio in _120420210838374TEMP_MPY_wvf_snd.ogg
MoviePy - Done.
Moviepy - Writing video out/_120420210838374.webm
Moviepy - Done !
Moviepy - video ready out/_120420210838374.webm
Mon Apr 12 08:39:01 UTC 2021
Mon Apr 12 08:40:01 UTC 2021
Mon Apr 12 08:41:01 UTC 2021
Mon Apr 12 08:42:01 UTC 2021
Mon Apr 12 08:43:01 UTC 2021
Mon Apr 12 08:44:01 UTC 2021
Mon Apr 12 08:45:01 UTC 2021
Mon Apr 12 08:46:01 UTC 2021
Mon Apr 12 08:47:01 UTC 2021
Mon Apr 12 08:48:02 UTC 2021
Mon Apr 12 08:49:01 UTC 2021
Mon Apr 12 08:50:01 UTC 2021
Mon Apr 12 08:51:01 UTC 2021
Mon Apr 12 08:52:01 UTC 2021
Mon Apr 12 08:53:01 UTC 2021
Mon Apr 12 08:57:01 UTC 2021
Mon Apr 12 08:58:01 UTC 2021
Mon Apr 12 08:59:01 UTC 2021
Mon Apr 12 09:00:01 UTC 2021
Mon Apr 12 09:01:01 UTC 2021
Mon Apr 12 09:02:01 UTC 2021
Mon Apr 12 09:03:01 UTC 2021
Mon Apr 12 09:04:01 UTC 2021
Mon Apr 12 09:05:01 UTC 2021
Mon Apr 12 09:06:01 UTC 2021
Mon Apr 12 09:07:01 UTC 2021
Mon Apr 12 09:08:01 UTC 2021
Mon Apr 12 09:09:01 UTC 2021
Mon Apr 12 09:10:01 UTC 2021
Mon Apr 12 09:11:01 UTC 2021
Mon Apr 12 09:12:02 UTC 2021
Mon Apr 12 09:13:01 UTC 2021
Mon Apr 12 09:14:01 UTC 2021
Mon Apr 12 09:15:01 UTC 2021
Mon Apr 12 09:16:01 UTC 2021
Mon Apr 12 09:17:01 UTC 2021

I want to create a last clock filter pymongo

I'm making a website. I write the all data I get from the database as a list. I want to make a filter. I just want to get the data in the last hour.
#app.route('/task/list/birsaat', methods=['GET'])
def get_birsaat():
birsaat_tasks=tasks_collection.find({"zaman":"zaman.utcnow()-timedelta(hours=1)"})
task_list_birsaat = []
for rss_collection in birsaat_tasks:
task_list_birsaat.append({'baslik': rss_collection['baslik'],
'kisa_bilgi': rss_collection['kisa_bilgi'], 'link': rss_collection['link'],
'zaman': rss_collection['zaman'], 'saglayici': rss_collection['saglayici']})
response_birsaat = jsonify(task_list_birsaat)
response_birsaat.headers.add('Access-Control-Allow-Origin', '*')
return response_birsaat
zaman means time in turkish. my database datas
_id:5eff873b4f9b5e349c14bc91
baslik:"KKTC’ye gelen tüm yolculara 1 gün karantina şartı getirildi"
kisa_bilgi:"haberler"
zaman:"Fri, 03 Jul 2020 21:25:00 +0300"
saglayici:"sabah"
IF you want to find the last hour result until now, you should add $gte in your query, and if the zaman is string you should convert your target value to the format you saved, if you want to access the Fri, 03 Jul 2020 21:25:00 +0300 you can use this:
(zaman.utcnow()-timedelta(hours=1)).ctime())
the output is:
'Sat Jul 4 06:39:30 2020'
for adding the , to the above result you can use this:
dt = (zaman.utcnow()-timedelta(hours=1)).ctime())
spl = dt.split(' ')
res = spl[0] + ',' + ' ' + spl[3] + spl[2] + ' ' + spl[-1] + ' ' + spl[4] + ' ' + '+0300'
the result is:
'Sat, 4 2020 06:39:30 +0300'
then you should filter mongodb by this value.

Not sure why my python output is looping

I wrote a little bit of code to read a number in a file. Append it to a variable, then increment the number so the next time it runs the number in the file will be number +1. It looks like its working except it seems to increment twice.. For example here is my code :
11 def mcIPNumber():
12 with open('mcIPlatest.txt', 'r+') as file:
13 NameNumber= file.read().replace('\n','')
14 NameNumber=int(NameNumber)
15 NewNumber= NameNumber+1
16 print "newnumber = %s" % NewNumber
17 file.seek(0)
18 file.write(str(NewNumber))
19 file.truncate()
20 return NameNumber
21
22 def makeNameMCTag():
23 NameNumber = mcIPNumber()
24 NameTag = "varName" + str(NameNumber)
25 print "Name Tag: %s" % NameTag
26 mcGroup = "varTagmc"
27 #IPNumber = 1
28 mcIP = "172.16.0.%s" % NameNumber
29 print ( "Multicast Tag: %s, %s" % (mcGroup,mcIP))
30
31
32 mcIPNumber()
33 makeNameMCTag()
But here is my output.. notice that "NewNumber" gets printed out twice.. for some reason"
newnumber = 2
newnumber = 3
Name Tag: varName2
Multicast Tag: varTagmc, 172.16.0.2
So it correctly made my varName2 and my IP 172.16.0.2 (incremented my initial number in the file by 1) but this means the 2nd time I run it.. I get this:
newnumber = 4
newnumber = 5
Name Tag: varName
Multicast Tag: varTagmc, 172.16.0.4
My expected result is this:
newnumber = 3
Name Tag: varName3
Multicast Tag: varTagmc, 172.16.0.3
Any idea why its looping?
Thanks!
(by the way if you're curious I'm trying to write some code which will eventually write the tf file for my TerraForm lab)
Because of this:
def makeNameMCTag():
NameNumber = mcIPNumber()
You are calling mcIPNumber from inside makeNameMCTag, so you don't excplicitly need to call that method in line 32.
Alternatively
def make_name_mc_tag(name_number):
NameTag = "varName" + str(name_number)
print "Name Tag: %s" % NameTag
...
make_name_mc_tag(mcIPNumber())
here you are passing the required data as a parameter.

Difficulty with GCSE A453 Programming Task 3

Over the past few days, I have been attempting to code a solution to Task 3 of the A453 Computing section. Essentially, I am aiming to produce a program that takes data from members of a class that have participated in a maths quiz (that is situated over three text files, as the exam specification states that participants in the hypothetical quiz must be from a "Class 1" "Class 2", or "Class 3")and then sorts it, according to the user's input, in one of the two following ways:
In alphabetical order with each student's (in the appropriate class) highest score for the tests.
By the highest score achieved by each student in that class, from highest to lowest.
Here is the code that I have written up so far:
def highest_score_first():
names_with_scores_list = []
ScoresFirstList = []
AlreadySeenList = []
for line in file:
names_with_scores_list.append(line.strip())
for row in names_with_scores_list:
nameString = row[0: row.index(', ') ]
scoreString = row[row.index(', ')+2 : len(row)]
scoresFirstString = scoreString+","+nameString
#print(scoresFirstString)
ScoresFirstList.append(scoresFirstString)
ScoresFirstList.sort(reverse = True)
for row in ScoresFirstList:
nameString = row[row.index(',') : len(row)]
if nameString not in AlreadySeenList:
print(row)
AlreadySeenList.append(nameString)
def alphabetical():
names_with_scores_list = []
NamesFirstList = []
AlreadySeenList = []
for line in file:
names_with_scores_list.append(line.strip())
for row in names_with_scores_list:
nameString = row[0: row.index(', ') ]
scoreString = row[row.index(', ')+2 : len(row)]
NamesFirstString = nameString+","+scoreString
NamesFirstList.append(NamesFirstString)
NamesFirstList.sort()
for row in NamesFirstList:
nameString = row[0: row.index(',') ]
if nameString not in AlreadySeenList:
print (row)
AlreadySeenList.append(nameString)
# main code here
chosen_class = input("Which class would you like to view - one, two or three?")
if chosen_class == "one":
file = open("classonescore.txt","r")
elif chosen_class == "two":
file = open("classtwoscore.txt","r")
elif chosen_class == "three":
file = open("classthreescore.txt","r")
else:
print("Unfortunately, you have entered an invalid class name. ")
function = input("How would you like to sort the data - alphabetically or by highest score? Choose A or H")
if function.upper() == "H":
highest_score_first()
elif function.upper() == "A":
alphabetical()
Essentially, the problem with the code is that, when the user wants the data for a class to be sorted alphabetically (in terms of highest score), only the lowest score for each student, as well as his name, is generated.
For instance, whilst data from Class 1 is written into the text file as follows:
Chris, 08
Clive, 09
Will, 04
Harry, 10
Ahmed, 08
Geoff, 06
Amy, 04
Vennu, 10
Vennu, 07
Amy, 06
Ahmed, 09
Geoff, 04
Harry, 07
Will, 06
Clive, 10
Chris, 10
It is displayed upon running the program (when the user wants scores to be generated using "alphabetical") as:
Ahmed,08
Amy,04
Chris,08
Clive,09
Geoff,04
Harry,07
Vennu,07
Will,04
Ideally, it should be generated as follows:
Ahmed, 09
Amy, 06
Chris, 10
Clive, 10
Geoff, 06
Harry, 10
Vennu, 10
Will, 06
Unfortunately, I am unable to contact my teacher, so any reply would be greatly appreciated.
Many thanks,
Chris

Django + MySQL : Round Robin Update of Same Table Columns

My Model is sort of like
Spot
spot_1 = 1/0
spot_2 = 1/0
spot_3 = 1/0
spot_4 = 1/0
spot_5 = 1/0
spot_6 = 1/0
Sort of like Round Robin Database, assuming the spot_1 represents Current Month, spot_2 represents the previous month, and so on. So if current month is June, so
Jun = spot_1
May = spot_2
Apr = spot_3
Mar = spot_4
Feb = spot_5
Jan = spot_6
So at the End of the Month of June, and Begining of July, this would be represented as
July = spot_1
Jun = spot_2
May = spot_3
Apr = spot_4
Mar = spot_5
Feb = spot_6
So the Values should be carried forward as well. Currently I am looping through the complete QuerySet and making the values to Move Forward.
How can this be achieved with Single update() statement ?
Use the F expressions:
from django.db.models import F
Spot.objects.all().update(spot_2=F('spot_1'), spot_3=F('spot_2'), ...)

Categories

Resources