go – Testing a template function in GoLang using mocking – making it DRY & easy to follow

I’m wondering how to organise test functions using mocks for GoLang drier & easier to follow.

Function

I have a template function that is very similar to ACF’s getField:

  • It take’s in a string (field name) & the post ID.
  • It checks if the ID exists and the obtains the post by ID (the f.store.Posts belongs to the fields struct)
  • If the post doesn’t exist or if the fields could not be unmarshalled it will return an empty string.
func (f *fields) getField(field string, id ...int) interface{} {

    fields := f.fields
    if len(id) > 0 {
        post, err := f.store.Posts.GetById(id(0))
        if err != nil {
            return ""
        }
        var m map(string)interface{}
        if err := json.Unmarshal(*post.Fields, &m); err != nil {
            return ""
        }
        fields = m
    }

    val, found := fields(field)
    if !found {
        return ""
    }

    return val
}

Testing

From the function, presumably I need to test if, The post exists, the json could be unmarshalle or if the field exists.
I have started to use github.com/golang/mock/gomock but am finding it confusing!
In each of the test functions below I create a new controller and mockPost, add assigning the fields Post to it.


func TestGetField(t *testing.T) {
    f, err := helper(`{"text": "content"}`)
    if err != nil {
        t.Error(err)
    }

    if field := f.getField("text"); field == "" {
        t.Errorf(test.Format("content", nil))
    }

    if field := f.getField("wrongval"); field != "" {
        t.Errorf(test.Format("", field))
    }
}

func TestGetField_Post(t *testing.T) {
    f, err := helper("{}")
    if err != nil {
        t.Error(err)
    }

    controller := gomock.NewController(t)
    defer controller.Finish()

    data := ()byte(`{"posttext": "postcontent"}`)
    mockPost := domain.Post{
        Id:     2,
        Fields: (*json.RawMessage)(&data),
    }

    posts := mocks.NewMockPostsRepository(controller)
    f.store.Posts = posts
    posts.EXPECT().GetById(2).Return(mockPost, nil)

    field := f.getField("posttext", 2)
    if field != "postcontent" {
        t.Errorf(test.Format("postcontent", field))
    }
}

func TestGetField_No_Post(t *testing.T) {
    f, err := helper("{}")
    if err != nil {
        t.Error(err)
    }

    controller := gomock.NewController(t)
    defer controller.Finish()

    posts := mocks.NewMockPostsRepository(controller)
    var mockErr = fmt.Errorf("No post")
    posts.EXPECT().GetById(gomock.Any()).Return(domain.Post{}, mockErr)
    f.store.Posts = posts

    field := f.getField("text", 1)

    if field != "" {
        t.Errorf(test.Format("", field))
    }
}

func TestGetField_Invalid_JSON(t *testing.T) {
    f, err := helper("{}")
    if err != nil {
        t.Error(err)
    }

    controller := gomock.NewController(t)
    defer controller.Finish()

    data := ()byte(`"text "content"`)
    mockPost := domain.Post{
        Id:     1,
        Fields: (*json.RawMessage)(&data),
    }

    posts := mocks.NewMockPostsRepository(controller)
    posts.EXPECT().GetById(1).Return(mockPost, nil)
    f.store.Posts = posts

    field := f.getField("text", 1)
    if field != "" {
        t.Errorf(test.Format("", field))
    }
}


func TestHasField(t *testing.T) {
    f, err := helper(`{"text": "content"}`)
    if err != nil {
        t.Error(err)
    }

    if has := f.hasField("text"); !has {
        t.Errorf(test.Format(true, has))
    }

    if has := f.hasField("wrongval"); has {
        t.Errorf(test.Format(true, has))
    }
}

Feedback

  • Without using the mock package, how would you approach this?
  • Are there any areas for improvement with the current codebase?
  • Is there away to consolidate any of the testing methods? It seems quite long winded for such a short function

Making a new font in Linux

I am new to this world of fonts (fontforge etc.). I have a new font of devanagri(indian) with me which I want to use in linux. I came across fontforge however I am not very clear about all the steps.
My question
Can anybody help me understand what the process of making fonts is?
It would be helpful if you can elaborate stepwise.

Making an HYIP program is now very simple and easy – HYIPs

Making an HYIP program is now very simple and easy. Just get a complete package Of HYIP from Zeligz Web Store at an affordable price and you will get the working website within 24 hours. Their HYIP Script is the most advanced in the HYIP market. With the script, you will get many other facilities and features. They have a live support system so you can contact them at any time for any support. Visit their website and get the details now.
 

Groupon Clone APP – Money Making Business Idea

One of the best way to make money to launch your own Coupon Platform like GROUPON. Groupon is the giant coupon company gloablly. Make a huge Profit by owning Groupon like company. Energing various advance technlogies to build a coupon business .Mail to sales@cashbackscript.net
 
Groupon Clone App is one of the omnipotent for monetizing a website. Coupons & Deals Business has raised in monstrous pace among the Business Market Place. 
 

.

Earn watching videos – Other Money Making Opportunities

Gram free is a video watch and earn platform where you earn cash for seeing videos. For this you visit this site.

HTTPS://zee.gl/6dmfE

Click this link and join to get paid.

Along with this site another site will also make you earn to click the link. All you has to do is join by clicking this website link and start earn

HTTPS://zee.gl/ref/Fxj864

 

 

 

 

 

google cloud platform – Something is making API calls to my GCP project

I started using Google Cloud Platform for a couple of months, however, yesterday the billing price started to grow, even though it is very little, it does it constantly and I have noticed that the API calls have also remained, Even though I have not been using the service, it is worth mentioning that I only have a virtual machine that I turn on sporadically.

The “Storage PD Capacity” criterion in billing is growing, apparently I exceeded the free storage limit, but the VM remains at 5GB of use.

Yesterday, I accidentally pressed a Compute Engine monitoring button and apparently a log service was activated, which I deactivated from the API’s panel, but what was explained above remains.

API calls since yesterday

Dollarfuture –dollarfuture.io – Other Money Making Opportunities

Disclaimer: I am not the admin or owner of the project, I don’t know the admin personally

242660752_001Dollarfutureforum.thumb.JPG.24c7d6eb2b5d6c2898a433a501e744f0.JPG

Start: Oct 15, 2020

Payouts: Instant

Ref-offer : 100% of first two referrals

 

About:

Dollarfuture is a 100% Decentralized Crowdfunding Dapp

Auto Referral Feeder (ARF) A Matrix Project Where No One Get Stucked, First Tokenized Smart Contract Ever. Creator team has a unique role for the token which will boost the use case and subsequently increase it value in the open market. There is no pre-own, pre-sale or team allocation, meaning DLF Tokens are essentially owned by the community. Members and Users decide the value Simple. Hint : Hold !

 

plans:

110 TRX to join

3X and 4X of your invested amound.

 

Min/Max: 110TRX / 6400 TRX

 

Payment systems: TRON

 

                                                                            

                                                                     ️Register

https://dollarfuture.io/Auth/Register?refferal=TKtC4skaUG7CBcuU8DAQS1JPuB4ixVbCLA

             

 

For registration this link need to be copied and pasted in the DApp browser of a tron wallet not just to be clicked on, Wallets to be used for registration, Tronlink wallet and Token pocket wallet

1057281548_Dollarfuturejoin..thumb.jpg.b8c96e4cf829c96dad3ca6c67debd6c6.jpg

Join Official Telegram Group:  T.Me

 

TECHNICAL DETAILS (information from ISP resources):

 

Domain Registrar: NameCheap, Inc. 

 

Registration Date: Aug 31, 2020, 12:58 PM 1 month 1 week 5 days ago

 

Expiration Date: Aug 31, 2021, 12:58 PM 10 months 1 week 2 days from now

 

Domain Status: clienttransferprohibited

                             servertransferprohibited

 

 


Edited by Hyipdealer

T.Me added

.(tagsToTranslate)paying(t)tron(t)smartcontract