One place for hosting & domains

      Write

      How To Write Doctests in Python


      Introduction

      Documentation and testing are core components of every productive software development process. Ensuring that code is thoroughly documented and tested not only ensures that a program runs as expected, but also supports collaboration across programmers as well as user adoption. A programmer can be well served by first writing documentation and then tests, before finally writing code. Following a process like this will ensure that the function one is coding (for example) is well thought out and addresses possible edge cases.

      Python’s standard library comes equipped with a test framework module called doctest. The doctest module programmatically searches Python code for pieces of text within comments that look like interactive Python sessions. Then, the module executes those sessions to confirm that the code referenced by a doctest runs as expected.

      Additionally, doctest generates documentation for our code, providing input-output examples. Depending on how you approach writing doctests, this can either be closer to either “‘literate testing’ or ‘executable documentation,’” as the Python Standard Library documentation explains.

      Doctest Structure

      A Python doctest is written as though it is a comment, with a series of three quotation marks in a row — """ — at the top and bottom of the doctest.

      Sometimes, doctests are written with an example of the function and the expected output, but it may be preferable to also include a comment on what the function is intended to do. Including a comment will ensure that you as the programmer have sharpened your goals, and a future person reading the code understands it well. Remember, the future programmer reading the code may very well be you.

      The following is a mathematical example of a doctest for a function such as add(a, b) that adds two numbers together:

      """
      Given two integers, return the sum.
      
      >>> add(2, 3)
      5
      """
      

      In this example we have a line of explanation, and one example of the add() function with two integers for input values. If in the future you want the function to be able to add more than two integers, you would need to revise the doctest to match the function’s inputs.

      So far, this doctest is very readable to a human. You can further iterate on this docstring by including machine-readable parameters and a return description to explicate each variable coming in and out of the function.

      Here, we’ll add docstrings for the two arguments that are passed to the function and the value that is returned. The docstring will note the data types for each of the values — the parameter a, the parameter b, and the returned value — in this case they are all integers.

      """
      Given two integers, return the sum.
      
      :param a: int
      :param b: int
      :return: int
      
      >>> add(2, 3)
      5
      """
      

      This doctest is now ready to be incorporated into a function and tested.

      Incorporating a Doctest into a Function

      Doctests sit within a function after the def statement and before the code of the function. As this follows the initial definition of the function, it will be indented following Python’s conventions.

      This short function indicates how the doctest is incorporated.

      def add(a, b):
          """
          Given two integers, return the sum.
      
          :param a: int
          :param b: int
          :return: int
      
          >>> add(2, 3)
          5
          """
          return a + b
      
      

      In our short example, we only have this one function in our program, so now we will have to import the doctest module and have a call statement for the doctest to run.

      We’ll be adding the following lines before and after our function:

      import doctest 
      ...
      doctest.testmod()
      

      At this point, let’s test it on the Python shell rather than saving it to a program file right now. You can access a Python 3 shell on your command line terminal of choice (including IDE terminal) with the python3 command (or python if you’re using a virtual shell).

      If you go this route, once you press ENTER, you’ll receive output similar to the following:

      Output

      Type "help", "copyright", "credits" or "license" for more information. >>>

      You’ll be able to start typing code after the >>> prompt.

      Our complete example code, including the add() function with a doctest, docstrings, and a call to invoke the doctest follows. You can paste it into your Python interpreter to try it out:

      import doctest
      
      
      def add(a, b):
          """
          Given two integers, return the sum.
      
          :param a: int
          :param b: int
          :return: int
      
          >>> add(2, 3)
          5
          """
          return a + b
      
      doctest.testmod()
      
      

      Once you run the code, you’ll receive the following output:

      Output

      TestResults(failed=0, attempted=1)

      This means that our program ran as expected!

      If you modify the program above so that the return a + b line is instead return a * b, which modifies the function to multiply integers and return their product instead, you’ll receive a failure notice:

      Output

      ********************************************************************** File "__main__", line 9, in __main__.add Failed example: add(2, 3) Expected: 5 Got: 6 ********************************************************************** 1 items had failures: 1 of 1 in __main__.add ***Test Failed*** 1 failures. TestResults(failed=1, attempted=1)

      From the output above, you can begin to understand how useful the doctest module is as it fully describes what happened when a and b were multiplied instead of added, returning the product of 6 in the example case.

      You may want to experiment with more than one example. Let’s try with an example where both variables a and b contain the value of 0, and change the program back to addition with the + operator.

      import doctest
      
      
      def add(a, b):
          """
          Given two integers, return the sum.
      
          :param a: int
          :param b: int
          :return: int
      
          >>> add(2, 3)
          5
          >>> add(0, 0)
          0
          """
          return a + b
      
      doctest.testmod()
      
      

      Once we run this, we’ll receive the following feedback from the Python interpreter:

      Output

      TestResults(failed=0, attempted=2)

      Here, the output indicates that the doctest attempted two tests, on both lines of add(2, 3) and add(0, 0) and that both passed.

      If, again, we change the program to use the * operator for multiplication rather than the + operator, we can learn that edge cases are important when working with the doctest module, because the second example of add(0, 0) will return the same value whether it is addition or multiplication.

      import doctest
      
      
      def add(a, b):
          """
          Given two integers, return the sum.
      
          :param a: int
          :param b: int
          :return: int
      
          >>> add(2, 3)
          5
          >>> add(0, 0)
          0
          """
          return a * b
      
      doctest.testmod()
      
      

      The following output is returned:

      Output

      ********************************************************************** File "__main__", line 9, in __main__.add Failed example: add(2, 3) Expected: 5 Got: 6 ********************************************************************** 1 items had failures: 1 of 2 in __main__.add ***Test Failed*** 1 failures. TestResults(failed=1, attempted=2)

      When we modify the program, only one of the examples fails, but it is fully described as before. If we had started with the add(0, 0) example rather than the add(2, 3) example, we may not have noticed that there were opportunities for failure when small components of our program change.

      Doctests in Programming Files

      So far, we have used an example on the Python interactive terminal. Let’s now use it in a programming file that will count the number of vowels in a single word.

      In a program, we can import and call the doctest module in our if __name__ == "__main__": clause at the bottom of our programming file.

      We’ll create a new file — counting_vowels.py — in our text editor, you can use nano on the command line, like so:

      We can begin with defining our function count_vowels and passing the parameter of word to the function.

      counting_vowels.py

      def count_vowels(word):
      
      

      Before we write the body of the function, let’s explain what we want the function to do in our doctest.

      counting_vowels.py

      def count_vowels(word):
          """
          Given a single word, return the total number of vowels in that single word.
      
      

      So far so good, we are being pretty specific. Let’s flesh this out with the data type of the parameter word and the data type we want returned. In the first case it’s a string, in the second case it’s an integer.

      counting_vowels.py

      def count_vowels(word):
          """
          Given a single word, return the total number of vowels in that single word.
      
          :param word: str
          :return: int
      

      Next, let’s find examples. Think of a single word that has vowels, and then type it into the docstring.

      Let’s choose the word 'Cusco' for the city in Peru. How many vowels are in “Cusco”? In English, vowels are often considered to be a, e, i, o, and u. So here we will count u and o as the vowels.

      We’ll add the test for Cusco and the return of 2 as the integer into our program.

      counting_vowels.py

      def count_vowels(word):
          """
          Given a single word, return the total number of vowels in that single word.
      
          :param word: str
          :return: int
      
          >>> count_vowels('Cusco')
          2
      

      Again, it’s a good idea to have more than one example. Let’s have another example with more vowels. We’ll go with 'Manila' for the city in the Philippines.

      counting_vowels.py

      def count_vowels(word):
          """
          Given a single word, return the total number of vowels in that single word.
      
          :param word: str
          :return: int
      
          >>> count_vowels('Cusco')
          2
      
          >>> count_vowels('Manila')
          3
          """
      

      Those doctests look great, now we can code our program.

      We’ll start with initializing a variable — total_vowels to hold the vowel count. Next, we’ll create a for loop to iterate across the letters of the word string, and then include a conditional statement to check whether each letter is a vowel. We’ll increase the vowel count through the loop, then return the total number of vowels in the word to the total_values variable. Our program should be similar to this, without the doctest:

      def count_vowels(word):
          total_vowels = 0
          for letter in word:
              if letter in 'aeiou':
                  total_vowels += 1
          return total_vowels
      

      If you need more guidance on these topics, please check out our How To Code in Python book or complementary series.

      Next, we’ll add our main clause at the bottom of the program and import and run the doctest module:

      if __name__ == "__main__":
          import doctest
          doctest.testmod()
      

      At this point, here is our program:

      counting_vowels.py

      def count_vowels(word):
          """
          Given a single word, return the total number of vowels in that single word.
      
          :param word: str
          :return: int
      
          >>> count_vowels('Cusco')
          2
      
          >>> count_vowels('Manila')
          3
          """
          total_vowels = 0
          for letter in word:
              if letter in 'aeiou':
                  total_vowels += 1
          return total_vowels
      
      if __name__ == "__main__":
          import doctest
          doctest.testmod()
      
      

      We can run the program by using the python (or python3 depending on your virtual environment) command:

      • python counting_vowels.py

      If your program is identical to the above, all the tests should have passed and you will not receive any output. This means that the tests passed. This silent feature is useful when you are running programs for other purposes. If you are running specifically to test, you may want to use the -v flag, as below.

      • python counting_vowels.py -v

      When you do, you should receive this output:

      Output

      Trying: count_vowels('Cusco') Expecting: 2 ok Trying: count_vowels('Manila') Expecting: 3 ok 1 items had no tests: __main__ 1 items passed all tests: 2 tests in __main__.count_vowels 2 tests in 2 items. 2 passed and 0 failed. Test passed.

      Excellent! The test has passed. Still, our code may not be quite optimized for all edge cases yet. Let’s learn how to use doctests to strengthen our code.

      Using Doctests to Improve Code

      At this point, we have a working program. Maybe it is not the best program it can be yet, so let’s try to find an edge case. What if we add an upper-case vowel?

      Add another example in the doctest, this time let’s try 'Istanbul' for the city in Turkey. Like Manila, Istanbul also has three vowels.

      Below is our updated program with the new example.

      counting_vowels.py

      def count_vowels(word):
          """
          Given a single word, return the total number of vowels in that single word.
      
          :param word: str
          :return: int
      
          >>> count_vowels('Cusco')
          2
      
          >>> count_vowels('Manila')
          3
      
          >>> count_vowels('Istanbul')
          3
          """
          total_vowels = 0
          for letter in word:
              if letter in 'aeiou':
                  total_vowels += 1
          return total_vowels
      
      if __name__ == "__main__":
          import doctest
          doctest.testmod()
      
      

      Let’s run the program again.

      • python counting_vowels.py

      We have identified an edge case! Below is the output we have received:

      Output

      ********************************************************************** File "counting_vowels.py", line 14, in __main__.count_vowels Failed example: count_vowels('Istanbul') Expected: 3 Got: 2 ********************************************************************** 1 items had failures: 1 of 3 in __main__.count_vowels ***Test Failed*** 1 failures.

      The output above indicates that the test on 'Istanbul' is the one that failed. We told the program we were expecting three vowels to be counted, but instead the program counted only two. What went wrong here?

      In our line if letter in 'aeiou': we have only passed in lower-case vowels. We can modify our 'aeiou' string to be 'AEIOUaeiou' to count both upper- and lower-case vowels, or we can do something more elegant, and convert our value stored in word to lower-case with word.lower(). Let’s do the latter.

      counting_vowels.py

      def count_vowels(word):
          """
          Given a single word, return the total number of vowels in that single word.
      
          :param word: str
          :return: int
      
          >>> count_vowels('Cusco')
          2
      
          >>> count_vowels('Manila')
          3
      
          >>> count_vowels('Istanbul')
          3
          """
          total_vowels = 0
          for letter in word.lower():
              if letter in 'aeiou':
                  total_vowels += 1
          return total_vowels
      
      if __name__ == "__main__":
          import doctest
          doctest.testmod()
      
      

      Now, when we run the program, all tests should pass. You can confirm again by running python counting_vowels.py -v with the verbose flag.

      Still, this probably is not the best program it can be, and it may not be considering all edge cases.

      What if we pass the string value 'Sydney' — for the city in Australia — to word? Would we expect three vowels or one? In English, y is sometimes considered to be a vowel. Additionally, what would happen if you use the value 'Würzburg' — for the city in Germany — would the 'ü' count? Should it? How will you handle other non-English words? How will you handle words that use different character encodings, such as those available in UTF-16 or UTF-32?

      As a software developer, you will sometimes need to make tricky decisions like deciding which characters should be counted as vowels in the example program. Sometimes there may not be a right or wrong answer. In many cases, you will not consider the full scope of possibilities. The doctest module is therefore a good tool to start to think through possible edge cases and capture preliminary documentation, but ultimately you will need human user testing — and very likely collaborators — to build robust programs that serve everyone.

      Conclusion

      This tutorial introduced the doctest module as not only a method for testing and documenting software, but also as a way to think through programming before you begin, by first documenting it, then testing it, then writing the code.

      Not writing tests could lead not only to bugs but software failure. Getting in the habit of writing tests prior to writing code can support productive software that serves other developers and end users alike.

      If you would like to learn more about testing and debugging, check out our “Debugging Python Programs” series. We also have a free eBook on How To Code in Python and another on Python Machine Learning Projects.



      Source link

      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.

      Introduction

      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.

      Prerequisites

      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:

      ./math/math.go

      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:

      ./math/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:

      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:

      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:

      ./math/math_test.go

      
      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:

      Output

      === 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:

      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:

      ./math_test.go

      ...
      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:

      Output

      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:

      ./math/math_test.go

      
      package math
      
      import (
          "fmt"
          "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)
              }
          }
      }
      
      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:

      Output

      === 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.

      Conclusion

      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.

      Research

      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.

      Design

      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!

      SEMrush

      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 WordPress.org 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.

      Video

      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.

      Analytics

      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