Showing posts with label go. Show all posts
Showing posts with label go. Show all posts

Friday, August 6, 2021

Top 5 Advanced Go Testing Techniques

 

Top 5 Advanced Go Testing Techniques

Test- driven development is an extraordinary method to keep the quality of your code high, while protecting yourself from regression and proving to yourself as well as other people that your code does what it should. Go has robust in-built testing library. If you are thinking to build or software with Go, it will be better to know the Go testing techniques so as to develop a perfect software. So here we’ll discuss strategies to level up Go testing that will save your time and effort to maintain the code. 

Top 5 Advanced Go Testing Techniques-

1. Use test suites-

Suite testing is a process of developing a test against common interface that can be used against various implementations of that interface. Here you will see how you can pass in multiple different Thinger implementations and have them run against the same tests. 

type Thinger interface {
   DoThing(input string) (Result, error)
}

// Suite tests all the functionality that Thingers should implement
func Suite(t *testing.T, impl Thinger) {
   res, _ := impl.DoThing("thing")
   if res != expected {
       t.Fail("unexpected result")
   }
}
// TestOne tests the first implementation of Thinger
func TestOne(t *testing.T) {
   one := one.NewOne()
   Suite(t, one)
}
// TestOne tests another implementation of Thinger
func TestTwo(t *testing.T) {
   two := two.NewTwo()
   Suite(t, two)
}

Tests that are written against the interface are usable by all implementations of interface to determine if the behavior requirements are met. This strategy will save time to solve the P versus NP problem. While swapping two underlying systems, you don’t need to write extra tests and it won’t break your app. Implicitly it requires that you create an interface defining the surface area of that you’re testing. By the use of dependency injection, you set up the suite from your package passing in the implementation for package.

Another great example of this in the standard library is golang.org/x/net/nettest package. It provides the means to verify a net.Conn satisfies its interface.

2. Don’t export concurrency primitives-

Go provides easy to use concurrency primitives that can sometimes causes their overuse. Mainly concerned is about channels and sync package. Some of the time, it is enticing to export a channel from your package for consumers to use. Also, it is common mistake to embed sync.Mutex without making it private. Likewise with anything, this isn’t in every case bad however it does difficulties when testing your program. When you export channels, you expose the consumer of the package to extra complexity they shouldn’t care about. When the channel is exported from a package, you open up challenges in testing for one consuming that channel. So as to test properly, the consumer needs to know about- when data is finished being sent on the channel, whether there are any errors receiving the data or not, After completion, how does the package clean up channel etc.

Consider an example of reading a queue. Here’s an example library that reads from the queue and exposes a channel for the consumer to read from. User of library wants to implement a test for their consumer: User might decide that DI(dependency injection) is a good idea for this and write messages with channel.

However, what about errors?

How to generate events to actually write into this mock that replicate the behavior of actual library you’re using? If library wrote synchronous API, then you could add this concurrency in our client code and it becomes easy to test.

Always remember that, it is easy to add concurrency in consuming package and difficult to remove once exported from a library. Don’t forget to mention in package documentation whether or not a struct/package is safe for concurrent access by various goroutines. Some of the times, it is still necessary to export channel through accessors rather than directly and force them to be ready-only or write only channels in declaration.

3. Avoid interface pollution-

Interfaces are important for testing as they are the most powerful tool in test arsenal, hence it is important to use them appropriately. Packages export an interface for consumers to use that turns leads to- consumers implementing their own mock of package implementation or the package exporting own mock. 
It will be better to consider interfaces before exporting. Mostly Programmers are tempted to export interfaces to mock out their behavior. Rather than, document that interfaces your structs satisfy just like you don’t create a hard dependency between consumer package and your own. Error package is a good example of this. When you have interface in program that you don’t want to export can use an internal/ package subtree to keep it scoped to the package. With this, we remove the concern that other consumers might depend on it and so can be flexible in the evolution of interfaces as new needs present themselves. Generally we create interfaces around external dependencies and use dependency injection to run tests locally. With this, consumer can implement small interfaces of their own, just wrapping the consumed surface of library for their own testing.

4. Make use of a separate _test package-

Generally tests in ecosystem are created in files pkg_test.go but still live in the same package: package pkg. Separate test package is a package you create in new file,   foo_test.go, in the package directory of package you want to test, foo/, with declaration package foo_test. 

You can import github.com/example/foo and some other dependencies. It enables lots of things. This is a suggested workaround for cyclic dependencies in tests, it allows developers to feel what it’s like to consume their own package.  If a package is hard to use, it will also be hard to test using this method. This strategy prevents tests by restricting access to private variables. Particularly if tests break and you’re using a separate test packages it;s almost possible that a client using the feature that broke in tests will also break when called.

This helps in keeping away from import cycles in tests. Many packages depend on other packages you wrote aside from those being tested, hence you’ll be in a situation where an import cycle occur as a natural consequence. External package sits above both packages in the package hierarchy. Taking example from the Go Programming Language(Chp. 11 Sec 2.4), net/url implements a URL parser that net/http imports for use.

But, net/url would like to test by using real use case by importing net/http. Hence net/url_test was came to focus.

Now, if you use separate test package, you may need access to unexported entities in your package where they were accessible. Most of the people hit this first while testing something time based. In such a situation you can use extra file to expose them exclusively during testing since _test.go files are excluded from regular builds.

5. Use net/http/httptest-

httptest allows you to exercise your http.Handler code without spinning up a server. It speeds up tests and allows them to run in parallel with less effort.

Here’s an example of the same test implemented using both of the methods. It saves you a considerable amount of code and resources. 

func TestServe(t *testing.T) {
   // The method to use if you want to practice typing
   s := &http.Server{
       Handler: http.HandlerFunc(ServeHTTP),
   }
   // Pick port automatically for parallel tests and to avoid conflicts
   l, err := net.Listen("tcp", ":0")
   if err != nil {
       t.Fatal(err)
   }
   defer l.Close()
   go s.Serve(l)
 res, err := http.Get("http://" + l.Addr().String() + "/?sloths=arecool")
   if err != nil {
       log.Fatal(err)
   }
   greeting, err := ioutil.ReadAll(res.Body)
   res.Body.Close()
   if err != nil {
       log.Fatal(err)
   }
   fmt.Println(string(greeting))
}
func TestServeMemory(t *testing.T) {
   // Less verbose and more flexible way
   req := httptest.NewRequest("GET", "http://example.com/?sloths=arecool", nil)
   w := httptest.NewRecorder()
 ServeHTTP(w, req)
   greeting, err := ioutil.ReadAll(w.Body)
   if err != nil {
       log.Fatal(err)
   }
   fmt.Println(string(greeting))
}

May be the biggest thing using httptest gets you is the ability to compartmentalize your test to just the function you want to test. No routers, middleware or any other side-effect coming from setting up servers, services, handler factories etc are thrown by ideas your former self thought were good.

Know the reasons to use enterprise mobile apps at- Why you should use Golang for enterprise mobile apps?

Wrap Up-

It will better to analyse the situation before applying any testing technique. The above mentioned top 5 Go testing techniques will surely help you to develop the best software. In case of any difficulty you can consult with Solace experts and get a free quote for software development. We will be happy to help you.


Tuesday, November 5, 2019

Why Golang Is Better Than Other Languages?

With the unbeatable expansion in technology, the world is also moving to uncover the absolute most pivotal revelations. GoLang, being one such progressive revelation, has overwhelmed the whole world. As GoLang walked into our lives, individuals have found a few different ways to get headways and innovation in the field of development. Golang has gained more popularity in less time as compared to other programming languages. 
In spite of the fact that for beginners golang may be slightly complex but with adequate practice, one can easily used to with this language. There is sufficient reason to go bonkers over this advanced programming language, however before demystifying them get to know some basics about GoLang. 

What you can do with Golang?

While some different languages like C, Java, and so on have strong command over the field of programming, a few new models have been introduced that can spell better outcomes for the modern computing, particularly in the cloud. The expanding ubiquity of Go for the most part owes to its lightweight and the fact that it’s reasonable for pretty much every microservices architecture. Container darling docker, as well as  Google’s Kubernetes, are also built with the use of Go. Go is also holding the ground in data science owing to its advantageous features, which the data scientists are hoping to use to acquire increasingly successful outcomes.
Being a profoundly advanced programming language, GoLang can facilitate the developers in various manners, which additionally incorporate native concurrency, garbage collection etc. While utilizing Go, a developer need not depend on a few other native capabilities to limit the need of composing codes to fix memory leakage, and so on. Some of different features offered by GoLang can fit flawlessly with data science and microservices architectures.
As a result of these previously mentioned advantages, Go is progressively being used by legions of companies everywhere throughout the globe. An Application Programming Interface for the Tensorflow has been incorporated, and products,such as Pachyderm are being created with using Go. There are a series of parts of Cloud Foundry that have been written in GoLang too. Also, the interesting thing is that this list is normally including various names composed with the help of Go. To know the comparison between Python and Go, just go through- Python vs Go : Which one to choose?

What Makes GoLang Absolutely Irreplaceable?

It was not exceptionally long that GoLang had set its journey to bring an improvement and also reduce some of the long-standing issues of the development industry. In the journey of giving the millennial developers a unified and consistent experience of development, Go appeared, and as time passes, it’s carving a niche for itself without a doubt. Be that as it may, is it worth the whole buzz? Is Go genuinely irreplaceable? Is it capable of staying ahead in technology race? Let’s find it out.

Simplicity is the Major USP of GoLang-

Simplicity is unsurpassable and GoLang has absolutely taken it to the next level. Numerous successful programming languages, for example, Rust, Scala, and so on are full of different complex features. Likewise, they have spelled amazing outcomes in development by having provided advanced memory management and type systems. These programming languages have absolutely taken the mainstream languages of their time, for example, Java, C#, C++, and so forth., and boosted their overall capabilities. Having taken a different and simpler way, GoLang has effectively eliminated many of such features, yet, for quite a few reasons. The following are some features and capacities that Go has eliminated:

1. No Generics-

Generics or templates allude to the pillar of various programming languages. By including the complex and error messages related to  generics, they can frequently be obscure to understand. By having chosen to hold back on this part, the Go developers have made it simple to work with it. Without a doubt, it has been an extremely disputable yet a savvy decision taken by the designers.

2. Single Executable-

There is very discrete runtime library in GoLang. It is capable of generating a single executable that one can deploy by copying. Thanks to this for eliminating the risk of version mismatches or dependencies. Additionally, it could be an incredible help for container based development projects.

3. No Dynamic Libraries-

There has been a slight change in 1.8 version of GoLang, as now the developers can load dynamic libraries in it by plug-in packages. But, as this feature was not in GoLang from the get go, it’s as yet considered as an extension for the extraordinary features.

Go Owes its Popularity to Goroutines-

From an efficient perspective, Goroutines is regarded as one of the most interesting parts of GoLang. It can allow the experts to harness the capabilities of multicore machines in a helpful manner.

1. CSP-

The establishment of GoLang’s concurrency model is C. A. R. The prime thought is to misdirect any kind of synchronization over the shared memory between a few threads of execution that is work-intensive and mistake inclined.

2. Synchronize Go-routines-

Another powerful method to wait for goroutines is to utilize sync groups. One can declare a wait group object and along these lines pass it to each goroutine that is responsible for calling its Done() techniques when it’s totally done.

3. Channels-

Channels can permit goroutines to exchange data easily. One can make a channel and pass it on to a goroutine. The user can not just write the channel, yet in addition read from it.

Handles Error Seamlessly-

The whole concept of error handling is dealt with diversely by GoLang. By convention functions, GoLang will never fail at returning an error as its final return values. Despite the fact that one can’t return errors from a go-routine, he/ she can convey them to the world outside through a few different mediums.
It’s to be sure a decent practice to pass an error channel to a go routine. The users can likewise write errors to the database, log records or call remote services while utilizing GoLang.

Conclusion-

Attributable to the exponential expansion in technology, the concept of software deployment as well as conveyance has changed all things to a high extent. The Microservices architecture has played a key job in unlocking the application agility. The vast majority of the new-age applications are designed such that they can be native to cloud and also they can exploit diverse cloud services provided by the cloud platforms. There are many programming languages with its own features. But, being a perfectly engineered programming language, GoLang is structured so that it can fit such new imperatives.
Composed for the cloud, GoLang has increased a lot of popularity because of its development and mastery of concurrent operations. In the course of recent years, Go has seen a stunning climb in its popularity, particularly for modern databases. Despite the fact that the huge part of Go’s soaring fame is related with Google’s support, its different approach in developed has played the primary motivation to add to its overall popularity.
Are you looking to develop enterprise software or mobile app for your business? Solace developers are expert in go development. We at Solace believe in the benefits and effectiveness of using frameworks for go development. We will provide the best solution to bring your company the success it deserves. Feel free to contact us for any app development.

Friday, November 1, 2019

Which Frameworks You Can Use For Development In Go Language?

Google’s Go programming language is gaining more popularity among developer’s community than others. It is a powerful language to write API and web development services also. The Go programming language is an open source project to make programmers more productive. Go is expressive, concise, clean, and efficient. It is easy to learn for beginner developers. Various web development organizations all over the world have been pulled in by the fascinating features and need to make the development procedure more productive. If you are new to web development you can see, How you should choose technology stack for Web Development?
Go language is fast and compiled to fast running local code. Being the top decision of the standard developers, it causes them to make more proficient, reliable and basic programming effectively. Go is additionally broadening the clients by its scalability and concurrency. The optimization possibility enable you to eliminate any measure of code composing and composing one of a kind APIs without compromising the usefulness. This compiled language plays out a code check preceding the run time. Here you can see a list of web frameworks to use for web development in Go language.  

Top 9 Web Frameworks For Development In Go Language-

1. Martini-

Martini is a lightweight web framework and also easy to integrate with third-party support. It’s flexibility helps to extend the capabilities with additional libraries. It goes about as an ecosystem instead of as a framework. To undergo loads of functions with negligible overhead Martini is used. You can develop for web applications using this framework. This framework gives some fundamental prerequisites, for example, routing, exception dealing and common tricks to do middleware. It offers support for wildcards, variable parameters, regex stricture and some more. Martini is useful to accomplish things like infusing dynamic informational indexes into handlers relying upon sorts. Despite the fact that this is a common feature in Ruby frameworks. Martini is popular in the Golang community. Martini has a little network, which is extremely active and has in excess of twenty plug-ins with many add ons.

2. Gin Gonic-

This web framework has a similar API like Martini however it performs better without a doubt. In the event that you have just utilized Martini, you know about Gin Gonic. Else, it will simply take 10 minutes to enable you to learn Gin. Truly, it’s that much easy and simple. The traditionalist Gin Gonic structure consolidates only the most significant features and libraries. This makes it perfect to build highly performing REST APIs. In addition, this is multiple times speedier than Martini framework. Regardless of if you add  rendering, JSON validation, nested groups, and middleware, despite everything it keeps up its definitive functionality. This structure uses httprouter, the fastest HTTP router for Golang language.

3. Beego-

In certain regards, we found that Beego is like the all-inclusive Django site framework for Python. It brags a broad array of features which are common to web applications and arranged into 8 modules which can be either avoided or used as required. Aside from the general MVC elements appeared in maximum web frameworks, it additionally fuses an ORM (Object-Relationship Map) to access information, session handling tools, an in-built cache handler, libraries for general tasks with HTTP components, and logging systems.

4. Net/HTTP-

You may realize this is the one framework you should require on the off chance that you read the Go mailing lists. Developers normally build up the entire XMPP server with just HTTP or net and it performs appropriately. By the by, complicated web applications typically require middleware. What’s more, there are some attractive projects that allowed you to mix and match middleware from other Golang web frameworks with the standard HTTP or net. Certainly, this network is huge because the clients can utilize bits again from heaps of different tasks. Nevertheless, it includes a confined interface and no standard method for maximizing middleware is characterized by it. The routing isn’t so amazing so you basically utilize a framework alongside it.

5. Buffalo-

If you use this framework, then it will be the high start for your project. This framework is fast and you can easily develop a web app either be it front end or back end app development. With the Hot reloading feature, the dev command will consequently observe the .html and .go files to restart and redevelop your binary. Buffalo is beyond the expectations of a framework. It is a coordinated web development ecosystem with direct guidance for the entire web development.

6. Web.Go-

This framework offers extra functionality for Go with its free routing system. It works as a productive framework compared with to simple listing routing. It permits routing through relations instead of the use. Web. Go is offers impressive functions and proficient routing. Web. Go is not difficult to utilize and  also is a lightweight framework intended to be fundamental and can be utilized from various perspectives as of your prerequisites.

7. Mango-

The measured quality is the best thing with respect to this web framework. You can choose from various libraries to fuse in your project. This framework helps you to develop reusable modules of HTTP functionality easily and rapidly. Also it includes a list of apps and middleware into one HTTP server object for keeping your code autonomous.

8. Gorilla-

Gorilla is conceivably the longest and biggest running Go web framework. This modular framework can have as little or however much as possible for the clients. This is incredible to utilize because many components can be reused with legitimately net/HTTP library. It features robust web sockets without use of a third party service such as Pusher.

9. Gocraft-

This framework is strong and also provides scalable and quick routing functionality. Routing is added by it to the HTTP or net package from the standard library. Gocraft is a Go mux custom middleware bundle which boasts reflection and casting capacities so you can statically type your code. 
Additionally, you can compose your own or include additional functionality with the inbuilt middleware. As developers give the most priority to the performance, Gocraft is an astounding alternative for them. Moreover, it’s extremely simpler to write backend web applications with the utilization of the mentioned framework.

Wrap up-

The above frameworks are listed considering the prerequisites of the development in Golang. We suggest you to oversee the set of  features every framework offer before you start your project. As the projects differ, the necessities vary. Some features are valuable on all grounds in a like manner, for other unique prerequisites you may need to experiment to adopt a framework. Golang is simpler and easy to utilize. In this way, testing won’t set aside a lot of effort for you. It is always better to go with a framework that has great community support and well- proven third- party implementations.  On the off chance that you are a developer and need to develop in Golang or need to employ a Golang developer, you can utilize any of the frameworks from the list of your future projects.
Are you looking to develop enterprise software or mobile app for your business? Solace developers are expert in go development. We at Solace believe in the benefits and effectiveness of using frameworks for go development. We will provide the best solution to bring your company the success it deserves. Feel free to contact us for any app development.

Thursday, October 10, 2019

Python vs Go: Which one to choose?

Preceding starting any project, it is necessary to choose the best language for its development. Most of the time, this selection come at a point to choose between Python and Golang. Here we will help you to choose the best language between Python and GoLang on the basis of comparison of different parameters. This will surely help you decide the best language suited for you. The parameters for comparison are- Scalability, performance, applications, execution, libraries and readability of code. Before start to the comparison, let us see some points about Golang.

What Is Python?

Python is a general purpose programming language, which means that it can be used for anything. The most significant part of Python is that it is an interpreted language, which implies that the composed code isn’t actually translated to a computer readable format at runtime. Many programming languages do this conversion when the program is being compiled. Mostly Python is used for web development. It is easy to learn Python because its syntax is easy and is the greatest advantage. You can also know the best python web frameworks at- Top 11 Best Free Python Web Framework Software To Use In 2019.

What is GoLang?

GoLang is also known as Go. This language is developed by Google. Go supports multi-paradigm like functional, procedural and concurrent. Go syntax after arriving from modification with C is to keep the code readable and compact. It includes strict linguistic structure which permits simpler cycle over gathering information structure like strings, maps and so forth. Go imparts many features of modern languages, such as method and operator overloading, pointer arithmetic and type inheritance. The most of the features of Go and its tools pursue the UNIX pattern, having in view of utility, so instead of merging into the language structure, a developer would now be able to concentrate more on the development logic. Know the comparison of Python vs Ruby vs Golang at- A Battle of Trios: Python vs Ruby vs Golang. Let us see the comparison between Python and Go on the basis of some important parameters-
Python vs Go

1. Scalability-

Development of a scalable application is a crucial work. If the things don’t scale it’s only negative to the reason for business. Golang was developed by keeping this thing in mind. It’s main purpose is to help developers at Google to solve issues which are at the scale of google, that involves many programmers working on large server software hosted on thousands of clusters. Hence Golang has inbuilt support for concurrent process channeling. 
Whereas, Python has some issues with concurrency but it can implement parallelism through threads.

2. Performance-

Go is extremely fast. It’s performance is similar to that of Java or C++. In short, Go is 40 times faster than Python. 

3. Applications-

Every programming language has a certain purpose hence at this point none of the language is a winner. Python is mostly used in the field of Data analytics, artificial intelligence, deep learning and web development. This can be generally credited to the libraries that are accessible in Python that make life in the said fields a ton simpler. 
On the other hand, GoLang is mostly used for system programming. It has also analyzed a generous amount of use and acceptance in the cloud computing because its support for concurrency. Golang has likewise observed a great deal of gratefulness and use in web development because of its incredible and easy to use libraries, which enable you to set up a web server in merely seconds.

4. Execution-

Python is dynamically typed language whereas Golang is statically typed language. Python uses an interpreter and Go lang uses compiler.
In Python, type interference is implemented by an interpreter. Hence some bugs may remain because interpreter interpreting something incorrectly. Hence Python limits the programmer when he needs to build a big programme.
In GoLang, variables are declared explicitly for the compiler so even trivial bugs are caught easily. Go can handle big programmes with finesse.

5. Libraries-

Libraries are the great benefit for programming languages. Python poses great libraries. There packages will help you with array handling and complex matrix functions, Tensorflow and Scikit Learn for Deep Learning, OpenCV for image processing, Pandas for Data Analysis, matplotlib for visualization etc.
Go posses some inbuilt libraries for web development, database handling, concurrent programming and encryption.

6. Readability-

Readability of a project is an important thing. Because a development team has many developers and each of these should understand the code. Python has easy to read and learn syntax. Also there are many different ways to do the same thing and this leads to confusion when a code is big or the developers working on it are in large numbers. Whereas, Go has strict rules for programming. It does not allow unnecessary libraries to import and unnecessary variables to be created. This implies there is a distinct method to play out a task which prompts a superior comprehension of code among huge groups.
Some of you may state that the adaptability of code endures a hit, however who truly thinks about flexibility particularly with regards to core programming? Syntax of GoLang is less friendly for beginners however it’s not as unforgiving as something prefer C or C++. So for readability of code we will go with GoLang. So as you all observe, GoLang unquestionably has the high ground much of the time and trumps Python as a programming language as we would like to think. It might not have the popularity that Python has but Go is catching up in that aspect  too.

Key Differences Between Python vs Go-

1. Python is a scripted language and has to be interpreted. While Go is faster most of the time since it does not have to consider anything at runtime.
2. Python does not provide built-in concurrency mechanism whereas Go has built-in concurrency mechanism.
3. Python has easy syntax and hence more readable, flexible. Go is likewise in the prime group with regards to clear syntax which holds zero zero unnecessary components.
4. About safety, Python is strongly typed language which is compiled and hence provides security, while Go is decent since every variable must have a type associated with it.
5. Python has more libraries as compared to Go.
6. Python is more user friendly than Go.
7. Python is as yet a most loved language with regards to data science problems while Go is progressively good for framework programming.
8. Python is dynamically typed language and Go is statically typed language.
9. Python is good for basic programming, using it can build up complex frameworks though, with Go a  similar tasks can be accomplished rapidly without going into nuances of programming language.
Are you looking to develop a software for your business with Python or GoLang? Then Solace is the right place to start. Developers at solace are well trained in Python and Go and able to provide the best web solution. Get a free quote for software development using python or Go that will lift your business to the next level.