One place for hosting & domains

      How To Write Unit Tests in Go

      The author selected the FreeBSD Foundation to receive a donation as part of the Write for DOnations program.


      A unit test is a function that tests a specific piece of code from a program or package. The job of unit tests is to check the correctness of an application, and they are a crucial part of the Go programming language.

      In this tutorial, you will create a small program and then run a series of tests on your code using Go’s testing package and the go test command. Once you complete the tutorial, you will have a working unit-testing suite that includes a table-based unit test, a coverage test, a benchmark, and a documented example.


      To complete this tutorial, you’ll need the following:

      Note: This tutorial uses Go Modules, which is a package management system introduced in Go version 1.11. Go Modules are intended to replace the $GOPATH and became the default option starting with Go version 1.13. For a more comprehensive overview of the differences between Go Modules and the $GOPATH, consider reading this official blog post from the Go core team.

      This tutorial was tested using Go version 1.14

      Step 1 — Creating a Sample Program to Unit Test

      Before you can write any unit tests, you need some code for your tests to analyze. In this step, you will build a small program that sums two integers. In the subsequent steps, you will use go test to test the program.

      First, create a new directory called math:

      Move inside the new directory:

      This will be the root directory for your program, and you will run all remaining commands from here.

      Now, using nano or your preferred text editor, create a new file called math.go:

      Add the following code:


      package math
      // Add is our function that sums two integers
      func Add(x, y int) (res int) {
          return x + y
      // Subtract subtracts two integers
      func Subtract(x, y int) (res int) {
          return x - y

      Here you are creating two functions called Add and Subtract. Each function accepts two integers and returns either their sum (func Add) or their difference (func Subtract).

      Save and close the file.

      In this step, you wrote some code in Go. Now, in the following steps, you will write some unit tests to ensure that your code functions properly.

      Step 2 — Writing Unit Tests in Go

      In this step, you will write your first test in Go. Writing tests in Go requires a test file link, and this test file must always end with _test.go. By convention, Go testing files are always located in the same folder, or package, where the code they are testing resides. These files are not built by the compiler when you run the go build command, so you needn’t worry about them ending up in deployments.

      And as with everything in Go, the language is opinionated about testing. The Go language provides a minimal yet complete package called testing that developers use alongside the go test command. The testing package provides some useful conventions, such as coverage tests and benchmarks, which you will now explore.

      Use your editor to create and open a new file called math_test.go:

      A test function in Go includes this signature: func TestXxxx(t *testing.T). This means that all test functions must start with the word Test, followed by a suffix whose first word is capitalized. Test functions in Go receive only one parameter, and in this case, it’s a pointer of type testing.T. This type contains useful methods that you will need to output results, log errors to the screen, and signal failures, like the t.Errorf() method.

      Add the following code to math_test.go:


      package math
      import "testing"
      func TestAdd(t *testing.T){
          got := Add(4, 6)
          want := 10
          if got != want {
              t.Errorf("got %q, wanted %q", got, want)

      First, you declare the name of the package that you want to test—math. Then you import the testing package itself, which then makes available the testing.T type and the other types and methods exported by the package. The code and testing logic is contained in the TestAdd function.

      To summarize, the following are characteristics of a test in Go:

      • The first and only parameter must be t *testing.T
      • The testing function begins with the word Test followed by a word or phrase that starts with a capital letter (the convention is to use the name of the method under test, e.g., TestAdd)
      • The test calls t.Error or t.Fail to indicate a failure (you are calling t.Error because it returns more detail than t.Fail)
      • You can use t.Log to provide non-failing debug information
      • Tests are saved in files using this naming convention: foo_test.go, such as math_test.go.

      Save and then close the file.

      In this step, you wrote your first test in Go. In the next step, you will begin using go test to test your code.

      Step 3 — Testing Your Go Code Using the go test command

      In this step, you will test your code. go test is a powerful subcommand that helps you automate your tests. go test accepts different flags that can configure the tests you wish to run, how much verbosity the tests return, and more.

      From your project’s root directory, run your first test:

      You will receive the following output:


      PASS ok ./math 0.988s

      PASS means the code is working as expected. When a test fails, you will see FAIL.

      The go test subcommand only looks for files with the _test.go suffix. go test then scans those file(s) for special functions including func TestXxx and several others that we will cover in later steps. go test then generates a temporary main package that calls these functions in the proper way, builds and runs them, reports the results, and finally cleans everything up.

      Our go test is probably sufficient for our little program, but there will be times when you’ll wish to see what tests are running and how long each takes. Adding the -v flag increases verbosity. Rerun your test with the new flag:

      You will see the following output:


      === RUN TestAdd --- PASS: TestAdd (0.00s) PASS ok ./math 1.410s

      In this step, you ran a basic unit test using the go test subcommand. In the next step, you will write a more complex, table-driven unit test.

      Step 4 — Writing Table-Driven Tests in Go

      A table-driven test is like a basic unit test except that it maintains a table of different values and results. The testing suite iterates over these values and submits them to the test code. Using this approach, we get to test several combinations of inputs and their respective output.

      You will now replace your unit test with a table of structs, whose fields include the necessary two arguments (two integers) and the expected result (their sum) for your Add function.

      Reopen math_test.go:

      Delete all the code in the file and add the following table-driven unit test instead:


      package math
      import "testing"
      // arg1 means argument 1 and arg2 means argument 2, and the expected stands for the 'result we expect'
      type addTest struct {
          arg1, arg2, expected int
      var addTests = []addTest{
          addTest{2, 3, 5},
          addTest{4, 8, 12},
          addTest{6, 9, 15},
          addTest{3, 10, 13},
      func TestAdd(t *testing.T){
          for _, test := range addTests{
              if output := Add(test.arg1, test.arg2); output != test.expected {
                  t.Errorf("Output %q not equal to expected %q", output, test.expected)

      Here you are defining a struct, populating a table of structs that include the arguments and expected results for your Add function, and then writing a new TestAdd function. In this new function, you iterate over the table, run the arguments, compare the outputs to each expected result, and then returning any errors, should they occur.

      Save and close the file.

      Now run the test with the -v flag:

      You will see the same output as before:


      === RUN TestAdd --- PASS: TestAdd (0.00s) PASS ok ./math 1.712s

      With each iteration of the loop, the code tests the value calculated by the Add function against an expected value.

      In this step, you wrote a table-driven test. In the next step, you will write a coverage test instead.

      Step 5 — Writing Coverage Tests in Go

      In this step, you will write a coverage test in Go. When writing tests, it is often important to know how much of your actual code the tests cover. This is generally referred to as coverage. This is also why you have not written a test for your Subtract function — so we can view an incomplete coverage test.

      Run the following command to calculate the coverage for your current unit test:

      • go test -coverprofile=coverage.out

      You will receive the following output:


      PASS coverage: 50.0% of statements ok ./math 2.073s

      Go saved this coverage data in the file coverage.out. Now you can present the results in a web browser.

      Run the following command:

      • go tool cover -html=coverage.out

      A web browser will open, and your results will render:

      go unit testing coverage.out

      The green text indicates coverage, whereas the red text indicates the opposite.

      In this step, you tested the coverage of your table-driven unit test. In the next step, you will benchmark your function.

      Step 6 — Writing Benchmarks in Go

      In this step, you will write a benchmark test in Go. Benchmarking measures the performance of a function or program. This allows you to compare implementations and to understand the impact of the changes you make to your code. Using that information, you can reveal parts of your Go source code worth optimizing.

      In Go, functions that take the form func BenchmarkXxx(*testing.B) are considered benchmarks. go test will execute these benchmarks when you provide the -bench flag. Benchmarks are run sequentially.

      Let’s add a benchmark to our unit test.

      Open math_test.go:

      Now add a benchamrk function using the func BenchmarkXxx(*testing.B) syntax:


      func BenchmarkAdd(b *testing.B){
          for i :=0; i < b.N ; i++{
              Add(4, 6)

      The benchmark function must run the target code b.N times, where N is an integer that can be adjusted. During benchmark execution, b.N is adjusted until the benchmark function lasts long enough to be timed reliably. The --bench flag accepts its arguments in the form of a regular expression.

      Save and close the file.

      Now let’s use go test again to run our benchmark:

      The . will match every benchmark function in a file.

      You can also declare benchmark functions explicitly:

      Run either command, and you will see an output like this:


      goos: windows goarch: amd64 pkg: math BenchmarkAdd-4 1000000000 1.07 ns/op PASS ok ./math 2.074s

      The resulting output means that the loop ran 10,000,000 times at a speed of 1.07 nanosecond per loop.

      Note: Try not to benchmark your Go code on a busy system being used for other purposes, or else you will interfere with the benchmarking process and get inaccurate results

      You have now added a benchmark to your growing unit test. In the next and final step, you will add examples to your documentation, which go test will also evaluate.

      Step 7 — Documenting Your Go Code with Examples

      In this step, you will document your Go code with examples and then test those examples. Go is very focused on proper documentation, and example code adds another dimension both to documentation and testing. Examples are based on existing methods and functions. Your examples should show users how to use a specific piece of code. Example functions are the third type of function treated specially by the go test subcommand.

      To begin, reopen math_test.go,

      Now add the highlighted code. This will add the fmt package to the import list and your example function at the end of the file:


      package math
      import (
      // arg1 means argument 1 and arg2 means argument 2, and the expected stands for the 'result we expect'
      type addTest struct {
          arg1, arg2, expected int
      var addTests = []addTest{
          addTest{2, 3, 5},
          addTest{4, 8, 12},
          addTest{6, 9, 15},
          addTest{3, 10, 13},
      func TestAdd(t *testing.T) {
          for _, test := range addTests {
              if output := Add(test.arg1, test.arg2); output != test.expected {
                  t.Errorf("Output %q not equal to expected %q", output, test.expected)
      func BenchmarkAdd(b *testing.B) {
          for i := 0; i < b.N; i++ {
              Add(4, 6)
      func ExampleAdd() {
          fmt.Println(Add(4, 6))
          // Output: 10

      The Output: line is used to specify and document the expected output.

      Note: The comparison ignores leading and trailing space.

      Save and close the file.

      Now rerun your unit test:

      You will see an updated outout like this:


      === RUN TestAdd --- PASS: TestAdd (0.00s) === RUN ExampleAdd --- PASS: ExampleAdd (0.00s) PASS ok ./math 0.442s

      Your examples are now also tested. This feature improves your documentation and also makes your unit test more robust.


      In this tutorial, you created a small program and then wrote a basic unit test to check its functionality. You then rewrote your unit test as a table-based unit test and then added a coverage test, a benchmark, and a documented example.

      Taking time to write adequate unit tests is useful to you as a programmer because it improves your confidence that the code or program you have written will continue to work as expected. The testing package in Go provides you with considerable unit-testing capabilities. To learn more, refer to Go’s official documentation.

      And if you wish to learn more about programming in Go, visit our tutorial series / free ebook, How To Code in Go.

      Source link

      36 Brilliant Blogging Tools to Help You Write Better, Publish More, and Increase Traffic

      Affiliate Disclosure: DreamHost maintains relationships with some of our recommended partners, so if you click through a link and purchase, we may receive a commission. We only recommend solutions we believe in.

      Running a blog can be tough. There are times when it can feel like having multiple jobs. Not only do you need to create fresh, high-quality content, but you’ll also have a website to manage, social media posts to schedule, and data to analyze.

      Having a versatile bag of tools at your disposal can keep your blogging gig from becoming overwhelming. There are solutions for most of your day-to-day tasks, from design to Search Engine Optimization (SEO) and everything in between.

      With all the possibilities to choose from, you could spend weeks just combing through your options. So we’ve done the hard work for you. In this article, we’ll cover why you need the right tools. Then we’ll detail 36 brilliant blogging solutions worth checking out. Let’s get started!

      Why You Need the Right Blogging Tools

      As a blogger, you’ll want to find tools that help you become more productive and successful. For example, discovering topics to blog about that your audience will love can be tricky. The right solution can help you brainstorm ideas and explore new niches you weren’t previously aware of, saving you a lot of time in the process.

      What’s more, there’s more to blogging than just writing. You need to be sure people can discover and share your website. Therefore, to maximize your reach, you’ll want to look into blogging tools that give your SEO and social media a boost. This can make up for any lack of knowledge or experience on your end, and free up your attention for your actual content.

      36 Brilliant Blogging Tools to Help You Write Better, Publish More, and Increase Traffic

      We’ve argued the case for having the right blogging tools at the ready. Now let’s explore 36 of the top options and see what they can do.


      Content creation requires lots of research. You need to be sure people are searching for what you’re going to be writing about. You’ll also need someplace to keep ideas and notes.

      1. Google Keyword Planner

      The Google Keyword Planner home page.

      Before you start writing a new blog post, you might want to make sure you’re using words that people are searching for. Google Keyword Planner can provide you with feedback on your potential keywords.

      This great tool will help you by showing you how popular each chosen keyword is through search volume metrics. You’ll also get some suggestions for other relevant phrases you may want to use.

      Price: Google Keyword Planner is free to use, as long as you have a Google Ads account set up.

      2. Google Trends

      The Google Trends website.

      When trying to nail down an idea for a successful blog post, you might want to start with Google Trends. You can enter any topic into the search box, and this tool will provide you with a ton of information and history about it.

      You can filter your results, which is especially useful if you’re trying to capture a particular region’s attention. Google Trends also provides you a list of related topics, which you can use to brainstorm more content ideas.

      Price: Google Trends is entirely free for anyone to use.

      3. BuzzSumo

      The BuzzSumo website.

      If you’re wondering what’s trending in your niche, BuzzSumo can tell you. Just search for the topic you’re interested in, and you’ll get a list of the top-performing content in that area.

      You can also enter the URL for one of your competitors. BuzzSumo will give you a list of the top-performing content from that site, so you can see what’s resonating with your potential audience.

      Price: BuzzSumo offers a seven-day free trial. After that, you can choose from several tiers starting at $79 per month.

      4. HubSpot’s Blog Ideas Generator

      HubSpot’s Blog Ideas Generator.

      When you start blogging, it’s hard to imagine ever running out of ideas. However, the day will likely come when you sit down to write and come up empty. That’s where HubSpot’s Blog Ideas Generator comes into the picture.

      Provide the generator with up to five nouns, and it will return a week’s worth of blog ideas. If you need a year’s worth of topics, you can enter some details and unlock 250 more potential blog posts.

      Price: The Blog Ideas Generator is free for anyone to use. But, if you want more ideas at once, you’ll have to trade some information to get them.

      5. EvernoteThe Evernote website.

      With all those new blog post ideas, you’re going to be doing a lot of research. If your bookmarks bar is becoming a disorganized mess, Evernote can provide a place to keep all of your screenshots, notes, and articles.

      What if you prefer a mix of handwritten and electronic notes? You can actually scan your notes with your phone into the app. You can even search these scanned documents since Evernote can read handwriting.

      Price: Evernote has several plans to choose from, including a robust free version. You can upgrade to one of the paid versions starting at $7.99 per month.

      Writing and Grammar

      Well-written, readable content is crucial for a successful blog. Even the most compelling ideas will suffer without the right words to convey them.

      6. Grammarly

      The Grammarly writing tool.

      Even the strongest writer can benefit from having a second pair of eyes look over their blog posts. Grammarly is like having an experienced editor making suggestions to improve your writing and style.

      Each time you open a new document in Grammarly, you can set goals for its tone, formality, and intent. You’ll then receive feedback to help you hit those targets. Grammarly also has a Chrome extension, so you can check your emails and Google Docs as well.

      One downside: Grammarly is currently only available in English. If you’re looking for a multilingual grammar checker, consider Language Tool, which can check your writing in more than 20 languages. It’s what our team uses to review Spanish content.

      Price: Grammarly’s free plan checks your grammar, spelling, and conciseness. The premium tier adds more style and genre checks (as well as a plagiarism detector) for $11.66 per month.

      7. Associated Press (AP) Stylebook

      The Associated Press Stylebook.

      The Associated Press (AP) Stylebook is a reference every blogger should have on their bookshelf. Using AP style for blog posts can help to keep them concise, clear, and informative.

      The AP Stylebook is updated frequently. If you buy the book from the official website, you’ll receive email notifications about these changes. It’s a simple way to keep up with stylistic adjustments.

      Price: You have multiple options for purchasing the AP Stylebook. A spiral-bound physical copy will cost you $26.95. The online stylebook starts at $22.00 for one user.

      8. Google Docs

      The Google Docs home page.

      Google Docs is a web-based word processor. You can use this application to compose, edit, and format your blog posts.

      One advantage of Google Docs is that you can access your documents anywhere, regardless of your device. For a blogger on the go, this is a must-have feature!

      Price: Google Docs is free to use. You can upgrade to G Suite for additional features and applications, starting at $6 per month.

      Project Management

      Blogs have a lot of moving parts. Project management tools can help you stay organized, so your blogging tasks stay on track.

      9. Asana

      The Asana project management tool.

      Asana enables you to build a roadmap for your blog projects. You can group tasks to make up a project or divide them into smaller chunks.

      If you collaborate with other writers on your blog, Asana is a powerful tool for team management. You’re able to see at a glance where each post is in your pipeline.

      Price: Asana’s free option allows collaboration with up to 15 people. Premium plans begin at $10.99 per user per month.

      10. Trello

      The Trello productivity tool.

      Trello’s design is based on cards, lists, and boards. It’s an intuitive system that can hold a ton of information.

      Trello is an excellent alternative to Asana if you’re looking for something a little more streamlined. You can keep all the attachments and notes you need for a task on its card. This format is also easier to handle if you’re a team of one.

      Price: Trello has a robust free option that enables you to have an unlimited number of personal boards and ten team boards. Upgraded plans begin at $9.99 per user per month.


      Gorgeous visuals to complement your words are an essential part of creating branded, shareable blog posts. You don’t need to be an artist, but the right tools can help you fake it.

      11. Adobe Photoshop

      The Adobe Photoshop website.

      When you think of photo editing software, Adobe Photoshop probably comes to mind. Whether you’re touching up a stock photo or creating a new logo, you can probably do it with Photoshop.

      One exciting aspect of this platform is that new features are always being added. One of the latest is the object selection tool. You can lasso or draw a rectangle around an object, and the selection snaps into place around it.

      Price: You can try Adobe Photoshop for free for seven days. After that, plans start at $20.99 per month.

      12. Canva

      The Canva photo editing tool.

      Canva is like Photoshop’s younger but no less accomplished sister. The free plan gives you generous access to templates, stock photos, and other design elements. However, Canva Pro contains some valuable features as well.

      With a Brand Kit, for example, you can collect the colors, fonts, and logos that make your blog recognizable all in one place. Imagine the time you could save on looking up HTML color codes!

      Price: You can upgrade to Pro for $9.95 per month. There’s also a 30-day free trial.

      13. Logaster

      The Logaster home page.

      Are you struggling to come up with a logo? If so, Logaster can generate a variety of options to choose from in seconds. Just enter your blog’s name and scroll through the possibilities.

      If you’d like, you can give Logaster more information to build your logo with. For instance, you can try specifying a color and industry for more personalization. If you’re not entirely happy with the design, you can do some editing by signing up for a free account.

      Price: You can download and use the small version of your new logo for free. However, Logaster also offers packages that include different size logos, letterheads, favicons, and more. These range from $19.99 to $89.99.

      Search Engine Optimization (SEO)

      SEO has many different facets that all need your attention. The following tools can help you analyze and optimize your blog’s content, so you’ll have a fighting chance for higher rankings.

      14. Yoast SEO

      The Yoast SEO plugin.

      If you have a blog on WordPress, you’ll probably want to install the Yoast SEO plugin. This tool makes optimizing each of your posts easy.

      For example, you can give Yoast SEO a keyphrase, and it will return actionable advice that you can use to improve your post. The premium version can even account for other forms of that keyphrase, including synonyms and plurals.

      Price: You can get started with the free version or go all-in with Yoast SEO Premium. The latter starts at $89 for one site.

      15. SEMrush

      The SEMRush website.

      It might be unfair to give SEMrush only one spot on this list, as it provides multiple tools. SEMrush offers insights on everything from social media to Pay-Per-Click (PPC) advertising.

      Most importantly, however, SEMrush’s SEO Toolkit can give you an edge over your competition. The Domain Overview lets you see which keywords your competitors use. You can use this information to hone your content plan over time.

      Price: SEMrush plans range from $83.28 to $333.28 per month. Higher tiers get you access to more reports and extended limits. The good news? We’ve worked out a free SEMrush trial for our readers, so you can see if this tool is a good fit for your blog without a long-term commitment!


      16. MarketMuse

      The MarketMuse solution.

      MarketMuse is a complete, AI-based solution for content. This tool can lend a hand with anything from research to content creation.

      The ability to optimize content can make MarketMuse a valuable part of your blogging strategy. Its AI analyzes your copy and makes suggestions for the language you should use. This can boost your SEO rankings, as you’ll be using the same words your audience uses to search.

      Price: You can try MarketMuse’s Pro plan free for a month. After that, the cost is $325 per month.

      17. Ahrefs

      The Ahrefs SEO tool.

      Ahrefs is an invaluable resource if you’ve been blogging for a while and want to move to the next level. This SEO toolset can help you maximize your efforts.

      While Ahrefs offers a wide range of features, it started as a backlink checker and still excels at that task. The Content Explorer tool analyzes individual pieces of content and displays how many backlinks they receive over time.

      Price: Ahrefs offers a seven-day trial for $7. Full plans start at $82 per month for a single user.

      18. Can I Rank?

      The Can I Rank tool.

      Can I Rank may be the next best thing to hiring an analyst. This tool uses AI to deliver actionable insights that can help you improve your blog’s SEO.

      To do this, Can I Rank’s reports provide steps towards ranking for your target keywords. You’ll get suggestions for improving your current content, and new keywords you may want to focus on going forward. The AI will also connect you to other SEO tools that may be helpful.

      Price: Can I Rank has a free plan, which limits how many times you can access each report. Paid plans start at $49 per month, and a free trial is available.

      19. Ubersuggest

      The Ubersuggest Chrome extension.

      Installing the Ubersuggest Chrome extension gives you access to SEO metrics and insights every time you search.

      Ubersuggest can help refine keywords that you’ve researched. If you perform a search with one of your target keywords, you’ll receive a list of related target phrases, along with the search volume for the current month and the estimated competition for the keyword.

      Price: This extension is free. You don’t even need to create an account, although you’ll gain access to more features if you do so.

      20. LinkMiner

      The LinkMiner extension.

      Broken links can hurt your site’s SEO. They’re easy to fix but not always simple to find. Fortunately, the LinkMiner Chrome extension unearths broken links for you.

      This extension provides you with overall results for each page you analyze. It also highlights all the links in your content in red, so you can get them fixed right away.

      Price: You can use this extension for free.

      Site Management

      A user-friendly CMS can make managing your website much more straightforward. When you pair that with reliable hosting, you’ll have a solid foundation for your blog.

      21. WordPress

      The home page.

      WordPress powers 37% of all sites on the internet, and for good reason. This free, open-source platform is powerful, flexible, and supported by an active community.

      One appealing feature for bloggers is the Block Editor. This editor makes it easy to create stunning, rich content, with no design or coding experience necessary. The drag-and-drop interface makes it possible to rearrange your content and experiment with different possibilities.

      Price: WordPress itself is free. You’ll just have to pay for a hosting plan. You can also choose to purchase premium themes and plugins.

      22. A Managed WordPress Hosting Plan

      DreamHost managed WordPress hosting.

      You’ll probably get more out of WordPress if you complement it with a managed WordPress hosting plan. These specialized plans come with extras that can make your website building and upkeep a lot easier.

      After all, just because you’re a blogger doesn’t mean you’re a web designer. That’s why our DreamPress managed hosting plans include a website builder specifically designed for WordPress sites. After you’ve created your site, we’ll keep it safe by performing daily and on-demand backups.

      Price: Managed WordPress hosting can vary in cost depending on your provider. Our hosting plans start at $16.95 per month.

      Blog Better with DreamPress

      Our automatic updates and strong security defenses take server management off your hands so you can focus on content creation.

      23. Wordable

      The Wordable plugin.

      As awesome as the Block Editor is, there are advantages to composing your blog posts in Google Docs. However, you’ll lose a lot of time copying and reformatting your posts before publishing them.

      The Wordable plugin accomplishes all of those tasks in a single click. Wordable doesn’t just import text; it also brings along the images and headings. You can have guest writers submit their pieces as Google Docs and import them with Wordable. You don’t have to set up an account on your site for them, and you won’t have to reformat their posts either.

      Price: You can test out Wordable with a three-export trial. After that, plans start at $19 per month for one user and one WordPress site.

      Social Media

      Handling multiple social media channels can create confusion and the potential for mistakes. To avoid that, you can stay on top of your social media schedule with the help of these tools.

      24. CoSchedule

      The CoSchedule plugin.

      CoSchedule is the editorial calendar of your dreams. It can help you manage blog posts and get them onto social media platforms.

      CoSchedule’s Blog Calendar lets you see your scheduled blog and social media posts in one place. If you need to reschedule a post, you can just drag and drop it wherever you’d like. The calendar automatically adjusts the accompanying social media messages.

      Price: You can get the Blog Calendar for $14 per month. If you’d like to add more functionality with the Marketing Calendar, the price increases to $29 per month.

      25. Social Snap

      The Social Snap plugin.

      Social Snap is a social media plugin for WordPress. This solution comes with a suite of tools designed to get more traffic to your blog.

      With Social Snap, you can place social sharing buttons anywhere in your blog posts. The floating sidebar could be an effective strategy if you tend to write longer content. You can also customize the buttons to match your website’s design.

      Price: Social Snap offers plans starting at $27.30 per year. There is no free trial, but there is a 30-day money-back guarantee.

      26. Buffer

      The Buffer platform.

      If you’re in the market for a complete social media solution, you may want to check out Buffer. This platform provides tools to help you publish and analyze your content.

      Buffer’s Publish tool enables you to manage all of your social media channels from one dashboard. With some determination and a lot of coffee, you might schedule a month’s worth of content in a single afternoon.

      Price: Buffer Publish begins at $12 per month. The Pro plan enables you to schedule up to 100 posts.

      27. Click to Tweet

      The Click to Tweet plugin.

      Click to Tweet is a free plugin provided by CoSchedule. If you have your eyes set on the Twitterverse, you’ll likely want this blogging tool at your side.

      With it, you can pull out especially tweet-worthy wisdom from your content. Your readers can then share these insights with their followers in one click.

      Price: Click to Tweet is free to download and use. You do need to provide some personal information and sign up for CoSchedule’s mailing list to access the tool.


      You may already include video on your blog, as it can increase the time visitors spend on a page. If not, these solutions can get you started.

      28. YouTube

      The YouTube home page.

      You may already use YouTube to host your videos, but there’s more you can do with the platform. For example, did you know that you can live stream with YouTube?

      Live streaming is a fun way to connect with your audience and has been growing in popularity in recent years. It’s a great way to build a sense of community around your blog.

      Price: YouTube is free to use. All you need is a Google account.

      29. Adobe Premiere Rush

      The Adobe Rush website.

      If creating video content sounds like a lot of work, you can check out Adobe Premiere Rush. This helpful tool makes producing a video (almost) as easy as posting to social media.

      With Adobe Premiere Rush, you can capture and edit footage right from your mobile phone. You can even add graphics, overlays, and voiceovers. Then you’ll be able to share the video to your YouTube channel, Instagram account, Facebook page, and other social media platforms.

      Price: Adobe Premiere Rush offers a free trial that limits you to three exports. After that, you can access the software for $9.99 per month.


      By keeping an eye on your blog’s statistics, you’ll be able to see where you can improve. If you’re not a data analyst, you might appreciate some help in that department.

      30. Google Analytics

      The Google Analytics website.

      If you haven’t already installed Google Analytics on your blog, what are you waiting for? Its many tools will give you access to the metrics you need for running a successful blog.

      While your hosting provider may provide you with some traffic data, Google Analytics offers you a wide range of numbers. Knowing where your traffic is coming from will help you focus your efforts on those channels.

      Price: Google Analytics is free to use. You just need to add a tracking code to your website.

      31. MonsterInsights

      The MonsterInsights plugin.

      MonsterInsights is a plugin that helps make Google Analytics even more powerful. It’s a match made in blogging heaven.

      A favorite feature of MonsterInsights is the Google Analytics dashboard. Instead of navigating away from WordPress, you can view all that data right in your admin dashboard. You’ll also be able to see what’s happening on your blog in real-time.

      Price: MonsterInsights plans begin at $99.50 per year. There’s no free trial, but there is a 14-day money-back guarantee.

      Marketing Your Blog

      Having the best content on the web won’t do you any good if no one knows it exists. Fortunately, you can get your blog in front of more people with these tools.

      32. OptinMonster

      The OptinMonster plugin.

      As a blogger, convincing readers to sign up for your email newsletter is critical. OptinMonster can help you create opt-in campaigns that turn casual readers into devoted fans.

      If your opt-in isn’t user-friendly, it’s unlikely to convert. OptinMonster gives you powerful targeting options, such as device-based targeting. This ensures that mobile users only see campaigns that are optimized for their devices.

      Price: OptinMonster’s basic plan will cost you $9 per month.

      33. Hunter

      The Hunter tool.

      Guest posting is a tried-and-true link building technique for bloggers. Crafting a strong pitch is hard enough, but sometimes the most challenging part is finding the right email to send it to.

      To make things easier, you can simply enter a domain name into Hunter’s search box, and the tool returns every email address it can find for that company. You can use this to see a particular individual’s email or search for a role, such as “submissions@” or “editorial@”.

      Price: You can perform 50 free searches per month. Paid plans start at $34 per month.

      34. NinjaOutreach

      The NinjaOutreach platform.

      Partnering with an influencer can increase your blog’s audience. NinjaOutreach enables you to filter through lots of influencers in your niche, so you can find the right one.

      Whether you’re targeting Instagram, Twitter, TikTok, or YouTube, NinjaOutreach has you covered with its extensive database of influencers. You can even find other bloggers who may be interested in collaboration.

      Price: NinjaOutreach offers a 7-day free trial. A monthly plan starts at $119.

      35. Mailchimp

      The Mailchimp platform.

      There’s more to email marketing than sending out a blast whenever you publish a new post. Mailchimp helps you organize your list and send out updates on time.

      No one wants to read ugly emails, but thanks to Mailchimp’s drag-and-drop builder, you can make customizations and even add images and videos. Then, real-time analytics lets you monitor how effective your campaigns are.

      Price: Mailchimp offers a generous free plan to get you started. You can get an upgraded email-only plan for $9.99 per month.

      36. Teachable

      The Teachable home page.

      Sharing your knowledge is an effective way of establishing yourself as an expert in your blogging niche. Unfortunately, setting up an online course can be a challenge.

      Teachable is a complete solution for building and running an online course. You can make your lessons extra special by taking advantage of Teachable’s live features. For example, you can schedule one-on-one sessions with your students to check in on progress and answer questions.

      Price: Teachable’s Basic plan comes with everything you need to create your first course, and costs $29 per month.

      11 Blogging Tools We Use on the DreamHost Blog

      While all of the blogging tools on this list are excellent, we have some favorites we use for the DreamHost blog itself. Here’s some extra love for the solutions that make our job so much easier:

      1. Google Docs: When it comes to collaboration, you can’t beat Google Docs.
      2. Grammarly: Even the most seasoned writers miss an Oxford comma from time to time.
      3. Language Tool: This is a useful grammar checker if you need support in languages other than English. We use it for our Spanish content!
      4. MarketMuse: If you love the content on our blog, we have to give some credit to MarketMuse.
      5. WordPress: Like so much of the internet, we love how easy WordPress is to use. It really is our favorite blogging tool!
      6. DreamPress Hosting: Not to toot our own horn, but we’re really good at this hosting thing.
      7. OptinMonster: No one wants to annoy their blog visitors with unwanted opt-ins, and we’re no exception.
      8. Yoast SEO: We’re proud of what we publish, and Yoast SEO helps ensure that our blog content gets seen by plenty of visitors.
      9. CoSchedule: Keeping track of when and where we’ve published our content is much easier thanks to CoSchedule.
      10. Canva: The one-click resize option for various social media channels is a gift.
      11. Google Analytics: We use Google Analytics to be sure we’re giving you more of what you want.

      If you’re not sure where to begin, the above tools should start you off on the right foot.

      Ready to Launch Your WordPress Blog?

      Whether you need help choosing a blogging platform, understanding affiliate marketing, or picking a WordPress theme, we can help! Subscribe to our monthly digest so you never miss an article.

      What’s Your Next Blogging Tool?

      Handling a blog on your own is a difficult task. Taking advantage of a few of the many blogging tools available can give you back some valuable time.

      Today, we’ve looked at a few reasons why you might want to invest in some blogging tools. If you’re just getting started with your blog, you might try out Google Docs and Grammarly to keep your content organized and polished. If you’re ready to step up your marketing game, Mailchimp can give you the edge you’re looking for.

      Ready to put those new blogging tools to work? It may be a smart time to upgrade your hosting service, to prepare for all the new traffic you’ll be getting. Check out our managed WordPress hosting plans!

      Source link

      How To Use unittest to Write a Test Case for a Function in Python

      The author selected the COVID-19 Relief Fund to receive a donation as part of the Write for DOnations program.


      The Python standard library includes the unittest module to help you write and run tests for your Python code.

      Tests written using the unittest module can help you find bugs in your programs, and prevent regressions from occurring as you change your code over time. Teams adhering to test-driven development may find unittest useful to ensure all authored code has a corresponding set of tests.

      In this tutorial, you will use Python’s unittest module to write a test for a function.


      To get the most out of this tutorial, you’ll need:

      Defining a TestCase Subclass

      One of the most important classes provided by the unittest module is named TestCase. TestCase provides the general scaffolding for testing our functions. Let’s consider an example:

      import unittest
      def add_fish_to_aquarium(fish_list):
          if len(fish_list) > 10:
              raise ValueError("A maximum of 10 fish can be added to the aquarium")
          return {"tank_a": fish_list}
      class TestAddFishToAquarium(unittest.TestCase):
          def test_add_fish_to_aquarium_success(self):
              actual = add_fish_to_aquarium(fish_list=["shark", "tuna"])
              expected = {"tank_a": ["shark", "tuna"]}
              self.assertEqual(actual, expected)

      First we import unittest to make the module available to our code. We then define the function we want to test—here it is add_fish_to_aquarium.

      In this case our add_fish_to_aquarium function accepts a list of fish named fish_list, and raises an error if fish_list has more than 10 elements. The function then returns a dictionary mapping the name of a fish tank "tank_a" to the given fish_list.

      A class named TestAddFishToAquarium is defined as a subclass of unittest.TestCase. A method named test_add_fish_to_aquarium_success is defined on TestAddFishToAquarium. test_add_fish_to_aquarium_success calls the add_fish_to_aquarium function with a specific input and verifies that the actual returned value matches the value we’d expect to be returned.

      Now that we’ve defined a TestCase subclass with a test, let’s review how we can execute that test.

      Executing a TestCase

      In the previous section, we created a TestCase subclass named TestAddFishToAquarium. From the same directory as the file, let’s run that test with the following command:

      • python -m unittest

      We invoked the Python library module named unittest with python -m unittest. Then, we provided the path to our file containing our TestAddFishToAquarium TestCase as an argument.

      After we run this command, we receive output like the following:


      . ---------------------------------------------------------------------- Ran 1 test in 0.000s OK

      The unittest module ran our test and told us that our test ran OK. The single . on the first line of the output represents our passed test.

      Note: TestCase recognizes test methods as any method that begins with test. For example, def test_add_fish_to_aquarium_success(self) is recognized as a test and will be run as such. def example_test(self), conversely, would not be recognized as a test because it does not begin with test. Only methods beginning with test will be run and reported when you run python -m unittest ....

      Now let’s try a test with a failure.

      We modify the following highlighted line in our test method to introduce a failure:

      import unittest
      def add_fish_to_aquarium(fish_list):
          if len(fish_list) > 10:
              raise ValueError("A maximum of 10 fish can be added to the aquarium")
          return {"tank_a": fish_list}
      class TestAddFishToAquarium(unittest.TestCase):
          def test_add_fish_to_aquarium_success(self):
              actual = add_fish_to_aquarium(fish_list=["shark", "tuna"])
              expected = {"tank_a": ["rabbit"]}
              self.assertEqual(actual, expected)

      The modified test will fail because add_fish_to_aquarium won’t return "rabbit" in its list of fish belonging to "tank_a". Let’s run the test.

      Again, from the same directory as we run:

      • python -m unittest

      When we run this command, we receive output like the following:


      F ====================================================================== FAIL: test_add_fish_to_aquarium_success (test_add_fish_to_aquarium.TestAddFishToAquarium) ---------------------------------------------------------------------- Traceback (most recent call last): File "", line 13, in test_add_fish_to_aquarium_success self.assertEqual(actual, expected) AssertionError: {'tank_a': ['shark', 'tuna']} != {'tank_a': ['rabbit']} - {'tank_a': ['shark', 'tuna']} + {'tank_a': ['rabbit']} ---------------------------------------------------------------------- Ran 1 test in 0.001s FAILED (failures=1)

      The failure output indicates that our test failed. The actual output of {'tank_a': ['shark', 'tuna']} did not match the (incorrect) expectation we added to of: {'tank_a': ['rabbit']}. Notice also that instead of a ., the first line of the output now has an F. Whereas . characters are outputted when tests pass, F is the output when unittest runs a test that fails.

      Now that we’ve written and run a test, let’s try writing another test for a different behavior of the add_fish_to_aquarium function.

      Testing a Function that Raises an Exception

      unittest can also help us verify that the add_fish_to_aquarium function raises a ValueError Exception if given too many fish as input. Let’s expand on our earlier example, and add a new test method named test_add_fish_to_aquarium_exception:

      import unittest
      def add_fish_to_aquarium(fish_list):
          if len(fish_list) > 10:
              raise ValueError("A maximum of 10 fish can be added to the aquarium")
          return {"tank_a": fish_list}
      class TestAddFishToAquarium(unittest.TestCase):
          def test_add_fish_to_aquarium_success(self):
              actual = add_fish_to_aquarium(fish_list=["shark", "tuna"])
              expected = {"tank_a": ["shark", "tuna"]}
              self.assertEqual(actual, expected)
          def test_add_fish_to_aquarium_exception(self):
              too_many_fish = ["shark"] * 25
              with self.assertRaises(ValueError) as exception_context:
                  "A maximum of 10 fish can be added to the aquarium"

      The new test method test_add_fish_to_aquarium_exception also invokes the add_fish_to_aquarium function, but it does so with a 25 element long list containing the string "shark" repeated 25 times.

      test_add_fish_to_aquarium_exception uses the with self.assertRaises(...) context manager provided by TestCase to check that add_fish_to_aquarium rejects the inputted list as too long. The first argument to self.assertRaises is the Exception class that we expect to be raised—in this case, ValueError. The self.assertRaises context manager is bound to a variable named exception_context. The exception attribute on exception_context contains the underlying ValueError that add_fish_to_aquarium raised. When we call str() on that ValueError to retrieve its message, it returns the correct exception message we expected.

      From the same directory as, let’s run our test:

      • python -m unittest

      When we run this command, we receive output like the following:


      .. ---------------------------------------------------------------------- Ran 2 tests in 0.000s OK

      Notably, our test would have failed if add_fish_to_aquarium either didn’t raise an Exception, or raised a different Exception (for example TypeError instead of ValueError).

      Note: unittest.TestCase exposes a number of other methods beyond assertEqual and assertRaises that you can use. The full list of assertion methods can be found in the documentation, but a selection are included here:

      Method Assertion
      assertEqual(a, b) a == b
      assertNotEqual(a, b) a != b
      assertTrue(a) bool(a) is True
      assertFalse(a) bool(a) is False
      assertIsNone(a) a is None
      assertIsNotNone(a) a is not None
      assertIn(a, b) a in b
      assertNotIn(a, b) a not in b

      Now that we’ve written some basic tests, let’s see how we can use other tools provided by TestCase to harness whatever code we are testing.

      Using the setUp Method to Create Resources

      TestCase also supports a setUp method to help you create resources on a per-test basis. setUp methods can be helpful when you have a common set of preparation code that you want to run before each and every one of your tests. setUp lets you put all this preparation code in a single place, instead of repeating it over and over for each individual test.

      Let’s take a look at an example:

      import unittest
      class FishTank:
          def __init__(self):
              self.has_water = False
          def fill_with_water(self):
              self.has_water = True
      class TestFishTank(unittest.TestCase):
          def setUp(self):
              self.fish_tank = FishTank()
          def test_fish_tank_empty_by_default(self):
          def test_fish_tank_can_be_filled(self):
     defines a class named FishTank. FishTank.has_water is initially set to False, but can be set to True by calling FishTank.fill_with_water(). The TestCase subclass TestFishTank defines a method named setUp that instantiates a new FishTank instance and assigns that instance to self.fish_tank.

      Since setUp is run before every individual test method, a new FishTank instance is instantiated for both test_fish_tank_empty_by_default and test_fish_tank_can_be_filled. test_fish_tank_empty_by_default verifies that has_water starts off as False. test_fish_tank_can_be_filled verifies that has_water is set to True after calling fill_with_water().

      From the same directory as, we can run:

      • python -m unittest

      If we run the previous command, we will receive the following output:


      .. ---------------------------------------------------------------------- Ran 2 tests in 0.000s OK

      The final output shows that the two tests both pass.

      setUp allows us to write preparation code that is run for all of our tests in a TestCase subclass.

      Note: If you have multiple test files with TestCase subclasses that you’d like to run, consider using python -m unittest discover to run more than one test file. Run python -m unittest discover --help for more information.

      Using the tearDown Method to Clean Up Resources

      TestCase supports a counterpart to the setUp method named tearDown. tearDown is useful if, for example, we need to clean up connections to a database, or modifications made to a filesystem after each test completes. We’ll review an example that uses tearDown with filesystems:

      import os
      import unittest
      class AdvancedFishTank:
          def __init__(self):
              self.fish_tank_file_name = "fish_tank.txt"
              default_contents = "shark, tuna"
              with open(self.fish_tank_file_name, "w") as f:
          def empty_tank(self):
      class TestAdvancedFishTank(unittest.TestCase):
          def setUp(self):
              self.fish_tank = AdvancedFishTank()
          def tearDown(self):
          def test_fish_tank_writes_file(self):
              with open(self.fish_tank.fish_tank_file_name) as f:
                  contents =
              self.assertEqual(contents, "shark, tuna")
     defines a class named AdvancedFishTank. AdvancedFishTank creates a file named fish_tank.txt and writes the string "shark, tuna" to it. AdvancedFishTank also exposes an empty_tank method that removes the fish_tank.txt file. The TestAdvancedFishTank TestCase subclass defines both a setUp and tearDown method.

      The setUp method creates an AdvancedFishTank instance and assigns it to self.fish_tank. The tearDown method calls the empty_tank method on self.fish_tank: this ensures that the fish_tank.txt file is removed after each test method runs. This way, each test starts with a clean slate. The test_fish_tank_writes_file method verifies that the default contents of "shark, tuna" are written to the fish_tank.txt file.

      From the same directory as let’s run:

      • python -m unittest

      We will receive the following output:


      . ---------------------------------------------------------------------- Ran 1 test in 0.000s OK

      tearDown allows you to write cleanup code that is run for all of your tests in a TestCase subclass.


      In this tutorial, you have written TestCase classes with different assertions, used the setUp and tearDown methods, and run your tests from the command line.

      The unittest module exposes additional classes and utilities that you did not cover in this tutorial. Now that you have a baseline, you can use the unittest module’s documentation to learn more about other available classes and utilities. You may also be interested in How To Add Unit Testing to Your Django Project.

      Source link