def _tap_detail_post(request, tap): form = forms.DrinkPostForm(request.POST) if not form.is_valid(): raise kbapi.BadRequestError, _form_errors(form) cd = form.cleaned_data if cd.get('pour_time') and cd.get('now'): pour_time = datetime.datetime.fromtimestamp(cd.get('pour_time')) now = datetime.datetime.fromtimestamp(cd.get('now')) skew = datetime.datetime.now() - now pour_time += skew else: pour_time = None duration = cd.get('duration') if duration is None: duration = 0 b = KegbotBackend(site=request.kbsite) try: res = b.RecordDrink(tap_name=tap, ticks=cd['ticks'], volume_ml=cd.get('volume_ml'), username=cd.get('username'), pour_time=pour_time, duration=duration, auth_token=cd.get('auth_token'), spilled=cd.get('spilled'), shout=cd.get('shout')) return protolib.ToProto(res, full=True) except backend.BackendError, e: raise kbapi.ServerError(str(e))
def _thermo_sensor_post(request, sensor_name): form = forms.ThermoPostForm(request.POST) if not form.is_valid(): raise kbapi.BadRequestError, _form_errors(form) cd = form.cleaned_data b = KegbotBackend(site=request.kbsite) sensor, created = models.ThermoSensor.objects.get_or_create( site=request.kbsite, raw_name=sensor_name) # TODO(mikey): use form fields to compute `when` return b.LogSensorReading(sensor.raw_name, cd['temp_c'])
def _coin_selector_post(request, selector_name): form = forms.CoinSelectorPostForm(request.POST) if not form.is_valid(): raise kbapi.BadRequestError, _form_errors(form) cd = form.cleaned_data b = KegbotBackend(site=request.kbsite) selector, created = models.CoinSelector.objects.get_or_create( site=request.kbsite, name=selector_name) # TODO(mikey): use form fields to compute `when` return b.LogCoinInserted(selector.name, cd['ticks'])
def setUp(self): models.KegbotSite.objects.filter(name='default').delete() self.site, created = models.KegbotSite.objects.get_or_create( name='default') self.backend = KegbotBackend(site=self.site) self.brewer = bdb_models.Brewer.objects.create( name='Moonshine Beers', country='USA', origin_state='Anystate', origin_city='Bathtub', production='retail', url='http://example.com/', description='Pretty bad beers.', ) self.beer_style = bdb_models.BeerStyle.objects.create(name='Porter', ) self.beer_type = bdb_models.BeerType.objects.create( name='Moonshine Porter', brewer=self.brewer, style=self.beer_style, calories_oz=3.0, carbs_oz=10.0, abv=0.05, ) self.keg_vol = units.UnitConverter.Convert(2.0, units.UNITS.Liter, units.RECORD_UNIT) self.keg_size = models.KegSize.objects.create( name='Tiny Keg', volume_ml=self.keg_vol, ) self.keg = models.Keg.objects.create( site=self.site, type=self.beer_type, size=self.keg_size, start_time=datetime.datetime(2000, 4, 1), end_time=datetime.datetime(2000, 5, 1), status='online', description='Our first keg!', origcost=99.0, ) self.tap = models.KegTap.objects.create( site=self.site, name='Test Tap', meter_name='test', ml_per_tick=(1000.0 / 2200.0), current_keg=self.keg, ) self.user = models.User.objects.create(username='******', ) self.user2 = models.User.objects.create(username='******', )
def cancel_drink(request): #if request.method != 'POST': # raise kbapi.BadRequestError, 'Method not supported at this endpoint' #form = forms.DrinkCancelForm(request.POST) form = forms.CancelDrinkForm(request.GET) if not form.is_valid(): raise kbapi.BadRequestError, _form_errors(form) cd = form.cleaned_data b = KegbotBackend(site=request.kbsite) try: res = b.CancelDrink(seqn=cd.get('id'), spilled=cd.get('spilled', False)) return protolib.ToProto(res, full=True) except backend.BackendError, e: raise kbapi.ServerError(str(e))
def handle(self, **options): installed = False try: b = KegbotBackend() installed = defaults.db_is_installed() except backend.BackendError, e: pass
def setUp(self): self.site, created = models.KegbotSite.objects.get_or_create( name='default') self.backend = KegbotBackend(site=self.site) test_usernames = ('user1', 'user2', 'user3') self.users = [ self.backend.CreateNewUser(name) for name in test_usernames ] self.taps = [ self.backend.CreateTap('tap1', 'kegboard.flow0', ml_per_tick=1 / 2200.0), self.backend.CreateTap('tap2', 'kegboard.flow1', ml_per_tick=1 / 2200.0), ]
def assign_auth_token(request, auth_device, token_value): if not request.POST: raise kbapi.BadRequestError("POST required.") form = forms.AssignTokenForm(request.POST) if not form.is_valid(): errors = _form_errors(form) raise kbapi.BadRequestError(errors) b = KegbotBackend(site=request.kbsite) username = form.cleaned_data["username"] try: tok = b.GetAuthToken(auth_device, token_value) user = b._GetUserObjFromUsername(username) if not user: raise kbapi.BadRequestError("User does not exist") if tok.user != user: if tok.user: raise kbapi.BadRequestError("Token is already bound to a user") tok.user = user tok.save() return tok except backend.NoTokenError: return b.CreateAuthToken(auth_device, token_value, username=username)
def assign_auth_token(request, auth_device, token_value): if not request.POST: raise kbapi.BadRequestError('POST required.') form = forms.AssignTokenForm(request.POST) if not form.is_valid(): errors = _form_errors(form) raise kbapi.BadRequestError(errors) b = KegbotBackend(site=request.kbsite) username = form.cleaned_data['username'] try: tok = b.GetAuthToken(auth_device, token_value) user = b._GetUserObjFromUsername(username) if not user: raise kbapi.BadRequestError("User does not exist") if tok.user != user: if tok.user: raise kbapi.BadRequestError("Token is already bound to a user") tok.user = user tok.save() return tok except backend.NoTokenError: return b.CreateAuthToken(auth_device, token_value, username=username)
def get_auth_token(request, auth_device, token_value): b = KegbotBackend(site=request.kbsite) tok = b.GetAuthToken(auth_device, token_value) return tok
class CoreModelsTestCase(unittest.TestCase): def setUp(self): models.KegbotSite.objects.filter(name='default').delete() self.site, created = models.KegbotSite.objects.get_or_create( name='default') self.backend = KegbotBackend(site=self.site) self.brewer = bdb_models.Brewer.objects.create( name='Moonshine Beers', country='USA', origin_state='Anystate', origin_city='Bathtub', production='retail', url='http://example.com/', description='Pretty bad beers.', ) self.beer_style = bdb_models.BeerStyle.objects.create(name='Porter', ) self.beer_type = bdb_models.BeerType.objects.create( name='Moonshine Porter', brewer=self.brewer, style=self.beer_style, calories_oz=3.0, carbs_oz=10.0, abv=0.05, ) self.keg_vol = units.UnitConverter.Convert(2.0, units.UNITS.Liter, units.RECORD_UNIT) self.keg_size = models.KegSize.objects.create( name='Tiny Keg', volume_ml=self.keg_vol, ) self.keg = models.Keg.objects.create( site=self.site, type=self.beer_type, size=self.keg_size, start_time=datetime.datetime(2000, 4, 1), end_time=datetime.datetime(2000, 5, 1), status='online', description='Our first keg!', origcost=99.0, ) self.tap = models.KegTap.objects.create( site=self.site, name='Test Tap', meter_name='test', ml_per_tick=(1000.0 / 2200.0), current_keg=self.keg, ) self.user = models.User.objects.create(username='******', ) self.user2 = models.User.objects.create(username='******', ) def tearDown(self): self.user.delete() self.user2.delete() self.keg.delete() del self.keg_vol self.beer_type.delete() self.beer_style.delete() self.brewer.delete() def testKegStuff(self): """Test basic keg relations that should always work.""" self.assertEqual( self.keg.size.volume_ml, units.Quantity(2.0, units.UNITS.Liter).InMilliliters()) self.assertEqual(self.keg.type.brewer.name, "Moonshine Beers") self.assertEqual(self.keg.served_volume(), 0.0) self.assertEqual(self.keg.remaining_volume(), self.keg_vol) def testDrinkAccounting(self): vol = units.Quantity(1200) d = self.backend.RecordDrink( tap_name=self.tap.meter_name, ticks=1200, username=self.user.username, ) print d self.assertEqual(self.keg.served_volume(), d.volume_ml) def testDrinkSessions(self): """ Checks for the DrinkingSession records. """ u1 = self.user u2 = self.user2 vol = units.Quantity(1200) drinks = {} base_time = datetime.datetime(2009, 1, 1, 1, 0, 0) ticks = volume = vol.InKbMeterTicks() td_10m = datetime.timedelta(minutes=10) td_200m = datetime.timedelta(minutes=200) td_190m = td_200m - td_10m self.assertEqual(models.Drink.objects.all().count(), 0) self.assertEqual(models.DrinkingSession.objects.all().count(), 0) ### User 1 # t=0 print self.backend.RecordDrink( tap_name=self.tap.meter_name, ticks=1200, username=u1.username, pour_time=base_time, ) # t=10 print self.backend.RecordDrink( tap_name=self.tap.meter_name, ticks=1200, username=u1.username, pour_time=base_time + td_10m, ) # t=200 print self.backend.RecordDrink( tap_name=self.tap.meter_name, ticks=1200, username=u1.username, pour_time=base_time + td_200m, ) drinks_u1 = u1.drinks.all().order_by('time') ### User 2 # t=0 print self.backend.RecordDrink( tap_name=self.tap.meter_name, ticks=1200, username=u2.username, pour_time=base_time, ) # t=200 print self.backend.RecordDrink( tap_name=self.tap.meter_name, ticks=1200, username=u2.username, pour_time=base_time + td_200m, ) # t=190 print self.backend.RecordDrink( tap_name=self.tap.meter_name, ticks=1200, username=u2.username, pour_time=base_time + td_190m, ) drinks_u2 = u2.drinks.all().order_by('time') u1_chunks = u1.session_chunks.all().order_by('start_time') self.assertEqual(len(u1_chunks), 2) u2_chunks = u2.session_chunks.all().order_by('start_time') self.assertEqual(len(u2_chunks), 2) s1, s2 = models.DrinkingSession.objects.all().order_by( 'start_time')[:2] SESSION_DELTA = datetime.timedelta( minutes=kb_common.DRINK_SESSION_TIME_MINUTES) # session 1: should be 10 minutes long as created above self.assertEqual(s1.start_time, drinks_u1[0].start_time) self.assertEqual(s1.start_time, drinks_u1[1].end_time) self.assertEqual(s1.drinks.valid().filter(user=u1).count(), 2) self.assertEqual(s1.drinks.valid().filter(user=u2).count(), 1) # session 2: at time 200, 1 drink self.assertEqual(s2.start_time, base_time + td_190m) self.assertEqual(s2.end_time, base_time + td_200m) self.assertEqual(s2.drinks.valid().filter(user=u1).count(), 1) self.assertEqual(s2.drinks.valid().filter(user=u2).count(), 2) # user2 session2: drinks are added out of order to create this, ensure times # match u2_c2 = u2_chunks[1] self.assertEqual(u2_c2.start_time, base_time + td_190m) self.assertEqual(u2_c2.end_time, base_time + td_200m) # Now check DrinkingSessions were created correctly; there should be # two groups capturing all 4 sessions. all_groups = models.DrinkingSession.objects.all().order_by( 'start_time') self.assertEqual(len(all_groups), 2) self.assertEqual(all_groups[0].start_time, base_time) self.assertEqual(all_groups[0].end_time, base_time + td_10m) self.assertEqual(all_groups[0].user_chunks.all().count(), 2) self.assertEqual(all_groups[1].start_time, base_time + td_190m) self.assertEqual(all_groups[1].end_time, base_time + td_200m) self.assertEqual(all_groups[1].user_chunks.all().count(), 2)
class StatsTestCase(unittest.TestCase): def setUp(self): self.site, created = models.KegbotSite.objects.get_or_create( name='default') self.backend = KegbotBackend(site=self.site) test_usernames = ('user1', 'user2', 'user3') self.users = [ self.backend.CreateNewUser(name) for name in test_usernames ] self.taps = [ self.backend.CreateTap('tap1', 'kegboard.flow0', ml_per_tick=1 / 2200.0), self.backend.CreateTap('tap2', 'kegboard.flow1', ml_per_tick=1 / 2200.0), ] #self.drinks = [] #for user in self.users: # for amt in (100, 200, 300): # d = self.backend.RecordDrink('kegboard.flow0', ticks=amt, # volume_ml=amt, username=user.username, do_postprocess=False) # self.drinks.append(d) def assertProtosEqual(self, expected, actual): d1 = ProtoMessageToDict(expected) d2 = ProtoMessageToDict(actual) msg = '' for k, v in d1.iteritems(): if k not in d2: msg += 'Value for %s not present in actual. \n' % k elif v != d2[k]: msg += 'Values for %s differ: expected "%s", actual "%s". \n' % ( k, v, d2[k]) for k, v in d2.iteritems(): if k not in d1: msg += 'Value for %s not present in expected. \n' % k if msg: self.fail(msg) def _getEmptyStats(self): s = models_pb2.Stats() s.last_drink_id = 0 s.total_volume_ml = 0.0 s.total_pours = 0 s.average_volume_ml = 0.0 s.greatest_volume_ml = 0.0 s.greatest_volume_id = 0 return s def testStuff(self): builder = stats.SystemStatsBuilder(None) empty_stats = models_pb2.Stats() system_stats_d0 = builder.Build() self.assertEquals(empty_stats, system_stats_d0) # Record a new drink and verify stats. pour_time = datetime.datetime(2011, 05, 01, 12, 00) self.backend.RecordDrink('kegboard.flow0', ticks=100, volume_ml=100, username='******', pour_time=pour_time, do_postprocess=False) drink1 = models.Drink.objects.get(seqn=1) expected = self._getEmptyStats() expected.last_drink_id = 1 expected.total_volume_ml = 100.0 expected.total_pours = 1 expected.average_volume_ml = 100.0 expected.greatest_volume_ml = 100.0 expected.greatest_volume_id = 1 expected.has_guest_pour = False d = expected.volume_by_day_of_week.add() d.weekday = "0" # Sunday d.volume_ml = 100 u = expected.volume_by_drinker.add() u.username = "******" u.volume_ml = 100 y = expected.volume_by_year.add() y.year = 2011 y.volume_ml = 100 expected.registered_drinkers.append("user1") expected.sessions_count = 1 system_stats_d1 = stats.SystemStatsBuilder(drink1).Build() self.assertProtosEqual(expected, system_stats_d1) # Pour another drink self.backend.RecordDrink('kegboard.flow0', ticks=200, volume_ml=200, username='******', pour_time=pour_time, do_postprocess=False) drink2 = models.Drink.objects.get(seqn=2) # Adjust stats expected.last_drink_id = 2 expected.total_volume_ml = 300.0 expected.total_pours = 2 expected.average_volume_ml = 150.0 expected.greatest_volume_ml = 200.0 expected.greatest_volume_id = 2 d = expected.volume_by_day_of_week[0] d.volume_ml += 200 u = expected.volume_by_drinker[0] u.volume_ml += 200 y = expected.volume_by_year[0] y.volume_ml += 200 system_stats_d2 = stats.SystemStatsBuilder(drink2).Build() self.assertProtosEqual(expected, system_stats_d2) # Build the same stats incrementally and verify identical result. system_stats_d2_inc = stats.SystemStatsBuilder( drink2, system_stats_d1).Build() self.assertProtosEqual(system_stats_d2, system_stats_d2_inc)