Base API Methods, Settings & Hooks

In this section, we will create our base methods to authenticate with the Twitter APIs via OAuth, as well as set the Base URL.  We will then create our @Before hooks to perform certain functions before a test scenario or feature is run, when that feature or scenario has the “Api” tag.

Settings

Now that we have all the parameters and information we need to successfully OAuth1 with the Twitter API, let’s add that information to our ‘Settings’ class.

  1. Open up the ‘Settings’ class in the ‘Utils.Settings’ nested namespace and edit the class file to include public static string variables for the following parameters…
    • BaseUrl – the base URL for our API tests (e.g. ‘https://api.twitter.com/1.1/statuses’ )
    • ConsumerKey – the Consumer Key value given to us by Twitter
    • ConsumerSecret – the Consumer Secret value given to us by Twitter
    • Token – the Access Token value given to us by Twitter
    • TokenSecret – the Access Token Secret value given to us by Twitter
      (Note that your values will be different to mine, they are unique to every different Twitter account)

      namespace ProductAutomation.Utils.Settings
      {
          public class Settings
          {
              public static readonly string baseUrl = "https://api.twitter.com/1.1/statuses";
              public static readonly string consumerKey = "Ra8DdzaIulRSY9bm9zE61DRyh"; //replace with your consumer key
              public static readonly string consumerSecret = "1QGF1R8QbfNR2SvcM8zjGmROTx0kwjcDlLNlPAlRxgWQjp39xf"; // replace with your consumer secret
              public static readonly string accessToken = "394853867-6gJTO7z8D11Paa4eox4YAB5jYmVPmq5F2idHU0ME"; // replace with your access token
              public static readonly string accessTokenSecret = "Bcdpa3JfxXKdPJKHvKwAHLmE8khY90nfoPlegGgC09s2p"; // replace your access token secret
          }
      }

Creating Base Methods

AuthTwitter() Method

In this method, we will use the 4 parameters in our ‘Settings’ class to authenticate with Twitter via OAuth1. We will be calling this method from another method in this class, so we can make its access private.

  1. Add the following private method into the ‘BaseApiTests’ class file…
    private static OAuth1Authenticator AuthTwitter()
    {
        OAuth1Authenticator oAuth1Authenticator = OAuth1Authenticator.ForProtectedResource(consumerKey, consumerSecret, accessToken, accessTokenSecret);
        return oAuth1Authenticator;
    }

    Ensure the using directive for RestSharp.Authenticators has been added…

    using RestSharp.Authenticators;

In our AuthTwitter() method, we set the return type to OAuth1Authenticator, and then set an OAuth1Authenticator variable to the OAuth1Authenticator.ForProtectedResource method, to login with our 4 parameters.  Finally we return it so we can use it in other methods and be authenticated.

SetBaseUriAndAuth() Method

In this method, we will get RestSharp to set the Client BaseURI to the baseUrl we set in our ‘Settings’ class. We will then set the authentication of the client to OAuth, via our AuthTwitter() method we made previously.

  1. Open up the ‘BaseApiTests’ class file and add the following static variables inside the class (but outside of any methods)…
    public static RestClient Client;
    public static IRestRequest Request;
    public static IRestResponse Response;
  2. Open up the ‘BaseApiTests’ class file and add the following method, which will set the client to the correct base URL and then authenticate for us by calling the AuthTwitter() method when we set Client.Authenticator…
    public static void SetBaseUriAndAuth()
    {
        Client = new RestClient(baseUrl);
        Client.Authenticator = AuthTwitter();
    }

    The whole thing should look like below when done…

    using RestSharp;
    using RestSharp.Authenticators;
    using static ProductAutomation.Utils.Settings.Settings;
    
    namespace RestAutomation.Apis
    {
        public class BaseApiTests
        {
            public static RestClient Client;
            public static IRestRequest Request;
            public static IRestResponse Response;
    
            public static void SetBaseUriAndAuth()
            {
                Client = new RestClient(baseUrl);
                Client.Authenticator = AuthTwitter();
            }
    
            private static OAuth1Authenticator AuthTwitter()
            {
                OAuth1Authenticator oAuth1Authenticator = OAuth1Authenticator.ForProtectedResource(consumerKey, consumerSecret, accessToken, accessTokenSecret);
                return oAuth1Authenticator;
            }    
        }
    }

Hooks

We will now add hooks to set the BaseUri before our features and/or scenarios are run. Please see https://github.com/techtalk/SpecFlow/wiki/Hooks for more information

FeatureHooks

  1. Open up the ‘FeatureHooks’ class file in the ‘Utils.Hooks’ nested namespace and add the following code to set the BaseUri before any features marked with the ‘@Api’ tag are run…
    using System.Linq;
    using ProductAutomation.Apis;
    using TechTalk.SpecFlow;
    
    namespace RestAutomation.Utils.Hooks
    {
        [Binding]
        internal static class FeatureHooks
        {
            [BeforeFeature()]
            internal static void BeforeHooks()
            {
                if (FeatureContext.Current.FeatureInfo.Tags.Contains("Api"))
                {
                    BaseApiTests.SetBaseUriAndAuth();
                }
            }
        }
    }

ScenarioHooks

  1. Open up the ‘ScenarioHooks’ class file in the ‘Utils.Hooks’ nested namespace and add the following code to set the BaseUri before any scenarios marked with the ‘@Api’ tag are run…
    using System.Linq;
    using ProductAutomation.Apis;
    using TechTalk.SpecFlow;
    
    namespace RestAutomation.Utils.Hooks
    {
        [Binding]
        internal static class ScenarioHooks
        {
            [BeforeScenario()]
            internal static void BeforeHooks()
            {
                if (ScenarioContext.Current.ScenarioInfo.Tags.Contains("Api"))
                {
                    BaseApiTests.SetBaseUriAndAuth();
                }
            }
        }
    }

    In the next section, we will start to create our test scenarios 🙂

Digiprove sealCopyright secured by Digiprove © 2018
Liked it? Take a second to support Thomas on Patreon!

Previous Article

Next Article

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.