def test_donor_names(): donors = Donors() d1 = Donor("Mark", 50) d2 = Donor("Mary", 80) donors.add_donor(d1) donors.add_donor(d2) assert set(donors.names) == set(["Mark", "Mary"])
def from_file(cls, file_path): first_donor = None donor_list = [] with open(file_path, 'r') as text: end = text.tell() while True: some_str = text.readline() if text.tell() == end: break donor_init = ["", ""] name_or_hist = 0 gift = "" history = [] for param in some_str: if param == ';': name_or_hist = 1 continue donor_init[name_or_hist] += param for hist in donor_init[1]: if hist == ',': history.append(float(gift)) gift = "" continue gift += hist history.append(float(gift)) if first_donor is None: first_donor = Donor(donor_init[0], history) else: donor_list.append(Donor(donor_init[0], history)) end = text.tell() return cls(first_donor, *donor_list)
def from_db(cls, db_path): database = SqliteDatabase(db_path) donors = [] try: database.connect() database.execute_sql('PRAGMA foreign_keys = ON;') query = Donation.select().order_by(Donation.donor.asc()) d_name = '' d_hist = [] for info in query: if (d_name != info.donor): if d_name: donors.append(Donor(d_name, d_hist)) logger.info(d_name + ' ' + str(d_hist)) d_hist = [] d_name = info.donor d_hist.append(float(info.gift)) donors.append(Donor(d_name, d_hist)) except Exception as e: print(e) finally: database.close() return cls(*donors)
def test_charity_add_donor(): new_donor1 = Donor("Fred") new_donor1.add_donation(100) new_donor1.add_donation(1000) new_donor1.add_donation(10000) new_donor2 = Donor("Bob") new_donor2.add_donation(200) new_donor2.add_donation(2000) new_donor2.add_donation(20000) # Checks init() new_charity = Charity("Foundation") assert new_charity.charity_name == "Foundation" assert new_charity.donors_dict == {} # Checks add_donor() new_charity.add_donor(new_donor1.donor_name, new_donor1.donations_list) new_charity.add_donor(new_donor2.donor_name, new_donor2.donations_list) assert new_charity.donors_dict["Fred"].donor_name == "Fred" assert new_charity.donors_dict["Fred"].donations_list == new_donor1.donations_list assert new_charity.donors_dict["Bob"].donor_name == "Bob" assert new_charity.donors_dict["Bob"].donations_list == new_donor2.donations_list # Checks print_total_donations() assert new_charity.print_total_donations() == "Donor {} : Total amount is {}\nDonor {} : Total amount is {}\n"\ .format("Fred", 11100, "Bob", 22200)
def test_add_donation(): donors = Donors() donors.add_donation("Mark", 10) assert donors.get_donor("Mark") == Donor("Mark", 10) donors.add_donation("Mark", 20) assert donors.get_donor("Mark").donations == (10, 20) donors.add_donation("Mary", 30) assert donors.get_donor("Mary") == Donor("Mary", 30) assert set(donors.names) == set(["Mark", "Mary"])
def test_init(): """ Test initialization of donor objects """ d1 = Donor('Maggie') d2 = Donor('Doug', 1000) d3 = Donor() assert d1.name == 'Maggie' assert d2.name == 'Doug' assert 1000 in d2.donations assert d3.name == '' d3.name = 'Sam' assert d3.name == 'Sam'
def test_save_db_to_disk(): """ Tests that you can save the database to disk """ d1 = Donor('Maggie', 1000, 2000, 3000) d2 = Donor('Doug', 1111, 2222, 3333, 4444, 5555) d3 = Donor('キラ') db1 = db() db1.add_donor(d1) db1.add_donor(d2) db1.add_donor(d3) db1.save_db_to_disk('./test_db.pkl') assert os.path.isfile('./test_db.pkl') os.remove('./test_db.pkl')
def test_challenge(): donors = Donors() d1 = Donor("Mark", 50) d1.add_donation(90) d1.add_donation(110) d2 = Donor("Mary", 80) d2.add_donation(95) d2.add_donation(115) donors.add_donor(d1) donors.add_donor(d2) copy = donors.challenge(3, min_amt=85, max_amt=100) assert copy.get_donor("Mark").donations == (270, ) assert copy.get_donor("Mary").donations == (285, )
def test_donordb_repr(): """ Tests donordb __repr__ method """ d1 = Donor('Maggie', 1000, 2000, 3000) d2 = Donor('Doug', 1111, 2222, 3333, 4444, 5555) d3 = Donor('キラ', 9001) db1 = db() db1.add_donor(d1) db1.add_donor(d2) db1.add_donor(d3) string = f'{d1.name:>24} : {d1.donations}\n' string += f'{d2.name:>24} : {d2.donations}\n' string += f'{d3.name:>24} : {d3.donations}\n' assert string == repr(db1)
def test_add_donor(): """ Tests that you can add a donor to the database """ d1 = Donor('Maggie') d2 = Donor('Doug', 1000) d3 = Donor('キラ', 9001) db1 = db(d1) db1.add_donor(d2) db1.add_donor(d3) assert str(d1) in str(db1.database) assert str(d2) in str(db1.database) assert str(d3) in str(db1.database) assert db1.add_donor('Maggie') == 'Maggie already exists in database' assert db1.add_donor('Kurami') == 'Kurami has been added to the database' assert 'Kurami' in str(db1.database)
def test_remove_donatio1(): """ Test ability to remove donations from donor """ d1 = Donor('Maggie', 1000, 2000, 3000) d2 = Donor('Doug', 1111, 2222, 3333, 4444, 5555) d1.remove_donation(1000) d1.remove_donation(2000) d2.remove_donation(5555) d2.remove_donation(1111) assert 3000 in d1.donations assert 1000 not in d1.donations assert 2000 not in d1.donations assert 1111 not in d2.donations assert 5555 not in d2.donations message = d1.remove_donation(1337) assert message == f'Donation 1337 not found for {d1.name}'
def test_add_donation1(): """ Test ability to add donations to donor """ d1 = Donor('Maggie') d2 = Donor('Doug', 1000) d3 = Donor() d1.add_donation(1000) d2.add_donation(2000) d2.add_donation(3000) d3.add_donation(5000) assert 1000 in d1.donations assert 1000 in d2.donations assert 2000 in d2.donations assert 3000 in d2.donations assert 2000 not in d1.donations assert 5000 in d3.donations
def test_rename_donor(): """ Tests that you can rename a donor """ d1 = Donor('Light', 1000, 2000, 3000) d2 = Donor('Doug', 1111, 2222, 3333, 4444, 5555) db1 = db() db1.add_donor(d1) db1.add_donor(d2) db1.rename_donor('Light', 'キラ') assert 'Light' not in str(db1.database) assert 'キラ' in str(db1.database) assert db1.rename_donor('Light', 'キラ') == 'Donor キラ already exists in database' assert db1.rename_donor('キラ', 'Doug') == 'Donor Doug already exists in database'
def add_donation(self, name, amt): d = self.get_donor(name) if d is None: d = Donor(name, amt) self.add_donor(d) else: d.add_donation(amt)
def from_db(cls, in_database): """Alternate constructor which creates and returns a DonorDict based off the contents of the passed Peewee database. Args: in_database (string): Path to Peewee database. in_database (SqliteDatabse): SqliteDatabase instance. Returns: DonorDict: Newly constructed DonorDict """ if isinstance(in_database, str): database = pw.SqliteDatabase(in_database) elif isinstance(in_database, pw.SqliteDatabase): database = in_database else: raise Exception('Passed database reference is invalid') db_donors = {} donors = [] # Extract donors and their donations from the database with database as db: db.execute_sql('PRAGMA foreign_keys = ON;') query = dm.Donation.select().order_by(dm.Donation.donor_name.desc()) for d in query: db_donors.setdefault(str(d.donor_name), []).append(float(d.amount)) # Instantiate all Donor objects for donor, donations in db_donors.items(): donors.append(Donor(donor, donations=donations)) return cls(*donors)
def _update_dict(self): d_str = self._redis.get(self.db_name) if d_str: donors = json.loads(d_str) for d in donors: self[d[self.name_key]] = Donor(d[self.name_key], d[self.donations_key])
def test_copy(): d = Donor("Mark", 10) d.add_donation(30) d.add_donation(50) d2 = d.copy(filterFn=lambda d: d > 20 and d < 40, mapFn=lambda d: d * 10) assert d2._donations == [300]
def setup_initial_charity(): """Helper function for setting up charity for unit tests""" new_donor1 = Donor("Fred") new_donor1.add_donation(100) new_donor1.add_donation(1000) new_donor1.add_donation(10000) new_donor2 = Donor("Bob") new_donor2.add_donation(200) new_donor2.add_donation(2000) new_donor2.add_donation(20000) new_charity = Charity("Foundation") new_charity.add_donor(new_donor1.donor_name, new_donor1.donations_list) new_charity.add_donor(new_donor2.donor_name, new_donor2.donations_list) return new_charity
def validate_and_create_thank_you(self, name, amount, zip_code): """ send a thank you email to the donor for donation """ try: amount = float(amount) except ValueError as e: return 'invalid donation amount: ' + str(amount) donor = None for d in self.donor_list: if name == str(d): donor = d donor.zip_code = zip_code break if donor is None: try: donor = Donor(name, zip_code) except IndexError as e: return 'Could not send thank you. The first and last name of donor must be provided\n' else: self.donor_list.append(donor) # add donation to list in memory donor.amount_list.append(amount) # add donation to database donor.save_donation(amount) return f"Hi {d}\nThank you for your donation of {amount} to the mailroom!\n"
def validate_and_create_thank_you(self, name, amount): """ send a thank you email to the donor for donation """ try: amount = float(amount) except ValueError as e: return 'invalid donation amount: ' + str(amount) existing_donor = None for d in self.donor_list: if name == str(d): existing_donor = d break if existing_donor is not None: existing_donor.amount_list.append(amount) existing_donor.save_donation(amount) else: try: d = Donor(name, [amount]) except IndexError as e: return 'Could not send thank you. The first and last name of donor must be provided\n' else: self.donor_list.append(d) return f"Hi {d}\nThank you for your donation of {amount} to the mailroom!\n"
def test_donor_initialization(): proper_donations_list = [Donation(100), Donation(200), Donation(300)] d1 = Donor("Bob", proper_donations_list) assert d1.donor_name == "Bob" assert d1.donations_list == proper_donations_list # Check Non proper list is proved d2 = Donor("Ted", [Donation(100), 2, "Red"]) assert d2.donor_name == "Ted" assert d2.donations_list == [] # Check No list is provided d3 = Donor("Sam") assert d3.donor_name == "Sam" assert d3.donations_list == []
def test_total_donations(): """ Test total_donations property """ d1 = Donor('Maggie', 1000, 2000, 3000) assert d1.total_donations == 6000 d1.add_donation(4000) assert d1.total_donations == 10000 d1.remove_donation(1000) assert d1.total_donations == 9000
def test_average_donation(): """ Test average_donation property """ d1 = Donor('Maggie', 1000, 2000, 3000) assert d1.average_donation == 2000 d1.add_donation(4000) assert d1.average_donation == 2500 d1.remove_donation(1000) assert d1.average_donation == 3000
def test_remove_donor(): """ Tests ability to remove a donor from donordb """ d1 = Donor('Maggie', 1000, 2000, 3000) d2 = Donor('Doug', 1111, 2222, 3333, 4444, 5555) d3 = Donor('キラ', 9001) db1 = db() db1.add_donor(d1) db1.add_donor(d2) db1.add_donor(d3) assert str(d1) in str(db1.database) db1.remove_donor('Maggie') assert str(d1) not in str(db1.database) assert str(d2) in str(db1.database) db1.remove_donor('Doug') assert str(d2) not in str(db1.database) assert db1.remove_donor('Kurami') == 'Kurami not found in database' assert 'Kurami' not in db1.database
def challenge(self, alter, min_gift=-1.0, max_gift=-1.0, *filt_names): remain_names = [x for x in self.names if x not in filt_names] remain_d = [] new_d = [] if min_gift == -1.0: min_gift = min([min(g) for g in self.histories]) - .01 if max_gift == -1.0: max_gift = max([max(g) for g in self.histories]) + .01 with self._client as client: donors = client.get_database()['donors'] donor_data = donors.find() for d in donor_data: if d['name'] in filt_names: chal_d = Donor('*'+d['name'], d['gifts']) new_d.append(chal_d.challenge(alter, min_gift, max_gift)) else: remain_d.append(Donor(d['name'], d['gifts'])) return Donor_Dict(*(new_d+remain_d))
def load_donor_collection(self): directory = 'data/' donor_files = os.listdir(directory) for dfile in donor_files: m = re.match("(\w+)(_)(\w+)(.json)", dfile) if m: donor = Donor("{} {}".format(m.groups(1), m.groups(3))) self.donor_list.append(donor.load_data(f"{directory}{dfile}"))
def challenge(self, alter, min_gift=-1.0, max_gift=-1.0, *filt_names): remain_names = [x for x in self.names if x not in filt_names] remain_d = [] new_d = [] if min_gift == -1.0: min_gift = min([min(g) for g in self.histories]) - .01 if max_gift == -1.0: max_gift = max([max(g) for g in self.histories]) + .01 with self._driver.session() as session: data_cyph = ("MATCH (d:Donor) RETURN d.name as name, d.gifts as gifts") donor_data = session.run(data_cyph) for d in donor_data: if d['name'] in filt_names: chal_d = Donor('*'+d['name'], d['gifts']) new_d.append(chal_d.challenge(alter, min_gift, max_gift)) else: remain_d.append(Donor(d['name'], d['gifts'])) return Donor_Dict(*(new_d+remain_d))
def load_donor_collection(self): """ function to load donor collection from existing records in database """ mailroom_db = MailroomDB() donor_list_from_db = mailroom_db.get_donor_list() for existing_donor in donor_list_from_db: donor_name = f"{existing_donor[0]} {existing_donor[1]}" zip_code = rs.get_donor_zip_code(donor_name) donor = Donor(donor_name, zip_code) self.donor_list.append(donor)
def test_donor_add_donation(): d1 = Donor("Bob", [Donation(100)]) d1.add_donation(200) curr_time = datetime.datetime.now() # Check length of list, and attributes of the added donation object assert len(d1.donations_list) == 2 assert d1.donations_list[1].amount == 200 assert d1.donations_list[1].date == curr_time
def test_read_db_from_disk(): """ Tests that database can be loaded from disk """ d1 = Donor('Maggie', 1000, 2000, 3000) d2 = Donor('Doug', 1111, 2222, 3333, 4444, 5555) d3 = Donor('キラ') db1 = db() db1.add_donor(d1) db1.add_donor(d2) db1.add_donor(d3) db2 = db() db1.save_db_to_disk('./test_db.pkl') db2.read_db_from_disk('./test_db.pkl') assert str(d1) in str(db2.database) assert str(d2) in str(db2.database) assert str(d3) in str(db2.database) os.remove('./test_db.pkl') with pytest.raises(FileNotFoundError): db2.read_db_from_disk('./test_db.pkl')