From 01e132628c3d846ae8f55cb8c81adec3d64332b4 Mon Sep 17 00:00:00 2001 From: Fedorov Vladimir Date: Tue, 14 Mar 2023 01:15:11 +0700 Subject: [PATCH] update calories --- main.go | 32 +++++++++++++++++++++++++++++-- main_test.go | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+), 2 deletions(-) create mode 100644 main_test.go diff --git a/main.go b/main.go index 3ca7e89..c9fb218 100644 --- a/main.go +++ b/main.go @@ -20,6 +20,10 @@ var ( "Отжимания", "Пресс", } + caloriesMap = map[string]int{ + "чай": 79, + "яблоко": 100, + } ) const ( @@ -198,7 +202,7 @@ func run() { _, _ = bot.Send(msg) continue case db.UserStateEat: - count, err := strconv.Atoi(text) + count, err := calcCalories(text) if err != nil { log.Println(err) continue @@ -211,7 +215,7 @@ func run() { _, _ = bot.Send(tgbot.NewMessage(chatID, "Все фигня, давай по новой")) continue } - _, _ = bot.Send(tgbot.NewMessage(chatID, fmt.Sprintf("Калории, фу, %s, записал.", text))) + _, _ = bot.Send(tgbot.NewMessage(chatID, fmt.Sprintf("Калории, фу, %d, записал.", count))) if err := dataBase.SetStatusToChat(chatID, db.UserStateNone); err != nil { log.Println(err) } @@ -246,6 +250,30 @@ func run() { } } +func calcCalories(text string) (int, error) { + count, ok := caloriesMap[strings.ToLower(text)] + if ok { + return count, nil + } + arr := strings.Split(text, " ") + if len(arr) == 2 { + coun1, err := strconv.Atoi(arr[0]) + if err != nil { + return 0, nil + } + count2, err := strconv.Atoi(arr[1]) + if err != nil { + return 0, nil + } + return coun1 * count2 / 100, nil + } + count, err := strconv.Atoi(text) + if err != nil { + return 0, nil + } + return count, nil +} + func sendGoToChat(bot *tgbot.BotAPI, dataBase *db.DB, chatID int64) { msg := tgbot.NewMessage(chatID, "Давай немного разомнемся, выбирай:") row := tgbot.NewKeyboardButtonRow() diff --git a/main_test.go b/main_test.go new file mode 100644 index 0000000..81f47e6 --- /dev/null +++ b/main_test.go @@ -0,0 +1,54 @@ +package main + +import "testing" + +func TestCalcCalories(t *testing.T) { + t.Parallel() + tests := []struct { + name string + text string + want int + wantErr bool + }{ + { + "empty text", + "", + 0, + false, + }, + { + "1 text", + "1", + 1, + false, + }, + { + "2 5 text", + "20 50", + 10, + false, + }, + { + "чай text", + "чай", + 39, + false, + }, + } + + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + count, err := calcCalories(tt.text) + if (err != nil) != tt.wantErr { + t.Errorf("error calc calories: %v", err) + return + } + if count != tt.want { + t.Errorf("error count: %v", err) + return + } + }) + } +}