def createHabit(): req = request.get_json() h = Habit(req["title"]) habits.append(h.to_dict()) return h.to_dict(), 201
def test_01_new(self): habit = Habit("TestHabit", "For testing purposes", 2) self.assertIsInstance(habit, Habit) self.assertEqual(habit.name, "TestHabit") self.assertEqual(habit.description, "For testing purposes") self.assertEqual(habit.periodicity_id, 2) save_result = habit.save(0) self.assertTrue(save_result)
def addHabit(self): popup = Popup(self.window) popup.promptUser(True) self.window.wait_window(popup.window) if popup.isValid: name = popup.input.get() habit = Habit(name, 0, False, self.fr_list) self.habits.append(habit) habit.display()
def test_create_invalid_option_periodicity_missing(sample_habits): expected_name = sample_habits[0]["name"] expected_description = sample_habits[0]["description"] with pytest.raises(TypeError) as exc_info: Habit(name=expected_name, description=expected_description) expected_error_message = "__init__() missing 1 required positional argument: 'periodicity'" assert str(exc_info.value) == expected_error_message
def update_analytic_fields(): """ Updates all statistics columns in the habit table automatically. These values are required for and retrieved by the following methods. Returns ------- None. """ all_habits = db.get_all_habit_names() for name in all_habits: habit = Habit.load(name[0], 1) if habit is not None: query = """ UPDATE habit SET current_streak=?, longest_streak=?, latest_check_date=?, next_check_date=? WHERE name=? """ values = (habit.streak.current_streak, habit.streak.longest_streak, habit.streak.latest_check_date, habit.streak.next_check_date, name[0]) db.update(query, values) return None
def sample_habits_objects(): sample_data_file_name = os.path.join(DATA_DIR, "sample_data.json") if os.path.exists(sample_data_file_name): # Read json file with example data with open(sample_data_file_name, encoding="utf-8") as json_file: # Load json file containing example data sample_habits = json.load(json_file) # Create habit coming from json and save to habit database sample_habits_objects = list() for item in sample_habits["sample_data"]: habit = Habit(item["name"], item["description"], item["periodicity"]) for checkoff_date in item["checkoffs"]: habit.check_off(checkoff_date) sample_habits_objects.append((habit.id, habit)) return sample_habits_objects else: assert False, f"File {sample_data_file_name} doest not exist."
def parseList(text): title = "" d = False list = text.split("\n") for i in range(len(list)): d = False if(list[i].endswith('+')): title = list[i].replace("+","") d = True else: title = list[i] habits.append(Habit(title,d))
def new_habit(self, name, period, spec, tracked=False, creation_datetime=datetime.now(), tracking=None, longest_streak=0): """Method creates new habit and submits it to database.""" habit = Habit(name, period, spec, tracked, creation_datetime, tracking if tracking else [], longest_streak if longest_streak else 0) self.habits.append(habit) self.submit_to_db(habit, Database.name)
def test_create_valid_option_all_weekly(sample_habits): expected_name = sample_habits[-1]["name"] expected_description = sample_habits[-1]["description"] expected_periodicity = sample_habits[-1]["periodicity"] expected_created = datetime.now(timezone.utc).strftime("%Y-%m-%d") expected_checkoffs = [] actual = Habit(name=expected_name, description=expected_description, periodicity=expected_periodicity) assert actual.name == expected_name assert actual.description == expected_description assert actual.periodicity.name == expected_periodicity assert actual.checkoffs == expected_checkoffs assert str(actual.created[:10]) == str(expected_created)
def load(self): # update las closed date try: time_file = open('timelog.txt', 'r') self.lastClosed = time_file.readline() except FileNotFoundError: self.lastClosed = str(str(datetime.date(datetime.now()))) # get the saved habits try: data_lists = pickle.load(open('user_data.p', 'rb')) for data in data_lists: habit = Habit(data['name'], data['streak'], data['isComplete'], self.main_window) # if date has changed to some point in the future, revert the habit to incomplete state if self.lastClosed != self.openTime: if habit.isComplete.get(): habit.streak += 1 else: habit.streak = 0 habit.isComplete.set(False) self.habit_list.append(habit) except FileNotFoundError: self.habit_list = []
def test_04_delete(self): habit = Habit.load("TestHabit", True) habit.delete(True) habit_reload = Habit.load("TestHabit", True) self.assertIsNone(habit_reload)
def test_03_set_favorite(self): habit = Habit.load("TestHabit", True) habit.set_favorite() habit_reload = Habit.load("TestHabit", True) self.assertEqual(habit_reload.is_favorite, 1)
def test_02_load(self): habit = Habit.load("TestHabit") self.assertIsInstance(habit, Habit) self.assertEqual(habit.name, "TestHabit") self.assertEqual(habit.description, "For testing purposes") self.assertEqual(habit.periodicity_id, 2)
def habit_object(sample_habits): return Habit(name=sample_habits[0]["name"], description=sample_habits[0]["description"], periodicity=sample_habits[0]["periodicity"])
def main(args): """ The main function calls methods from the Habit class depending on the selection made by the user. Parameters ---------- args : object A populated namespace with attributes. Returns ------- None. """ # Each time the app is launched, the statistical values # for all Habits are updated. analytics.update_analytic_fields() if args.new: name = args.new habit = Habit.new(name) if habit is not None: habit.save(0) elif args.copy: name = args.copy habit = Habit.load(name) if habit is not None: habit.duplicate() elif args.edit: name = args.edit habit = Habit.load(name) if habit is not None: habit.edit() elif args.fav: name = args.fav habit = Habit.load(name) if habit is not None: habit.set_favorite() elif args.delete: name = args.delete habit = Habit.load(name) if habit is not None: habit.delete() elif args.show: name = args.show habit = Habit.load(name) if habit is not None: habit.get_summary() habit.streak.get_summary() elif args.check: name = args.check habit = Habit.load(name) if habit is not None: habit.streak.check() elif args.stats: choice = args.stats if choice == 1: print("\nUrgent habits that have to checked today at the latest") analytics.get_urgent_habits() elif choice == 2: print("\nThe longest streaks for all habits") analytics.get_longest_streak() elif choice == 3: print("\nAll active habits") analytics.get_active_habits() return None
from flask import Flask, jsonify, request from habit import Habit import json app = Flask(__name__) habits = [ Habit("1").to_dict(), Habit("2").to_dict(), Habit("3").to_dict(), ] @app.route("/habits") def getAll(): return jsonify(habits) @app.route("/habits", methods=["POST"]) def createHabit(): req = request.get_json() h = Habit(req["title"]) habits.append(h.to_dict()) return h.to_dict(), 201 @app.route("/habits/<int:habitID>", methods=["GET"]) def getOne(habitID):