def fleet_id_change(self, cr, uid, ids, order_fleet_id=False, fleet_id=False, product_id=False, maintenance_start_date=False, maintenance_product_qty=False): result = {} result['value'] = {} fleet_id = order_fleet_id or fleet_id if fleet_id: fleet = self.pool.get('stock.location').browse(cr, uid, fleet_id) if fleet.expire_time and not fleet.is_expired: start_date = DateTime.strptime(fleet.expire_time, '%Y-%m-%d') + RelativeDateTime(days=fixed_days_before_month_end + 1) else: start_date = maintenance_start_date and DateTime.strptime(maintenance_start_date, '%Y-%m-%d') or DateTime.strptime(self.default_maintenance_start_date(cr, uid, {}), '%Y-%m-%d') end_date = self._get_end_date_from_start_date(cr, uid, start_date, fleet) result['value'].update({'fleet_id': fleet_id}) if product_id: product = self.pool.get('product.product').browse(cr, uid, product_id) if product.is_maintenance: maintenance_month_qty = self._get_maintenance_month_qty_from_start_end(cr, uid, start_date, end_date) result['value'].update({'maintenance_start_date': start_date.strftime('%Y-%m-%d')}) result['value'].update({'maintenance_end_date': end_date.strftime('%Y-%m-%d')}) result['value'].update({'maintenance_month_qty': maintenance_month_qty}) result['value'].update({'product_uom_qty': maintenance_product_qty * maintenance_month_qty}) result['value'].update({'product_uos_qty': maintenance_product_qty * maintenance_month_qty}) # TODO * product_obj.uos_coeff return result
def setUp(self): """ called before each test from this class """ _, _, resources, _, _, cal = simple_project() # set of dates self.date_last_week = DateTime(2004, 10, 1) self.date_today = DateTime(2004, 10, 7) self.date_tomorrow = DateTime(2004, 10, 8) self.date_next_week = DateTime(2004, 10, 13) self.date_next_score = DateTime(2004, 10, 26) # set up calendar cal.day_types = {'working':['Working', [(Time(8), Time(12)), (Time(13), Time(17))]], 'halfday':['HalfDay', [(Time(9), Time(15))]], 'nonworking': ['Nonworking', []], } cal.default_day_type = 'working' cal.add_timeperiod(self.date_last_week, self.date_last_week, 'nonworking') cal.add_timeperiod(self.date_today, self.date_today, 'working') cal.add_timeperiod(self.date_tomorrow, self.date_next_week, 'halfday') cal.weekday['sat'] = 'nonworking' cal.weekday['sun'] = 'nonworking' # set up calendar 2 cal_2 = Calendar('c_2', 'Special Calendar') cal_2.add_timeperiod(self.date_next_week, self.date_next_score, 'nonworking') # build tree cal.append(cal_2) # set up resources self.r1 = resources[0] # tata self.r2 = resources[1] # toto self.r2.calendar = cal_2
def oswego_xform_post(row_dict): # create synthetic meal date/time meal_time = row_dict['meal_time'] if meal_time != None: mt_hrmin, mt_ampm = meal_time.split() mt_hr, mt_min = map(int, mt_hrmin.split(':')) if mt_ampm == 'PM': mt_hr += 12 row_dict['meal_datetime'] = DateTime(1980, 4, 18, mt_hr, mt_min) else: row_dict['meal_datetime'] = None # create synthetic onset date/time onset_time = row_dict['onset_time'] onset_date = row_dict['onset_date'] if onset_time != None and onset_date != None: on_hrmin, on_ampm = onset_time.split() on_hr, on_min = map(int, on_hrmin.split(':')) if on_ampm == 'PM': on_hr += 12 on_mth, on_day = map(int, onset_date.split('/')) row_dict['onset_datetime'] = DateTime(1980, on_mth, on_day, on_hr, on_min) else: row_dict['onset_datetime'] = None return row_dict
def setUp(self): """ called before each test from this class """ self.stone = MileStone('Test') self.child_stone = MileStone('Test_child') self.unicode_stone = MileStone(u'accentuée') self.unicode_stone.description = u"autre chaîne unicode non-ASCII" # set of dates self.date_today = DateTime(2004, 10, 7) self.date_tomorrow = DateTime(2004, 10, 8) self.date_yesterday = DateTime(2004, 10, 6) # set of date constraints self.at_constraints = { BEGIN_AT_DATE: self.date_yesterday, END_AT_DATE: self.date_tomorrow } self.before_constraints = { BEGIN_BEFORE_DATE: self.date_today, END_BEFORE_DATE: self.date_tomorrow } self.after_constraints = { BEGIN_AFTER_DATE: self.date_yesterday, END_AFTER_DATE: self.date_today } self.before_after_constraints = { BEGIN_BEFORE_DATE: self.date_today, END_AFTER_DATE: self.date_yesterday } # set of id self.good_id = 'good_id' self.other_id = 'other_id' self.another_id = 'another_id' self.last_id = 'last_id'
def get_rs(self): db.reset(result=[ ('abc', -1, True, DateTime(2003, 1, 1), None, 0, 0), ('def', -2, False, DateTime(2005, 2, 2), None, 2, 0), ]) rs = dbobj.ResultSet(td) rs.from_cursor(db.cursor()) return rs
def test_update(self): rs = self.get_rs() # Check changed row behaviour rs[0].id = 3 self.assertEqual(rs.db_has_changed(), True) self.assertEqual( repr(rs[0]), "<%s: id=3, textcol='abc', intcol=-1, boolcol=True, datecol=<cocklebur.datetime.mx_parse_datetime 01/01/2003 00:00:00>, lastupt=None, missing=None>" % table_name) self.assertEqual(rs[0].db_desc(), 'testtable[id:0->3]') # Check .db_revert() rs.db_revert() self.assertEqual(rs.db_has_changed(), False) self.assertEqual( repr(rs[0]), "<%s: id=0, textcol='abc', intcol=-1, boolcol=True, datecol=<cocklebur.datetime.mx_parse_datetime 01/01/2003 00:00:00>, lastupt=None, missing=None>" % table_name) # Check .db_update() now1 = DateTime(2009, 8, 11, 10, 0, 0) db.reset(result=[ ('lmn', -1, False, DateTime(2003, 1, 1), now1, 3, 0), ]) rs[0].id = 3 rs[0].boolcol = '' testcommon.freeze_time(now1, rs.db_update) self.check_exec([ ('UPDATE testtable SET id=%s, boolcol=%s, lastupt=%s WHERE id=%s', (3, False, now1, 0)), ('SELECT * FROM testtable WHERE id=%s', (3, )), ]) self.assertEqual(rs.db_has_changed(), False) self.assertEqual(rs[0].id, 3) self.assertEqual(rs[0].boolcol, '') self.assertEqual(rs[0].textcol, 'lmn') self.assertEqual(rs[0].lastupt, now1) # Check subsequent update now2 = DateTime(2009, 8, 11, 10, 1, 0) db.reset(result=[ ('lmn', -1, True, DateTime(2003, 1, 1), now2, 4, 0), ]) rs[0].id = 4 testcommon.freeze_time(now2, rs.db_update) self.check_exec([ ('UPDATE testtable SET id=%s, lastupt=%s WHERE id=%s', (4, now2, 3)), ('SELECT * FROM testtable WHERE id=%s', (4, )), ]) self.assertEqual(rs.db_has_changed(), False) self.assertEqual(rs[0].id, 4) self.assertEqual(rs[0].textcol, 'lmn') self.assertEqual(rs[0].lastupt, now2) # Check rollback() behaviour - for ResultRows, the effect is to # (mostly) undo the effects of the last db_update(), so a subsequent # db_update() will attempt to reapply any changes. db.rollback() self.assertEqual(rs.db_has_changed(), True) self.assertEqual(rs[0].id, 4) self.assertEqual(rs[0].lastupt, now1)
def maintenance_qty_change(self, cr, uid, ids, maintenance_product_qty=False, maintenance_month_qty=False, maintenance_start_date=False, maintenance_end_date=False, is_maintenance=False, fleet_id=False): result = {} if not is_maintenance: return result result['value'] = {} warning_messages = "" if maintenance_start_date: start = DateTime.strptime(maintenance_start_date, '%Y-%m-%d') if start.day != fixed_month_init_day: warning_messages += "- Start date should should ideally start at day %s of the month; corrected to day %s\n" % (fixed_month_init_day, fixed_month_init_day) start = DateTime.DateTime(start.year, start.month, fixed_month_init_day) result['value'].update({'maintenance_start_date': start.strftime('%Y-%m-%d')}) #return result if maintenance_end_date: end = DateTime.strptime(maintenance_end_date, '%Y-%m-%d') en_date_check = end + DateTime.RelativeDateTime(days=fixed_days_before_month_end + 1) if end.month == en_date_check.month or en_date_check.day != 1: warning_messages += "- End date should should end %s days before the end of the month! It has been reset to the correct value.\n" % fixed_days_before_month_end day = end.days_in_month - fixed_days_before_month_end end = DateTime.DateTime(end.year, end.month, day, 0, 0, 0.0) result['value'].update({'maintenance_end_date': end.strftime('%Y-%m-%d')}) if maintenance_start_date and maintenance_end_date: if end < start: warning_messages += "- End date should be AFTER Start date!\n" day = start.days_in_month - fixed_days_before_month_end #then we set the minimal end date end = DateTime.DateTime(start.year, start.month, day, 0, 0, 0.0) result['value'].update({'maintenance_end_date': end.strftime('%Y-%m-%d')}) maintenance_month_qty = self._get_maintenance_month_qty_from_start_end(cr, uid, start, end) result['value'].update({'maintenance_month_qty': maintenance_month_qty}) if maintenance_month_qty < min_maintenance_months: warning_messages += "- we usually try to sell %s months at least!\n" % min_maintenance_months if fleet_id: fleet = self.pool.get('stock.location').browse(cr, uid, fleet_id) theoretic_end = self._get_end_date_from_start_date(cr, uid, start, fleet) if theoretic_end.year != end.year or theoretic_end.month != end.month or theoretic_end.day != end.day: warning_messages += "- Theoretic Maintenance End Date was: %s !\n" % theoretic_end.strftime('%Y-%m-%d') if maintenance_product_qty and maintenance_month_qty: #only set the default fleet at init result['value'].update({'product_uom_qty': maintenance_product_qty * maintenance_month_qty}) result['value'].update({'product_uos_qty': maintenance_product_qty * maintenance_month_qty}) # TODO * product_obj.uos_coeff if len(warning_messages) > 1: result['warning'] = {'title': 'Maintenance Dates Warning', 'message': warning_messages} return result
def test_availability(self): DAY = [MORNING, AFTERNOON] self.assertEqual(self.c1.availability(DateTime(2004, 01, 05)), []) self.assertEqual(self.c1.availability(DateTime(2004, 01, 06)), DAY) self.assertEqual(self.c1.availability(DateTime(2004, 05, 07)), []) self.assertEqual(self.c1.availability(DateTime(2004, 06, 07)), [HALFDAY]) self.assertEqual(self.c1.availability(DateTime(2006, 12, 29)), DAY) self.assertEqual(self.c1.availability(DateTime(2006, 12, 30)), []) self.assertEqual(self.c2.availability(DateTime(2004, 05, 07)), [])
def fleet_id_change(self, cr, uid, ids, order_fleet_id=False, fleet_id=False, product_id=False, maintenance_start_date=False, maintenance_product_qty=False): result = {} result['value'] = {} fleet_id = order_fleet_id or fleet_id if fleet_id: fleet = self.pool.get('stock.location').browse(cr, uid, fleet_id) if fleet.expire_time and not fleet.is_expired: start_date = DateTime.strptime( fleet.expire_time, '%Y-%m-%d') + RelativeDateTime( days=fixed_days_before_month_end + 1) else: start_date = maintenance_start_date and DateTime.strptime( maintenance_start_date, '%Y-%m-%d') or DateTime.strptime( self.default_maintenance_start_date(cr, uid, {}), '%Y-%m-%d') end_date = self._get_end_date_from_start_date( cr, uid, start_date, fleet) result['value'].update({'fleet_id': fleet_id}) if product_id: product = self.pool.get('product.product').browse( cr, uid, product_id) if product.is_maintenance: maintenance_month_qty = self._get_maintenance_month_qty_from_start_end( cr, uid, start_date, end_date) result['value'].update({ 'maintenance_start_date': start_date.strftime('%Y-%m-%d') }) result['value'].update({ 'maintenance_end_date': end_date.strftime('%Y-%m-%d') }) result['value'].update( {'maintenance_month_qty': maintenance_month_qty}) result['value'].update({ 'product_uom_qty': maintenance_product_qty * maintenance_month_qty }) result['value'].update({ 'product_uos_qty': maintenance_product_qty * maintenance_month_qty }) # TODO * product_obj.uos_coeff return result
def set_time(): h = int(time_field_hour.get()) m = int(time_field_min.get()) s = int(time_field_sec.get()) self.go_time = DateTime(now().year,now().month,now().day,h,m,s) if self.go_time < now(): self.go_time = DateTime(now().year, now().month, now().day + 1, h, m, s) self.dt = self.go_time - now() self.armed = True run_alarm()
def test_long_result(self): # We use fetchmany, so this tests our ability to repeatedly fetch db.reset(result=[ ('abc', -1, True, DateTime(2003, 1, 1), None, 0, 0), ('def', -2, False, DateTime(2005, 2, 2), None, 2, 0), ('ghi', -4, False, DateTime(2002, 3, 4), None, 3, 0), ] * 99) curs = db.cursor() rs = dbobj.ResultSet(td) rs.from_cursor(curs) self.assertEqual(len(rs), 99 * 3)
def test_iso_datetime(self): conv = SourceDataTypes.get_conversion('iso-datetime') self.assertEqual(conv('1970-12-23 01:12:23.34'), DateTime(1970, 12, 23, 1, 12, 23.34)) self.assertEqual(conv('1970-12-23 01:12:23.34'), DateTime(1970, 12, 23, 1, 12, 23.34)) self.assertEqual(conv('70-12-23 1:12:23.4'), DateTime(1970, 12, 23, 1, 12, 23.4)) self.assertEqual(conv('70-12-23 1:2:3.4'), DateTime(1970, 12, 23, 1, 2, 3.4)) self.assertEqual(conv(None), None) self.assertEqual(conv(''), None)
def _maintenance_month_qty(self, cr, uid, ids, prop, unknow_none, context={}): result = {} for line in self.browse(cr, uid, ids, context=context): if line.maintenance_start_date and line.maintenance_end_date: result[line.id] = self._get_maintenance_month_qty_from_start_end( cr, uid, DateTime.strptime(line.maintenance_start_date, "%Y-%m-%d"), DateTime.strptime(line.maintenance_end_date, "%Y-%m-%d"), ) else: result[line.id] = 0 return result
def _get_end_date_from_start_date(self, cr, uid, start_date, sub_fleet): year = start_date.year anniversary_time = DateTime.strptime(sub_fleet.anniversary_time, '%Y-%m-%d') month = anniversary_time.month day = anniversary_time.days_in_month - fixed_days_before_month_end end = DateTime.DateTime(year, month, day, 0, 0, 0.0) delta = DateTime.RelativeDateDiff( end + RelativeDateTime(days=fixed_days_before_month_end + 1), start_date) maintenance_month_qty = delta.months + delta.years * 12 if maintenance_month_qty < min_maintenance_months: end = DateTime.DateTime(year + 1, month, day, 0, 0, 0.0) return end
def fleet_id_change( self, cr, uid, ids, order_fleet_id=False, fleet_id=False, product_id=False, maintenance_start_date=False, maintenance_product_qty=False, ): result = {} result["value"] = {} fleet_id = order_fleet_id or fleet_id if fleet_id: fleet = self.pool.get("stock.location").browse(cr, uid, fleet_id) if fleet.expire_time and not fleet.is_expired: start_date = DateTime.strptime(fleet.expire_time, "%Y-%m-%d") + RelativeDateTime( days=fixed_days_before_month_end + 1 ) else: start_date = ( maintenance_start_date and DateTime.strptime(maintenance_start_date, "%Y-%m-%d") or DateTime.strptime(self.default_maintenance_start_date(cr, uid, {}), "%Y-%m-%d") ) end_date = self._get_end_date_from_start_date(cr, uid, start_date, fleet) result["value"].update({"fleet_id": fleet_id}) if product_id: product = self.pool.get("product.product").browse(cr, uid, product_id) if product.is_maintenance: maintenance_month_qty = self._get_maintenance_month_qty_from_start_end( cr, uid, start_date, end_date ) result["value"].update({"maintenance_start_date": start_date.strftime("%Y-%m-%d")}) result["value"].update({"maintenance_end_date": end_date.strftime("%Y-%m-%d")}) result["value"].update({"maintenance_month_qty": maintenance_month_qty}) result["value"].update({"product_uom_qty": maintenance_product_qty * maintenance_month_qty}) result["value"].update( {"product_uos_qty": maintenance_product_qty * maintenance_month_qty} ) # TODO * product_obj.uos_coeff return result
def correctedDateTimeFromString(year_str, month_str, day_str, hour_str, minute_str, second_str): """Return mx.DateTime object from string components. Correct if illegal components are given: hour=24, minute=60, second=60. """ correction_applied = False # check if one of the time components has to be corrected timeCorrection = fixTimeComponents(int(hour_str), int(minute_str), float(second_str)) if sum(timeCorrection['increaseDelta']) > 0: correction_applied = True uncorrected_datetime = DateTime(int(year_str), int(month_str), int(day_str), timeCorrection['component'][0], timeCorrection['component'][1], timeCorrection['component'][2]) corrected_datetime = adjustDateTime(timeCorrection['increaseDelta'], uncorrected_datetime) return (corrected_datetime, correction_applied)
def create_analytic_lines(self, cr, uid, ids, context={}): res = super(account_move_line, self).create_analytic_lines(cr, uid, ids, context) matched_invoice_line_ids = [] for move_line in self.browse(cr, uid, ids, context): if move_line.analytic_lines and len(move_line.analytic_lines) == 1 and move_line.product_id.is_maintenance and move_line.invoice: print "native analytic line creation" print move_line analytic_line = move_line.analytic_lines[0] #we assume their is only one analytic line for a maintenance product print analytic_line for invoice_line in move_line.invoice.invoice_line: if invoice_line.id not in matched_invoice_line_ids: #we take care of not matching invoice line twice if invoice_line.product_id and invoice_line.product_id.is_maintenance \ and invoice_line.product_id.id == analytic_line.product_id.id and analytic_line.amount == invoice_line.price_subtotal: matched_invoice_line_ids.append(invoice_line.id) month_qty = int(invoice_line.maintenance_month_qty) splitted_amount = invoice_line.quantity / invoice_line.maintenance_month_qty amount = float(analytic_line.amount) / float(invoice_line.maintenance_month_qty) start_date = DateTime.strptime(invoice_line.maintenance_start_date, '%Y-%m-%d') self.pool.get('account.analytic.line').write(cr, uid, analytic_line.id, {'invoice_line_id':invoice_line.id, 'date':start_date, 'unit_amount':splitted_amount, 'amount': amount}) for i in range(1, month_qty): start_date += DateTime.RelativeDateTime(months=1) print start_date self.pool.get('account.analytic.line').copy(cr, uid, analytic_line.id, {'date': start_date}) #TODO check month_qty return res
def whotext_xform_pre(row_dict): months = { 'January': 1, 'February': 2, 'March': 3, 'April': 4, 'May': 5, 'June': 6, 'July': 7, 'August': 8, 'September': 9, 'October': 10, 'November': 11, 'December': 12 } rawdate = row_dict['repdate'] try: day, wordmonth, year = rawdate.split() except: print rawdate sys.exit() month = months[wordmonth] newdate = DateTime(int(year), month, int(day)) row_dict['repdate'] = str(newdate.day) + '/' + str( newdate.month) + '/' + str(newdate.year) row_dict['report'] = row_dict['report'].replace('<p>', '\n') return row_dict
def term_barcode_mx_date(barcode): "Возвращает дату/время генерации ШК типа mx.DateTime.DateTime" d0 = DateTime(2010, 1, 1, 0, 0, 0) minutes = numeral_systems.any_to_dec(barcode[7:12], 36) return d0 + TimeDelta(minutes=minutes)
def __init__(self, locked=False): init_dict = self.__init_dict__ for key in init_dict: value = init_dict[key] date, mo, da, ye, time, ho, mi, se = [None] * 8 if type(value) in [str, unicode]: date, mo, da, ye, time, ho, mi, se = reDateTime.match( value).groups() if type(init_dict[key]) == dict: setattr(self, key, makeFMData( init_dict[key], locked=False)) # lock all substructures?? elif type(init_dict[key]) == list: l = [] for d in init_dict[key]: if type(d) == dict: l.append(makeFMData(d)) # lock ?? else: l.append(d) setattr(self, key, l) elif date and time: setattr( self, key, DateTime(int(ye), int(mo), int(da), int(ho), int(mi), int(se))) elif date: setattr(self, key, Date(int(ye), int(mo), int(da))) elif time: setattr(self, key, Time(int(ho), int(mi), int(se))) else: setattr(self, key, init_dict[key]) if locked: self.__modified__.add('__locked__')
def addEventLine(self, year, eventline): #print "Event line:", eventline event = {} parts = eventline.split(None, 1) if len(parts) == 1 or len(parts) == 0: return if parts[0] == "opt": if parts[1] == "-A": self.dateStyle = self.AMERICAN print "Setting date style to AMERICAN" elif parts[1] == "-E": self.dateStyle = self.EUROPEAN return if parts[0] == "year": return if len(parts[0]) != 5: return if parts[0][2] != "/": return if self.dateStyle == self.EUROPEAN: day = int(parts[0][0:2]) month = int(parts[0][3:]) elif self.dateStyle == self.AMERICAN: month = int(parts[0][0:2]) day = int(parts[0][3:]) event['text'] = parts[1].strip() event['short'] = event['text'] #print "Adding event", year, month, day, "=", event['text'] index = DateTime(year, month, day) if self.datelist.has_key(index): self.datelist[index].append(event) else: self.datelist[index] = [ event, ]
def mk_calendar1(): cal = Calendar('c_1', 'Calendrier 1') cal.day_types = {'nonworking': ['Non working', []], 'working': ['Working', [MORNING, AFTERNOON]], 'halfday': ['HalfDay', [HALFDAY]], } cal.default_day_type = 'working' cal.national_days = [(1,1), (12,25), (11,11)] cal.start_on = DateTime(2004,01,06) cal.stop_on = DateTime(2006,12,29) cal.weekday['mon'] = 'working' cal.weekday['tue'] = 'working' cal.weekday['wed'] = 'working' cal.weekday['thu'] = 'working' cal.weekday['fri'] = 'working' cal.weekday['sat'] = 'nonworking' cal.weekday['sun'] = 'nonworking' date = DateTime(2004, 05, 07) cal.add_timeperiod(date, date, 'nonworking') date = DateTime(2004, 05, 05) cal.add_timeperiod(date, date, 'working') date = DateTime(2004, 06, 07) cal.add_timeperiod(date, date, 'halfday') return cal
def create_analytic_lines(self, cr, uid, ids, context={}): res = super(account_move_line, self).create_analytic_lines(cr, uid, ids, context) matched_invoice_line_ids = [] for move_line in self.browse(cr, uid, ids, context): if move_line.analytic_lines and len( move_line.analytic_lines ) == 1 and move_line.product_id.is_maintenance and move_line.invoice: print "native analytic line creation" print move_line analytic_line = move_line.analytic_lines[ 0] #we assume their is only one analytic line for a maintenance product print analytic_line for invoice_line in move_line.invoice.invoice_line: if invoice_line.id not in matched_invoice_line_ids: #we take care of not matching invoice line twice if invoice_line.product_id and invoice_line.product_id.is_maintenance \ and invoice_line.product_id.id == analytic_line.product_id.id and analytic_line.amount == invoice_line.price_subtotal: matched_invoice_line_ids.append(invoice_line.id) month_qty = int(invoice_line.maintenance_month_qty) splitted_amount = invoice_line.quantity / invoice_line.maintenance_month_qty amount = float(analytic_line.amount) / float( invoice_line.maintenance_month_qty) start_date = DateTime.strptime( invoice_line.maintenance_start_date, '%Y-%m-%d') self.pool.get('account.analytic.line').write( cr, uid, analytic_line.id, { 'invoice_line_id': invoice_line.id, 'date': start_date, 'unit_amount': splitted_amount, 'amount': amount }) for i in range(1, month_qty): start_date += DateTime.RelativeDateTime( months=1) print start_date self.pool.get('account.analytic.line').copy( cr, uid, analytic_line.id, {'date': start_date }) #TODO check month_qty return res
def test_adapt_bc_datetime(self): value = self.execute('select (%s)::timestamp::text', [DateTime(-41, 1, 1, 13, 30, 29.123456)]) # microsecs for BC timestamps look not available in PG < 8.4 # but more likely it's determined at compile time. self.assert_( value in ('0042-01-01 13:30:29.123456 BC', '0042-01-01 13:30:29 BC'), value)
def date(self): """return a mx.DateTime object for the email's date or None if no date is set or if it can't be parsed """ value = self.get('date') if value: datetuple = parsedate(value) if datetuple: return DateTime(*datetuple[:6]) return None
def test_phonenumberchange_delay(self): """Fresh phone numbers should not be used if config says so.""" cereconf.INDIVIDUATION_PHONE_TYPES['system_fs']['types']['contact_mobile_phone']['delay'] = 7 cereconf.INDIVIDUATION_PHONE_TYPES['system_fs']['types']['contact_private_mobile']['delay'] = 7 ou = Factory.get('OU')(self.db) co = Factory.get('Constants')(self.db) ou.find_stedkode(0, 0, 0, 0) pe = self.createPerson(first_name='Miss', last_name='Test', studnr='007') ac = self.createAccount(pe, 'mstest') pe.populate_affiliation(source_system=co.system_fs, ou_id=ou.entity_id, affiliation=co.affiliation_student, status=co.affiliation_status_student_aktiv) pe.write_db() pe.populate_contact_info(source_system=co.system_fs, type=co.contact_mobile_phone, value='98012345') pe.write_db() # Create e-mail address for user ed = Email.EmailDomain(self.db) ed.populate('example.com', 'For testing') ed.write_db() et = Email.EmailTarget(self.db) et.populate(co.email_target_account, ac.entity_id, co.entity_account) et.write_db() ea = Email.EmailAddress(self.db) ea.populate('test', ed.entity_id, et.entity_id) ea.write_db() epa = Email.EmailPrimaryAddressTarget(self.db) epa.populate(ea.entity_id, et) epa.write_db() self.db.commit() # hack the create_date in change_log self.db.execute(""" UPDATE [:table schema=cerebrum name=change_log] SET tstamp = :tid WHERE subject_entity = :s_id AND change_type_id = :ct_id""", {'s_id': pe.entity_id, 'ct_id': co.person_create, 'tid': DateTime(2009, 10, 4),}) self.db.commit() d = self.client.callRemote('generate_token', id_type="externalid_studentnr", ext_id='007', username='******', phone_no='98012345', browser_token='a') d = self.assertFailure(d, error.Error) # TODO: test that sendmail is called with the correct to-address return d
def test_get_usernames(self): pe = self.createPerson(DateTime(1984, 8, 1), "Ola", "Nordmann", ansnr='12387001') self.createAccount(pe, 'ola') self.createAccount(pe, 'olano') self.createAccount(pe, 'norman') d = self.client.callRemote('get_usernames', id_type='externalid_sap_ansattnr', ext_id='12387001') d.addCallback(self.assertAccounts, ('ola', 'olano', 'norman')) return d
def test_adapt_bc_datetime(self): from mx.DateTime import DateTime value = self.execute("select (%s)::timestamp::text", [DateTime(-41, 1, 1, 13, 30, 29.123456)]) # microsecs for BC timestamps look not available in PG < 8.4 # but more likely it's determined at compile time. self.assertTrue( value in ("0042-01-01 13:30:29.123456 BC", "0042-01-01 13:30:29 BC"), value)
def _get_end_date_from_start_date(self, cr, uid, start_date, sub_fleet): year = start_date.year anniversary_time = DateTime.strptime(sub_fleet.anniversary_time, '%Y-%m-%d') month = anniversary_time.month day = anniversary_time.days_in_month - fixed_days_before_month_end end = DateTime.DateTime(year, month, day, 0, 0, 0.0) delta = DateTime.RelativeDateDiff(end + RelativeDateTime(days=fixed_days_before_month_end + 1), start_date) maintenance_month_qty = delta.months + delta.years * 12 if maintenance_month_qty < min_maintenance_months: end = DateTime.DateTime(year + 1, month, day, 0, 0, 0.0) return end
def _maintenance_month_qty(self, cr, uid, ids, prop, unknow_none, context={}): result = {} for line in self.browse(cr, uid, ids, context=context): if line.maintenance_start_date and line.maintenance_end_date: result[ line.id] = self._get_maintenance_month_qty_from_start_end( cr, uid, DateTime.strptime(line.maintenance_start_date, '%Y-%m-%d'), DateTime.strptime(line.maintenance_end_date, '%Y-%m-%d')) else: result[line.id] = False return result
def asMx( self ): """Produce an mxDateTime instance for this value""" from mx.DateTime import DateTime return DateTime.DateTime( source.year, source.month, source.day, source.hour, source.minute, source.second + (source.microsecond/1000.0), #source.tzinfo )
def test_short_result(self): db.reset(result=[ ('abc', -1, True, DateTime(2003, 1, 1), None, 0, 0), ('def', -2, False, DateTime(2005, 2, 2), None, 2, 0), ]) curs = db.cursor() rs = dbobj.ResultSet(td) rs.from_cursor(curs) self.assertEqual(len(rs), 2) self.assertEqual(rs.db_has_changed(), False) rs.db_update() self.check_exec(None) self.assertEqual(rs[0].textcol, 'abc') self.assertEqual(rs[1].textcol, 'def') self.assertEqual( repr(rs[0]), "<%s: id=0, textcol='abc', intcol=-1, boolcol=True, datecol=<cocklebur.datetime.mx_parse_datetime 01/01/2003 00:00:00>, lastupt=None, missing=None>" % table_name) self.assertEqual(rs[0].db_desc(), None) self.assertEqual(rs[0].is_new(), False) self.assertEqual(rs[0].db_has_changed(), False) # Make sure we can pickle and restore the set rs2 = loads(dumps(rs)) self.assertEqual(rs[0].textcol, 'abc') self.assertEqual(rs[1].textcol, 'def') self.assertEqual( repr(rs[0]), "<%s: id=0, textcol='abc', intcol=-1, boolcol=True, datecol=<cocklebur.datetime.mx_parse_datetime 01/01/2003 00:00:00>, lastupt=None, missing=None>" % table_name) # Refetch db.reset(result=[ ('abc', -1, True, DateTime(2003, 1, 1), None, 0, 0), ]) rs[0].db_refetch() self.check_exec([ ('SELECT * FROM testtable WHERE id=%s', (0, )), ])
def test_insert(self): rs = self.get_rs() # Make a new row row = rs.new_row() row.id = 4 row.textcol = 'xyz' row.intcol = 99 row.boolcol = 1 self.assertEqual(rs.db_has_changed(), False) # Attach it to the rowset rs.append(row) self.assertEqual(row.is_new(), True) self.assertEqual(len(rs), 3) self.assertEqual(rs.db_has_changed(), True) # Check a revert detaches it rs.db_revert() self.assertEqual(len(rs), 2) self.assertEqual(rs.db_has_changed(), False) # Check that it gets committed rs.append(row) db.reset(result=[ ('hij', 99, True, None, None, 4, 0), ]) now = DateTime(2009, 8, 11, 10, 0, 0) testcommon.freeze_time(now, rs.db_update) self.assertEqual(row.is_new(), False) self.check_exec([ ('INSERT INTO testtable (id,textcol,intcol,boolcol,lastupt) VALUES (%s,%s,%s,%s,%s)', (4, 'xyz', 99, dbobj.TRUE, now)), ('SELECT * FROM testtable WHERE oid=%s', (999, )), ]) # Now see if the refetch worked self.assertEqual(row.id, 4) self.assertEqual(row.textcol, 'hij') self.assertEqual(row.intcol, 99) self.assertEqual(row.boolcol, 'True') # This is to make web apps happy self.assertEqual(row.datecol, None) # A subsequent rollback should set us back to the pre-update state db.rollback() self.assertEqual(row.id, 4) self.assertEqual(row.textcol, 'xyz') # And we should now be able to do another update, and a commit, and any # following rollbacks shouldn't touch us. db.reset(result=[ ('hij', 99, False, None, None, 4, 0), ]) rs.db_update() db.commit() db.rollback() self.assertEqual(row.textcol, 'hij')
def __init__(self, surname, given_names, sex=None, DOB=None, DOB_prec=0, street_address=None, locality=None, state=None, postcode=None, country=None, alt_street_address=None, alt_locality=None, alt_state=None, alt_postcode=None, alt_country=None, work_street_address=None, work_locality=None, work_state=None, work_postcode=None, work_country=None, passport_number=None, passport_country=None, passport_number_2=None, passport_country_2=None, home_phone=None, work_phone=None, mobile_phone=None, fax_phone=None, e_mail=None, last_update=None): self.__dict__.update(vars()) if self.DOB: self.DOB = DateTime(*[int(d) for d in self.DOB.split('-')]) Person.id += 1 self.person_id = self.id self.last_update = None
def POST(self): i = web.input() job_form = AddJob(Request().POST) user_id = web.ctx.session.user_id name = db.users.filter_by(id=user_id).first().name jobs = db.jobs.all() if job_form.validate() is True: start_date = i.start_date.split("/") day = int(start_date[0]) month = int(start_date[1]) year = int(start_date[2]) time = DateTime(year, month, day, 0, 0, 0) db.jobs.insert(job_nm=i.job_name, job_desc=i.job_desc, job_date_start=time.ticks()) try: db.commit() except: db.rollback() web.redirect('../welcome/') else: return render('welcome.mako', name=name, jobs=jobs, job_form=job_form)
def test_parse_datetime_timezone(self): # Time zone information is ignored. expected = DateTime(2007, 1, 1, 13, 30, 29) self.assertEqual(expected, self.DATETIME("2007-01-01 13:30:29+01", self.curs)) self.assertEqual(expected, self.DATETIME("2007-01-01 13:30:29-01", self.curs)) self.assertEqual(expected, self.DATETIME("2007-01-01 13:30:29+01:15", self.curs)) self.assertEqual(expected, self.DATETIME("2007-01-01 13:30:29-01:15", self.curs)) self.assertEqual( expected, self.DATETIME("2007-01-01 13:30:29+01:15:42", self.curs)) self.assertEqual( expected, self.DATETIME("2007-01-01 13:30:29-01:15:42", self.curs))
def mountTime(self, time_str): dic_time = {"day": 0, "month": 0, "year": 0, "hour": 0, "minute": 0} dic_time["day"] = int(time_str[0:2]) dic_time["month"] = int(time_str[2:4]) dic_time["year"] = int(time_str[4:8]) dic_time["hour"] = int(time_str[8:10]) dic_time["min"] = int(time_str[10:12]) ret = self._validateTime(dic_time) if ret == OK: time = DateTime(dic_time["year"], dic_time["month"], dic_time["day"], dic_time["hour"], dic_time["min"], 0) return time else: return INVALID
def default_maintenance_start_date(self, cr, uid, context={}): now = DateTime.now() date = DateTime.DateTime(now.year, now.month, fixed_month_init_day, 0, 0, 0.0) + DateTime.RelativeDateTime(months=default_maintenance_start_delta) return date.strftime('%Y-%m-%d')