add products
continuous-integration/drone/push Build is passing

This commit is contained in:
2023-04-09 13:31:01 +07:00
parent 12ffc3461f
commit c3d00b5dec
6 changed files with 14 additions and 14 deletions
+51
View File
@@ -0,0 +1,51 @@
package eat_bot_state
import (
"strconv"
"strings"
)
var (
productsMap = map[string]struct {
caloriesIn100G int
awgWeightG int
}{
"чай": {caloriesIn100G: 65, awgWeightG: 200},
"яблоко": {caloriesIn100G: 52, awgWeightG: 242},
"хлеб": {caloriesIn100G: 245, awgWeightG: 35},
"огурец": {caloriesIn100G: 15, awgWeightG: 20},
"помидор": {caloriesIn100G: 18, awgWeightG: 18},
}
)
func calcCalories(text string) (int, error) {
product, ok := productsMap[strings.ToLower(text)]
if ok {
return product.caloriesIn100G * product.awgWeightG / 100, nil
}
arr := strings.Split(text, " ")
if len(arr) == 2 {
product, ok := productsMap[strings.ToLower(arr[0])]
if ok {
count, err := strconv.Atoi(arr[1])
if err != nil {
return 0, nil
}
return product.caloriesIn100G * count / 100, nil
}
count1, err := strconv.Atoi(arr[0])
if err != nil {
return 0, nil
}
count2, err := strconv.Atoi(arr[1])
if err != nil {
return 0, nil
}
return count1 * count2 / 100, nil
}
count, err := strconv.Atoi(text)
if err != nil {
return 0, nil
}
return count, nil
}
@@ -0,0 +1,65 @@
package eat_bot_state
import (
"fmt"
"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",
"чай",
130,
false,
},
{
"чай 250 text",
"чай 250",
162,
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 {
fmt.Println(count, tt.want)
fmt.Println(count, tt.want)
t.Errorf("error count: %v", err)
return
}
})
}
}
@@ -4,7 +4,6 @@ import (
"fmt"
"log"
"net/http"
"valera/internal/calories"
"valera/internal/db"
"valera/internal/states"
@@ -30,7 +29,7 @@ func NewEatBotState(bot *tgbot.BotAPI, dataBase *db.DB) states.BotState {
func (s *eatBotState) Do(text string, chatInfo *db.ChatInfo, username string) error {
if chatInfo.Status == string(db.UserStateEat) {
count, err := calories.CalcCalories(text)
count, err := calcCalories(text)
if err != nil {
log.Println(err)
return nil