Home > database >  How do i apply unit testing to check leap year with golang?
How do i apply unit testing to check leap year with golang?

Time:10-25

I want to do unit testing and check if dates are leap year or not, how do i apply unit testing in this case, i don’t t know how to go about it in this situation?

I have already created my function and it works fine, i also have a JSON file that contains list of people and their Birthday dates !

Would appreciate some feedback or advice on how to tackle this problem ! Thanks

BD.go:

 package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
    "os"
    "time"
)

// Users struct which contains
// an array of users
type Users struct {
    Users []User `json:"users"`
}

// User struct which contains a name
// a type and a list of social links
type User struct {
    Firstname  string `json:"fname"`
    Secondname string `json:"lname"`
    Date       string `json:"date"`
}

var users Users
var user User

func Birthday() {
    // Open our jsonFile
    jsonFile, err := os.Open("users.json")
    // if we os.Open returns an error then handle it
    if err != nil {
        fmt.Println(err)
    }

    fmt.Println("Successfully Opened users.json")
    // defer the closing of our jsonFile so that we can parse it later on
    defer jsonFile.Close()

    // read our opened xmlFile as a byte array.
    byteValue, _ := ioutil.ReadAll(jsonFile)

    // we initialize our Users array
    // we unmarshal our byteArray which contains our
    // jsonFile's content into 'users' which we defined above
    json.Unmarshal(byteValue, &users)
    IsLeapYear("users.json")
}

func IsLeapYear(user string) bool {
    // we iterate through every user within our users array and
    // print out the user Type, their name
    for i := 0; i < len(users.Users); i   {
        date, err := time.Parse("2006/01/02", users.Users[i].Date)
        if err != nil {
            date, err = time.Parse("2006-01-02", users.Users[i].Date)
            // date, err = time.Parse("2006 01 02", users.Users[i].Date)
            if err != nil {
                log.Fatal("unsupported date format:", err)
            }
        }

        // check if the date is a leap year, ex: 29 is not a leap year but 28th is !

        if date.Day()%400 == 0 || (date.Day()%4 == 0 && date.Day()%100 != 0) {
            fmt.Println("User First Name: "   users.Users[i].Firstname)
            fmt.Println("User Second Name: "   users.Users[i].Secondname)
            fmt.Println("User Date: "   users.Users[i].Date)
            fmt.Println(users.Users[i].Date, "is a Leap Year ✨ ✨ ✨")

            // checking if the date.day matches today's date
            if date.Day() == time.Now().Day() {
                fmt.Println("User First Name: "   users.Users[i].Firstname)
                fmt.Println("User Date: "   users.Users[i].Date)
                fmt.Println("TODAY IS YOUR BIRTHDAY, Happy birthday !!!           
  • Related