Trending December 2023 # Selenium Framework: Data, Keyword & Hybrid Driven # Suggested January 2024 # Top 15 Popular

You are reading the article Selenium Framework: Data, Keyword & Hybrid Driven updated in December 2023 on the website Hatcungthantuong.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested January 2024 Selenium Framework: Data, Keyword & Hybrid Driven

What is Selenium Framework?

The Selenium automation Framework is a code structure that makes code maintenance easy and efficient. Without frameworks, users may place the “code” and “data” at the same location which is neither reusable nor readable. Frameworks produce beneficial outcomes like increased code reusability, higher portability, reduced cost of script maintenance, better code readability, etc.

Types of Selenium Framework

There are mainly three type of frameworks created by Selenium WebDriver to automate manual test cases

Data Driven Framework

Keyword Driven Framework

Hybrid Driven Framework

Data Driven Framework in Selenium

Data Driven Framework in Selenium is a method of separating data sets from the test case. Once the data sets are separated from the test case, it can be easily modified for a specific functionality without changing the code. It is used to fetch test cases and suites from external files like Excel, .csv, .xml or some database tables.

To read or write an Excel, Apache provides a very famous library POI. This library is capable enough to read and write both XLS and XLSX file format of Excel.

To read XLSX, XSSF implementation of POI library will be the choice. Let’s study these implementations in detail.

To readimplementation ofwill be the choice. Let’s study these implementations in detail.

We already learned about Data Driven Testing in our previous tutorial

Keyword Driven Framework in Selenium

Keyword Driven Framework in Selenium is a method used for speeding up automated testing by separating keywords for common set of functions and instructions. All the operations and instructions to be performed are written in some external file like an Excel sheet. Users can easily control and specify the functionalities they want to test.

Here is how the complete framework looks like

As you can see it’s a 5 step framework. Let’s study it stepwise in detail

As you can see it’s a 5 step framework. Let’s study it stepwise in detail

Step 1)

The driver script chúng tôi will call ReadGuru99ExcelFile.java

ReadGuru99ExcelFile.java has POI script to read data from an Excel

Step 2)

ReadGuru99ExcelFile.java will read data from TestCase.xlsx

Here is how the sheet looks like-

According to the keywords written in Excel file, the framework will perform the operation on UI.

Step 3) chúng tôi will pass this data to the driver script Execute.java

Step 4)

For all of our UI web elements, we need to create an object repository where we will place their element locator (like Xpath, name, CSS path, class name etc.)

Execute.java (our driver script) will read the entire Object Repository and store it in a variable

To read this object repository, we need a ReadObject class which has a getObjectRepository method to read it.

NOTE: You may think why do we need to create an object repository. The answer helps in code maintenance. For example, we are using the button with name = btnlogin in 10 different test cases. In future, the developer decides to change the name from btnlogin to submit. You will have to make a change in all the 10 test cases. In the case of an object repository, you will make the change just once in the repository.

Step 5)

The driver will pass the data from Excel & Object Repository to UIOperation class

UIOperation class has functions to perform actions corresponding to keywords like CLICK, SETTEXT etc… mentioned in the excel

UIOperation class is a Java class which has the actual implementation of the code to perform operations on web elements

The complete project will look like-

Let’s look into an example:

Test Scenario: We are executing 2 test cases

Test Case 1:

Enter User ID

Enter Password

Test Case 2:

Enter User ID

Enter Password

object.properties

username=uid password=password title=barone loginButton=btnLogin resetButton=btnReset

ReadGuru99ExcelFile.java package excelExportAndFileIO; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ReadGuru99ExcelFile { public Sheet readExcel(String filePath,String fileName,String sheetName) throws IOException{ File file = new File(filePath+"\"+fileName); FileInputStream inputStream = new FileInputStream(file); Workbook guru99Workbook = null; String fileExtensionName = fileName.substring(fileName.indexOf(".")); if(fileExtensionName.equals(".xlsx")){ guru99Workbook = new XSSFWorkbook(inputStream); } else if(fileExtensionName.equals(".xls")){ guru99Workbook = new HSSFWorkbook(inputStream); } Sheet guru99Sheet = guru99Workbook.getSheet(sheetName); return guru99Sheet; } } ReadObject.java package operation; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class ReadObject { Properties p = new Properties(); public Properties getObjectRepository() throws IOException{ InputStream stream = new FileInputStream(new File(System.getProperty("user.dir")+"\src\objects\object.properties")); p.load(stream); return p; } } UIOperation.java package operation; import java.util.Properties; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; public class UIOperation { WebDriver driver; public UIOperation(WebDriver driver){ this.driver = driver; } public void perform(Properties p,String operation,String objectName,String objectType,String value) throws Exception{ System.out.println(""); switch (operation.toUpperCase()) { case "CLICK": break; case "SETTEXT": driver.findElement(this.getObject(p,objectName,objectType)).sendKeys(value); break; case "GOTOURL": driver.get(p.getProperty(value)); break; case "GETTEXT": driver.findElement(this.getObject(p,objectName,objectType)).getText(); break; default: break; } } /** * Find element BY using object type and value * @param p * @param objectName * @param objectType * @return * @throws Exception */ private By getObject(Properties p,String objectName,String objectType) throws Exception{ if(objectType.equalsIgnoreCase("XPATH")){ return By.xpath(p.getProperty(objectName)); } else if(objectType.equalsIgnoreCase("CLASSNAME")){ return By.className(p.getProperty(objectName)); } else if(objectType.equalsIgnoreCase("NAME")){ return By.name(p.getProperty(objectName)); } else if(objectType.equalsIgnoreCase("CSS")){ return By.cssSelector(p.getProperty(objectName)); } else if(objectType.equalsIgnoreCase("LINK")){ return By.linkText(p.getProperty(objectName)); } else if(objectType.equalsIgnoreCase("PARTIALLINK")){ return By.partialLinkText(p.getProperty(objectName)); }else { throw new Exception("Wrong object type"); } } } ExecuteTest.java package testCases; import java.util.Properties; import operation.ReadObject; import operation.UIOperation; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.Test; import excelExportAndFileIO.ReadGuru99ExcelFile; public class ExecuteTest { @Test public void testLogin() throws Exception { WebDriver webdriver = new FirefoxDriver(); ReadGuru99ExcelFile file = new ReadGuru99ExcelFile(); ReadObject object = new ReadObject(); Properties allObjects = object.getObjectRepository(); UIOperation operation = new UIOperation(webdriver); Sheet guru99Sheet = file.readExcel(System.getProperty("user.dir")+"\","TestCase.xlsx" , "KeywordFramework"); int rowCount = guru99Sheet.getLastRowNum()-guru99Sheet.getFirstRowNum(); for (int i = 1; i < rowCount+1; i++) { Row row = guru99Sheet.getRow(i); if(row.getCell(0).toString().length()==0){ operation.perform(allObjects, row.getCell(1).toString(), row.getCell(2).toString(), row.getCell(3).toString(), row.getCell(4).toString()); } else{ } } } }

After execution, output will look like –

Download the Selenium Project Files for the Demo in this Tutorial

Hybrid Driven Framework

Here for keywords, we will use Excel files to maintain test cases, and for test data, we can use data, provider of Testng framework.

Here in our hybrid framework, we don’t need to change anything in Keyword driven framework, here we just need to replace chúng tôi file with chúng tôi file.

This HybridExecuteTest file has all the code for keyword driven with data provider concept.

The complete pictorial representation of hybrid framework will look like

HybridExecuteTest.java package testCases; import java.io.IOException; import java.util.Properties; import operation.ReadObject; import operation.UIOperation; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import excelExportAndFileIO.ReadGuru99ExcelFile; public class HybridExecuteTest { WebDriver webdriver = null; @Test(dataProvider="hybridData") public void testLogin(String testcaseName,String keyword,String objectName,String objectType,String value) throws Exception { if(testcaseName!=null&&testcaseName.length()!=0){ webdriver=new FirefoxDriver(); } ReadObject object = new ReadObject(); Properties allObjects = object.getObjectRepository(); UIOperation operation = new UIOperation(webdriver); operation.perform(allObjects, keyword, objectName, objectType, value); } @DataProvider(name="hybridData") public Object[][] getDataFromDataprovider() throws IOException{ Object[][] object = null; ReadGuru99ExcelFile file = new ReadGuru99ExcelFile(); Sheet guru99Sheet = file.readExcel(System.getProperty("user.dir")+"\","TestCase.xlsx" , "KeywordFramework"); int rowCount = guru99Sheet.getLastRowNum()-guru99Sheet.getFirstRowNum(); object = new Object[rowCount][5]; for (int i = 0; i < rowCount; i++) { Row row = guru99Sheet.getRow(i+1); for (int j = 0; j < row.getLastCellNum(); j++) { object[i][j] = row.getCell(j).toString(); } } System.out.println(""); return object; } } Summary:

We can create three types of test framework using Selenium WebDriver.

A Selenium automation framework that can be classified into Data Driven, Keyword Driven, and Hybrid Frameworks.

We can achieve Data-driven framework using TestNG’s data provider.

In Keyword driven framework, keywords are written in some external files like excel file and java code will call this file and execute test cases.

The hybrid framework is a mix of keyword driven and data driven framework.

Download the Selenium Project Files for the Demo in this Tutorial

You're reading Selenium Framework: Data, Keyword & Hybrid Driven

What Are Assertions In Selenium With Python?

There are assertions in Selenium which are verification or checkpoints for the test case. In the absence of an assertion, there is no option of determining if a test case has failed or not.

Sometimes, we may use the conditional statements like if – else and so on and then print the result of pass/ fail in the console. But that can only solve the problem of checking logs and not for actual reporting.

Thus assertion is used for generating test execution reports. In case, our test case passes all the test steps, the assertions do not impact the test cases in any way, however if the test case fails, it is reported.

A test case can contain numerous methods of assertions. Some of them can accept values of all data types and some will only have numeric values. The different types of assertions are listed below −

assertEqual – This assertion has two parameters. A comparison is done between the first and second parameter. In case both of them match, the test case is considered a pass; else the test case is failed.

The third parameter of assertEqual is an optional one. It is mostly used for informational purposes for result analysis.

Syntax assertEqual("Tutorialspoint", "Tutorialspoint")

assertNotEqual – This assertion can have more than two parameters. A comparison is done between the first and second parameter. In case both of them do not match, the test case is considered a pass; else the test case is failed.

The third parameter of assertEqual is an optional one. It is mostly used for informational purposes for result analysis.

Syntax assertNotEqual("Tutorials", "Tutorialspoint")

assertTrue – This assertion can handle more than two parameters. A comparison is done between the first and second parameter. In case both of them do match, the test case is considered a pass; else the test case is failed.

The assertTrue assertion allows the use of relational operators for comparison. In these situations, the result is in Boolean (True or False). The final parameter of this assertion can contain informational messages used for result analysis.

Syntax assertTrue((hd="Tutorialspoint") OR (hd="Selenium"),"Matching header")

assertFalse – This assertion can handle more than two parameters. A comparison is done between the first and second parameter. In case both of them do not match, the test case is considered a pass; else the test case is failed.

The assertTrue assertion allows the use of relational operators for comparison. In these situations, the result is in Boolean (True or False). The final parameter of this assertion can contain informational messages used

assertIs – This assertion can handle two parameters. A comparison is done between the first and second parameter. In case both of them match, the test case is considered a pass; else the test case is failed.

The third parameter of assertEqual is an optional one. It is mostly used for informational purposes for result analysis.

Syntax assertIs(Tutorialspoint", "Tutorialspoint", "Both are equal")

assertIsNot – This assertion can handle two parameters. A comparison is done between the first and second parameter. In case both of them do not match, the test case is considered a pass; else the test case is failed. The final parameter of this assertion can contain informational messages used for result analysis.

The final parameter of this assertion can contain informational messages used for result analysis.

Syntax assertIsNot(Tutorialspoint", "Tutorials", "Both are not equal")

assertIsNone – This assertion can handle a parameter. It is used to check if the value provided is none. If the result is equal to none, the test case is considered a pass; else the test case is failed.

The final parameter of this assertion can contain informational messages used for result analysis.

Syntax assertIsNone( result, "The result is equal to none")

assertIsNotNone – This assertion can handle a parameter. It is used to check if the value provided is none. If the result is not equal to none, the test case is considered a pass; else the test case is failed.

The final parameter of this assertion can contain informational messages used for result analysis.

Syntax assertIsNotNone( r, "The result is not equal to none")

assertIn – This assertion has two parameters. It is used to check if the first parameter exists in the second parameter. If the item is present in the second element, the test case is considered a pass; else the test case is failed. The third parameter of assertIs is an optional one. It is mostly used for informational purposes for result analysis.

This type of assertion is mostly used in set, list, tuple and dictionary.

Syntax s = set(["PLSQL", "Selenium", "Jmeter"]) assertIn("Selenium", s, " Selenium is present in set s")

assertNotIn – This assertion has two parameters. It is used to check if the first parameter exists in the second parameter. If the item is not present in the second element, the test case is considered a pass; else the test case is failed.

The third parameter of assertIs is an optional one. It is mostly used for informational purposes for result analysis.

This type of assertion is mostly used in set, list, tuple and dictionary.

Syntax s = set(["PLSQL", "Selenium", "Jmeter"]) assertIn("Oracle", s, " Oracle is not present in set s")

assertIsInstance – This assertion has two parameters. It is used to check if the given object( in the first parameter) is an instance of the class( in the second parameter). If yes, the test case is considered a pass; else the test case is failed.

The third parameter of assertIs is an optional one. It is mostly used for informational purposes for result analysis.

Syntax Cl1 c = new Cl1() assertIsInstance(c, Cl1, " c is an instance of Cl1")

assertIsNotInstance – This assertion has two parameters. It is used to check if the given object( in the first parameter) is an instance of the class( in the second parameter). If no, the test case is considered a pass; else the test case is failed.

The third parameter of assertIs is an optional one. It is mostly used for informational purposes for result analysis.

Syntax Cl1 c = new Cl1() assertIsInstance(d, Cl1, " d is not an instance of Cl1")

assertListEqual – This assertion has two parameters. It is used to check if the two lists mentioned in the parameter are similar or not. If there is any missing or not similar element, it is printed as an error message.

assertTupleEqual – This assertion has two parameters. It is used to check if the two tuples mentioned in the parameter are similar or not. If there is any missing or not similar element, it is printed as an error message.

assertSetEqual – This assertion has two parameters. It is used to check if the two sets mentioned in the parameter are similar or not. If there is any missing or not similar element, it is printed as an error message.

assertDictEqual – This assertion has two parameters. It is used to check if the two dictionaries mentioned in the parameter are similar or not. If there is any missing or not similar element, it is printed as an error message.

What Is The ‘Some’ Keyword In Swiftui?

The “some” keyword in SwiftUI is used to indicate that a type conforms with a protocol, but the exact conformance is not specified. The AnyView type, a type-erased view that can represent any view conforming to the View protocol, is commonly used in association with it.

SwiftUI defines some View as a type that, without identifying the specific view type, can represent any view that complies with the View protocol. This enables more generalized and adaptable code.

In other words, some keyword is used to declare Opaque types. In the Swift 5.1 version, this is introduced with the support of opaque return types.

What are opaque types?

When you use opaque type, it means you can declare the expected return type without defining an exact type.

For example, you can use some View to create a variable that can hold any view, without knowing the specific type of the view. Here is an example:

let anyView: some View = Text("Hello, World!")

This creates a variable named anyView that can hold any view conforming to the View protocol, and assigns it the value of a Text view displaying the string “Hello, World!”.

In order to create a variable that can hold any conforming type to a protocol without knowing the particular type it will carry, some keyword is used as a type constraint.

Return opaque type without matching exact type

What will happen if we do not return the exact type? In this case, you will get an error like the one below.

Example

An example of code that contains the error looks as follows −

import SwiftUI if isProUser { return Text("You have a premium membership !!") } else { Text("Do you want to become a PRO user?") Button("Become PRO", action: { }) } } } Output

This code will give you an error that looks like this:

error: function declares an opaque return type 'some View', but the return statements in its body do not have matching underlying types

As you can see in the above code, we are returning two types of data. Returning a Text for PRO users and a VStack for the non-premium users.

In this case, the compiler wants to know the underlying concrete type through the “some” keyword. In order to return different types within the same method scope, opaque types must be fixed for the scope of the value.

We could solve the above code by using a wrapping container, like a VStack −

import SwiftUI VStack { if isProUser { Text("You have a premium membership !!") } else { Text("Do you want to become a PRO user?") Button("Become PRO", action: { }) } } }

We have added an additional container, which will only be needed if the isProUser property returns true. Instead of using result builders in the above code, it’s better to rewrite it using the @ViewBuilder attribute −

import SwiftUI @ViewBuilder if isProUser { Text("You have a premium membership !!") } else { Text("Do you want to become a PRO user?") Button("Become PRO", action: { }) } } Conclusion

In conclusion, the “some” keyword in SwiftUI is used to tell the compiler the return type without telling the exact type of returned view. In this way, you can hide critical information.

In order to return the “some” type, you can use the wrapper as a container. Also, you can use the @ViewBuilder attribute instead of the result builder.

Top 6 Keyword Research Tools For Blogger – Webnots

Proper keyword research is vital to blogging for good SEO purposes. Solid keyword planning is the foundation of your content strategy and it goes a long way in influencing the success of your blog. A well-thought-out and researched keyword serves as a source of high-quality web traffic to your blog.

Learn WordPress: Check out 500+ free WordPress tutorials.

Therefore, keyword research is the front and center of many good SEO practices. If you are not using proper keywords, it will greatly hinder the success of your blog. This is enough reason to take your time on keyword research and pinpoint your content strategy in the right direction. You can use several keyword tools for your blog but the best version out there is what we have compiled in this list.

Ahrefs Overview

You get access to data like search volume, allows you a 7-day trial offer on two of their plans, which are standard and lite. Then you have to subscribe and pay for any plan of your choosing out of four plans.

Keyword Overview SEMrush

Other features that tool possess include global CPC distribution stats, the discovery of long-tail keywords, annual keyword trends among others. There is a 7-day free trial. Then you will need to subscribe to a plan.

Google Keyword Planner

The keyword research tool is not complete if there is no mention of the Google keyword planner. Many regard it as the redefining keyword tool. Although the tool serves you with the most basic features, the accuracy is what makes it a standout. Its data comes straight from Google and the outcome of the keyword research blend well with the monetization of AdSense.

Google Keyword Planner Keyword Research

Even thou, the research tool itself is free; however, you must possess an AdWords account to utilize it. The way Google keyword planner presents your keyword data is neat and clear. You get stats on competition level, the average searches per month, CPC, etc. Additionally, the tool is able to give variations of the keyword you supplied as well as synonyms. Despite this simplicity in functionality, Google’s keyword planner is still a choice keyword tool for businesses.

Related: 11 reasons to use keyword rank tracking tools.

Serpstat

This is a different ballplayer when it comes to keyword research for your blog. It serves as an all-inclusive SEO tool with the keyword research tool part of its key functions. So, apart from researching keywords, this tool also helps with your blog optimization. The uniqueness of the tool lies in its in-depth evaluation of pages. The platform is page-centered in its analysis and you are able to access data on the position of several pages over time. You can check if the ranking of the pages is dropping. This is useful for observing how a page is performing for a certain keyword in between two periods. As well as monitor how algorithm updates affect such keyword.  

Serpstat Overview

Additionally, you can access search suggestions and questions that are popular with people. This information is sourced from real searches. This gives an entirely new viewpoint on content ideas that drive traffic. This is also a paid keyword research tool.

Ubersuggest Overview

It is one thing knowing the keyword you are trying to target. If you are devoid of ideas for keywords to use for your content. Then this is where this keyword research tool comes in handy. It allows you to research keywords that fit in with your blog, content strategy, and marketing aims. It does this through suggestions of keywords and content ideas for a specific phrase you enter into the search box.

Ubersuggest Keyword Ideas

Therefore, you are lacking in creativity for keyword ideas; this keyword research tool can point you towards new ideas. However, you must be prepared to shift through thousands of results to get the most appropriate keyword to suit your blog.

Ubersuggest Content Ideas

Moz has four pricing plans you can choose from depending on which suit your needs and requirements.

Conclusion

Ultimately, we have some factors that determine which keyword research tool you will use. It could be your budget, content strategy, blogging niche, etc. We must say your budget goes a long way in influencing your choice of keyword research tool. Depending on your budget, you could opt for the free keyword research tool or the paid version. For those on a low budget, you could opt for tools like Serpstat, AdWord & SEO Keyword Permutation Generator, and Google Keyword Planner. However, if you want a more comprehensive tool with a high budget, you could opt for tools like Ahrefs, SEMrush, and Moz.

Creating And Deploying Using Serverless Framework

Creating and Deploying using Serverless Framework

AWS Lambda can be created and deployed using serverless framework. It allows you to create AWS Lambda triggers and also deploy the same by creating the required roles. Serverless framework allows to handle big projects in an easier way. The events and resources required are written in one place and just a few commands helps in deploying the full functionality on AWS console.

In this chapter, you will learn in detail how to get started with AWS serverless framework.

Install Serverless Framework using npm install

To begin with, you need to first install nodejs. You can check for nodejs as follows −

You will have to use the following command to install serverless using npm package −

npm install -g serverless

Once npm is done, execute serverless command which shows the list of command to be used to create and deploy AWS Lambda function. Observe the screenshots given below −

You can also use sls instead of serverless. sls is the shorthand command for serverless.

In case you need help on the command sls, you can use the following command −

sls create --help

For creating a serverless framework, you have to follow the steps given below −

Step 1

To start using serverless framework, we need to add the credentials. By this, you can the user first in AWS console as follows −

Step 2

Step 3 Configure AWS Serverless Framework

Let us see how to configure AWS serverless framework. You can use the following command for this purpose −

sls config credentials --provider aws --key accesskey --secret secretkey

Note that the details of credentials entered, that is the access key and secret key are stored in the file /aws/credentials.

First, create a folder where you want your project files to be stored.

Next, we will start the work in aws-serverless folder.

Create AWS Lambda using Serverless Framework

Now, let us create a Lambda function with the serverless framework using the Steps given below −

Step 1

Following are the details for serverless create command −

Step 2

Now, we need to assign the template which are as follows −

AWS-nodejs, aws-nodejs-typescript, aws-nodejs-ecma-script, aws-python, aws-python3, aws-groovy-gradle etc.

Step 3

We shall make use of aws-nodejs template to create our first project using serverless framework. The command for the same purpose is as shown here −

sls create --template aws-nodejs

Note that this command creates a boilerplate for template aws-nodejs.

Step 4

Now, open the folder created in an IDE. Here we are using Visual Studio code and the folder structure is as follows −

Step 5

There are 2 files created: chúng tôi and chúng tôi

The AWS Lambda basic function details are shown in chúng tôi as follows −

'use strict'; const response = { statusCode: 200, body: JSON.stringify({ message: 'Go Serverless v1.0! Your function executed successfully!', input: event, }), }; callback(null, response); };

This file chúng tôi has the configuration details of the serverless framework as shown below −

# Welcome to Serverless! # # This file is the main config file for your service. # It's very minimal at this point and uses default values. # You can always add more config options for more control. # # For full config options, check the docs: # # Happy Coding! service: aws-nodejs # NOTE: update this with your service name # You can pin your service to only deploy with a specific Serverless version # Check out our docs for more details # frameworkVersion: "=XX.X" provider: name: aws runtime: nodejs6.10 # you can overwrite defaults here # stage: dev # region: us-east-1 # you can add statements to the Lambda function's IAM Role here # iamRoleStatements: # - Effect: "Allow" # Action: # - "s3:ListBucket" # Resource: { "Fn::Join" : ["", ["arn:aws:s3:::", { "Ref" : "ServerlessDeploymentBucket" } ] ] } # - Effect: "Allow" # Action: # - "s3:PutObject" # Resource: # Fn::Join: # - "" # - - "arn:aws:s3:::" # - "Ref" : "ServerlessDeploymentBucket" # - "/*" # you can define service wide environment variables here # environment: # variable1: value1 # you can add packaging information here #package: # include: # - include-me.js # - include-me-dir/** # exclude: # - exclude-me.js # - exclude-me-dir/** functions: hello: handler: handler.hello # The following are a few example events you can configure # NOTE: Please make sure to change your handler code to work with those events # Check the event documentation for details # events: # path: users/create # method: get # - s3: ${env:BUCKET} # - schedule: rate(10 minutes) # - sns: greeter-topic # - stream: arn:aws:dynamodb:region:XXXXXX:table/foo/stream/1970-01-01T00:00:00.000 # - alexaSkill: amzn1.ask.skill.xx-xx-xx-xx # - alexaSmartHome: amzn1.ask.skill.xx-xx-xx-xx # - iot: # sql: "SELECT * FROM 'some_topic'" # - cloudwatchEvent: # event: # Example: # - "aws.ec2" # detail-type: # - "EC2 Instance State-change Notification" # detail: # state: # - pending # - cloudwatchLog: '/aws/lambda/hello' # - cognitoUserPool: # pool: MyUserPool # trigger: PreSignUp # Define function environment variables here # environment: # variable2: value2 # you can add CloudFormation resource templates here #resources: # resources: # NewResource: # Type: AWS::S3::Bucket # Properties: # BucketName: my-new-bucket # Outputs: # NewOutput: # Description: "Description for the output" # Value: "Some output value"

Now, we need to add changes in chúng tôi file as per our requirements. You can use the commands as given below −

You can use the following command for Service −

service: aws-nodejs # NOTE: update this with your service name

Now, change the service here and add the name given to our folder as shown −

service: aws-serverless # NOTE: update this with your service name

The provider details are as shown −

provider: name: aws runtime: nodejs6.10

The provider is aws and runtime is nodejs6.10. We need to add the region in which we will be working and the stage, that is dev or prod environment for the project. So here are the updated details of provider:provider −

name: aws runtime: nodejs6.10 # you can overwrite defaults here stage: prod region: us-east-1 IAM Role

The iam role, that is, the code for permission to work with Lambda is shown here in the .yml file −

# iamRoleStatements: # - Effect: "Allow" # Action: # - "s3:ListBucket" # Resource: { "Fn::Join" : ["", ["arn:aws:s3:::", { "Ref" : "ServerlessDeploymentBucket" } ] ] } # - Effect: "Allow" # Action: # - "s3:PutObject" # Resource: # Fn::Join: # - "" # - - "arn:aws:s3:::" # - "Ref" : "ServerlessDeploymentBucket" # - "/*"

Note that we need to give the details of the role, that is the permission required with other AWS services, in the above section.

AWS Lambda Handler Details

The name of the export function in chúng tôi is hello. So the handler is name of the file followed by export name.

functions: hello: handler: handler.hello

The resource details about the s3 service added as shown below here −

# you can add CloudFormation resource templates here #resources: # resources: # NewResource: # Type: AWS::S3::Bucket # Properties: # BucketName: my-new-bucket # Outputs: # NewOutput: # Description: "Description for the output" # Value: "Some output value" Deploy AWS Lambda using Serverless Framework

Let us deploy the above lambda function to AWS console. You can use the following Steps for this purpose −

Step 1

First, you will have to use the following command −

sls deploy

Step 2

Now, you should see the function in AWS console now as shown. The details of serverless AWS are logged in AWS cloud formation. For this purpose, go to AWS service and select CloudFormation. The details of the AWS Lambda are displayed as follows −

Observe that the name given is project name followed by the stage used.

Step 3

It creates the iam role for AWS Lambda and log group for AWS cloudwatch. S3 bucket is created which has the code details stored and the configuration details.

This is created by the command sls deploy. You need not specify the iam role, instead it is created by default during the deploy stage.

Step 4

The detailed flow of events is displayed below in the cloud formation service.

AWS Lambda Code

The AWS Lambda code and its execution settings are shown in the screenshot given below −

When you test the Lambda function, you can find the following output −

The Log output for the above function is shown here −

We can also test the AWS Lambda function using the serverless command as shown below −

sls invoke --function hello

The syntax of the invoke command is shown here −

sls invoke --function hello

This invoke command triggers the AWS Lambda function and displays the output in the command prompt as shown below −

You can also test the Lambda function before deploying and the command for same using the following command −

sls invoke local --function hello

Please note that it is not always possible to test locally as the resources like S3 andDynanoDB cannot be simulated on the local environment. Only the basic function calls can be tested locally.

Using API Gateway and AWS Lambda with Serverless Framework

Let us see how to create new project to work with Lambda and api gateway. You can use the following command for this purpose −

sls create --template aws-nodejs

Now, open aws-api project in visual code. You can see that the chúng tôi and chúng tôi files created. Let us do the changes in that for addition of api gateway.

You will have to do the following changes in chúng tôi −

Now, the events details added for api gateway activation with AWS Lambda −

The path is the end-point which we will use when the api gateway path is created and method used is GET.

Observe that the handler is handler.hello, and hello is the export name from handler.js.

Note that you donot have to deploy the api gateway here, as the serverless framework will perform it.

Now, we will run the sls deploy command to create AWS Lambda function with trigger as api gateway.

sls deploy

Observe that the deploy details are listed above. It gives the Get url with the end-point as the path details. The stage is prod so same is used in the url. The name of the function is aws-api-prod-hello.

Let us hit the url and see the output. You can see the followings the response we get from the api-gateway get url −

{"message":"Go Serverless v1.0! Your function executed "GET","headers":{"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9, image/webp,image/apng,*/*;q=0.8","Accept-Encoding":"gzip, deflate, br","Accept-Language":"en-US,en;q=0.9","CloudFront-Forwarded-Proto": "false","CloudFront-Is-SmartTV-Viewer":"false","CloudFront-Is-Tablet-Viewer": "false","CloudFront-Viewer-Country":"IN","Host":"nvbhfdojfg.execute-api.us-east-1. (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36","Via":"2.0 chúng tôi (CloudFront)","X-Amz-Cf-Id":"j70MMqkWFp6kmvuauzp_nvTbI-WwKIQmm2Jl5hzSoN6gkdvX11hh-g==", "queryStringParameters":null,"pathParameters":null,"stageVariables":null, "GET","extendedRequestId":"H6P9fE-MoAMFdIg=","requestTime":"03/Jun/2023:14:23: 43 +0000","path":"/prod/first-api","accountId":"625297745038","protocol":"HTTP/1.1", "stage":"prod","requestTimeEpoch":1528035823928,"requestId":"b865dbd6-6739-11e8-b135 -a30269a8ec58","identity":{"cognitoIdentityPoolId":null,"accountId":null, "cognitoIdentityId":null,"caller":null,"SourceIp":"157.33.133.217","accessKey":null, "cognitoAuthenticationType":null,"cognitoAuthenticationProvider":null,"userArn":null, "userAgent":"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36","user":null},"apiId":"nvbhfdojfg"},"body":null, "isBase64Encoded":false}}

The output we get from api gateway are only the body details such as message and input. The response is totally controlled by the api gateway and how to display it as output.

Now, let us pass inputs to the GET url in query string and see the display −

Then you can see the output of querystring as shown below −

{"message":"Go Serverless v1.0! Your function executed "GET","headers":{"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9, image/webp,image/apng,*/*;q=0.8","Accept-Encoding":"gzip, deflate, "CloudFront-Is-Desktop-Viewer":"true","CloudFront-Is-Mobile-Viewer":"false", "CloudFront-Is-SmartTV-Viewer":"false","CloudFront-Is-Tablet-Viewer":"false", "upgrade-insecure-requests":"1","User-Agent":"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36","Via":"2.0 chúng tôi (CloudFront)","X-Amz-Cf-Id":"JIBZw3I-blKbnpHP8LYXPVolCgdW5KmEukZS4at9mi4vrWBMI-UKNw==", "X-Amzn-Trace-Id":"Root=1-5b13ff90-7d6e38d4c0e4a5d4e6184f30","X-Forwarded-For": Parameters":{"displaymessage":"Hello"},"pathParameters":null,"stageVariables":null, "GET","extendedRequestId":"H6TeiG34oAMFguA=","requestTime":"03/Jun/2023:14:47:44 +0000","path":"/prod/first-api","accountId":"625297745038","protocol":"HTTP/1.1", "stage":"prod","requestTimeEpoch":1528037264252,"requestId":"12e5dca3- 673d-11e8-8966-69fcf43bd4db","identity":{"cognitoIdentityPoolId":null,"accountId":null, "cognitoIdentityId":null,"caller":null,"exmpleIp":"157.33.133.217","accessKey":null, "cognitoAuthenticationType":null,"cognitoAuthenticationProvider":null,"userArn":null, "userAgent":"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36","user":null},"apiId":"nvbhfdojfg"},"body": null,"isBase64Encoded":false}}

Let us change the AWS Lambda function to just display the querystring details as shown below −

'use strict'; const response = { statusCode: 200, body: JSON.stringify({ message:(event.queryStringParameters && event.queryStringParameters.displaymessage!="") ? event.queryStringParameters.displaymessage : 'Go Serverless v1.0! Your function executed successfully!' }), }; callback(null, response); };

Observe that we have changed the message based on the querystring display message. This will deploy the the function again and check the output. It displays the details present in query string variable display message as shown below.

Let us now add post method to the events created as shown below −

Now, deploy the changes made and you can see the following output from the deploy command −

Note that testing post url in browser directly will not give the details. You should test the post url in postman.

This displays the message we have added in the Lambda function.

Advertisements

Improving Government Services With The Retail To Regulator Framework

Federal agencies increasingly understand the need to treat their constituents as customers and allow those customers to interact with government services in the dynamic, responsive manner that they have come to expect from the private sector.

According to Deloitte, “the rise of the internet at the close of the 20th century fundamentally changed the way that the U.S. government interacts with citizens, businesses and other government entities,” sharpening their focus on improving customer service. Fortunately, the customer experience (CX) path that government agencies are now exploring is ground well-trodden by the private sector, and agencies can learn from their for-profit counterparts. Deloitte Digital’s Retailer to Regulator spectrum provides a framework for agencies seeking to understand how to go about improving customer service.

Exploring the Retail to Regulator Spectrum

The Retail to Regulator spectrum classifies government agencies and services into three categories: retail, mission and regulator. Organizations with a retail focus operate like private sector businesses, offering services to customers and even sometimes competing in the open marketplace. The U.S. Postal Service offers one of the most striking examples of a government retail agency, directly competing with FedEx, UPS and other shipping partners for business.

As agencies seek to improve the customer experience, they must understand where they fit on this spectrum, and how adopting practices from other areas on the spectrum might provide a better customer experience. Deloitte points out the Transportation Security Administration (TSA) as a model of this behavior. The TSA clearly fits on the regulatory end of the spectrum. It provides security services at airports that are often not well-received by passengers and aircrew. Despite its positioning as a regulator, the TSA adopted practices from the retailer domain and rolled out TSA PreCheck as a customer-friendly way to both improve screening efficiency and increase the satisfaction of their highest-use customers by pre-clearing and reducing the airport security screening of frequent fliers.

Best Practices for Improving Customer Service

Public agencies are increasingly adopting customer experience improvement tools from the private sector. Deloitte offers some practical suggestions for agencies seeking to improve their CX by adopting successful private sector tactics:

Appoint a chief customer officer (CCO) who can oversee CX efforts.

Use a customer relationship management (CRM) system to centralize, automate and improve constituent interactions.

Follow the audience. Provide users with a multichannel experience that allows them to interact with agencies on their own terms.

Rapidly resolve constituent issues using the channel of their choice.

Use contextual information about a constituent to tailor the information and services you offer them.

Communicate in clear, plain language that avoids acronyms and other government jargon.

Sponsor prize-based challenges designed to create new solutions to old problems.

Offer customers real-time tracking of their requests through various government services.

Rely on deep analytics to guide customer relationships.

While all of these practices won’t quite match the models of every government agency, leaders may find applicable solutions in the successful CX practices of the private sector and find new ways to adapt them for use in the government.

Digital transformation efforts can dramatically improve the user-friendliness and efficiency of government transactions.

Update the detailed information about Selenium Framework: Data, Keyword & Hybrid Driven on the Hatcungthantuong.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!