def test_import_no_files(self): """Test the import when files are not found.""" current_dir = os.getcwd() path = current_dir + r"\data_files" clear_db() import_data(path, "cust_data.csv", "prod_data.csv", "rent_data.csv") self.assertRaises(FileNotFoundError)
def get(self): "Initialize database similar to in vserver" # Dangerous: do not use in production action = self.get_argument("action", None) if not self.application.debug: if not self.is_admin() or action != "dump": self.json_error(403, "Debug mode is off") if action == "clear": clear_db(self.db, self.application.storage_path) self.json_success("done") elif action == "init": init_db(self.db, self.application.storage_path) self.json_success("done") elif action == "dump": result = dump_db(self.db) if self.get_argument("human-readable", "false") != "true": self.json_success(**result) ans = [] for key, value in result.items(): thead = list(value[0]) tbody = [] for line in value: tbody.append(list(map(line.__getitem__, thead))) ans.append( { "header": key, "thead": thead, "tbody": tbody, } ) self.render("dump.html", tables=ans) else: self.json_error(400, "action should be clear, init, or dump")
def refresh_members(): if request.method == 'GET': database.clear_db("members") uids = ast.literal_eval( urllib.request.urlopen(site_base + "/api.php?api=" + api_key + "&request=list_member_uid").read().decode( 'utf-8').rstrip('\n')) if __debug__: print("UIDs: %s" % uids) for uid in uids: print("URL: %s" % site_base + "/api.php?api=" + api_key + "&request=member&id=" + uid) member = json.loads( urllib.request.urlopen(site_base + "/api.php?api=" + api_key + "&request=member&id=" + uid).read().decode('utf-8')) member['new'] = 'no' database.add_member(member) urllib.request.urlretrieve( site_base + "/api.php?api=" + api_key + "&request=mug_shot&id=" + uid, "static/members/" + uid + ".jpg") socketio.emit('my_response', {'data': '**ADMIN** Members list refreshed'}, namespace='/comms') return "Ok"
def test_show_rentals(self): """Tests a database query to return a dictionary of customers who have rented a certain product""" current_dir = os.getcwd() path = current_dir + r"\data_files" clear_db() import_data(path, "customer_data.csv", "product_data.csv", "rental_data.csv") expected_dict2 = { "1001": { "address": "35 Kentucky Rd", "email_address": "*****@*****.**", "name": "Jim Beam", "phone_number": "111-222-3333" }, "1004": { "address": "66934 Redmond Way", "email_address": "*****@*****.**", "name": "Harry Henderson", "phone_number": "444-555-6666" } } renters_test = show_rentals("2002") self.assertEqual(renters_test, expected_dict2)
def get(self): 'Initialize database similar to in vserver' # Dangerous: do not use in production action = self.get_argument('action', None) if not self.application.debug: if not self.is_admin() or action != 'dump': self.json_error(403, 'Debug mode is off') if action == 'clear': clear_db(self.db, self.application.storage_path) self.json_success('done') elif action == 'init': init_db(self.db, self.application.storage_path) self.json_success('done') elif action == 'dump': result = dump_db(self.db) if self.get_argument('human-readable', 'false') != 'true': self.json_success(**result) ans = [] for key, value in result.items(): thead = list(value[0]) tbody = [] for line in value: tbody.append(list(map(line.__getitem__, thead))) ans.append( {'header': key, 'thead': thead, 'tbody': tbody,} ) self.render('dump.html', tables=ans) else: self.json_error(400, 'action should be clear, init, or dump')
def test_import_bad_data(self): """Test the import of bad or incomplete data.""" current_dir = os.getcwd() path = current_dir + r"\data_files" clear_db() import_data(path, "bad_cust_data.csv", "bad_prod_data.csv", "bad_rent_data.csv") self.assertRaises(NameError)
def test_import_data(self): """Tests importing of data from csv files""" current_dir = os.getcwd() path = current_dir + r"\data_files" clear_db() import_test = import_data(path, "customer_data.csv", "product_data.csv", "rental_data.csv") self.assertEqual(list(import_test), [(8, 5, 11), (0, 0, 0)])
def clear_db(): if request.method == 'GET': database.clear_db("all") socketio.emit('my_response', {'data': '**ADMIN** Database cleared'}, namespace='/comms') socketio.emit('reload_results', {'data': 'reload results'}, namespace='/comms') return "Ok"
async def purgedb(self, ctx): """Destroys the database.""" await ctx.send("Removing the content and structure of the database...") clear_db() await ctx.send("Killing bot... Please reset to reinitialize DB") await self.bot.close() exit(1)
def test_import_data(self): """Test importing data""" db.clear_db() counts, errors = db.import_data( '/Users/Tian/Documents/PythonClass/Tianx/SP_Python220B_2019' '/students/Tianx/Lesson5/', 'product.csv', 'customers.csv', 'rental.csv') self.assertEqual(counts, (3, 10, 9)) self.assertEqual(errors, (0, 0, 0))
def test_show_available_products(self): """Tests a database query to return a dictionary of products that have a quantity listed as greater than zero""" current_dir = os.getcwd() path = current_dir + r"\data_files" clear_db() import_data(path, "customer_data.csv", "product_data.csv", "rental_data.csv") expected_dict1 = { "2001": { "description": "stereo", "number_available": "6", "type": "electronics" }, "2002": { "description": "television", "number_available": "4", "type": "electronics" }, "2003": { "description": "microwave", "number_available": "2", "type": "appliance" }, "2004": { "description": "painting", "number_available": "11", "type": "decoration" }, "2005": { "description": "table_lamp", "number_available": "7", "type": "electronics" }, "2006": { "description": "end_table", "number_available": "3", "type": "furniture" }, "2007": { "description": "couch", "number_available": "1", "type": "furniture" } } available_test = show_available_products() self.assertEqual(available_test, expected_dict1)
def remove_incomplete_users(session): users = session.query(User).all() for user in users: if (user.wc_id is None) or (user.fb_token is None) or (user.wc_token is None): clear_db(user.username)
""" This file is a quick way to reset the DB after an update Its not really intended for anyone other then our QA tester in case his bot fails to start due to a DB issue """ from time import sleep from database import clear_db print( "WARNING THIS WILL REMOVE ALL ENTRIES FROM THE DATABASE; ARE YOU SURE YOU WANT TO CONTINUE(y/n)" ) if input() == "y": print("Clearing DB") clear_db() print("Database cleared. Please start your bot") sleep(5)
if __name__ == "__main__": ''' args. Opt 1: dashboard.py -m username metaphor ''' session = get_session() if len(sys.argv) > 1: if sys.argv[1] == "-m": #CHANGE METAPHOR for USER name = sys.argv[2] metaphor = sys.argv[3] change_metaphor(name, metaphor, session) elif sys.argv[1] == "-d": # DELETE USER FROM DATABASE name = sys.argv[2] clear_db(name, session) elif sys.argv[1] == "-l": name = sys.argv[2] step_count = int(sys.argv[3]) user = session.query(User).filter_by(username=name).first() change_steps(user, step_count, session) #get_dashboard_state(user) else: users = session.query(User).all() for user in users: events = get_events_for_user(user, session) print("{}'s metaphor: {}".format(user.username, user.metaphor)) for ev in events: act = ev.activity print("{} weight:{}, completed: {}".format( act.name, act.weight, ev.completed))
async def do_clear_db(): log.info('Clearing DB...') clear_db() return {'status': 'ok'}
def tearDown(self): clear_db()
def _clear_db(): db_session.rollback() clear_db()
''' Created on 6.5.2012 @author: teerytko ''' from userapp import create_userapp from database import clear_db if __name__ == "__main__": app = create_userapp('settings.DefaultConfig') print "Cleaning database %r" % app.config['DATABASE_ENGINE'] clear_db(app)
def setUp(self): database.clear_db()