github.com/masterhung0112/hk_server/v5@v5.0.0-20220302090640-ec71aef15e1c/manualtesting/manual_testing.go (about)

     1  // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
     2  // See LICENSE.txt for license information.
     3  
     4  package manualtesting
     5  
     6  import (
     7  	"errors"
     8  	"hash/fnv"
     9  	"math/rand"
    10  	"net/http"
    11  	"net/url"
    12  	"strconv"
    13  	"time"
    14  
    15  	"github.com/masterhung0112/hk_server/v5/api4"
    16  	"github.com/masterhung0112/hk_server/v5/app"
    17  	"github.com/masterhung0112/hk_server/v5/app/slashcommands"
    18  	"github.com/masterhung0112/hk_server/v5/model"
    19  	"github.com/masterhung0112/hk_server/v5/shared/mlog"
    20  	"github.com/masterhung0112/hk_server/v5/store"
    21  	"github.com/masterhung0112/hk_server/v5/utils"
    22  	"github.com/masterhung0112/hk_server/v5/web"
    23  )
    24  
    25  // TestEnvironment is a helper struct used for tests in manualtesting.
    26  type TestEnvironment struct {
    27  	Params        map[string][]string
    28  	Client        *model.Client4
    29  	CreatedTeamID string
    30  	CreatedUserID string
    31  	Context       *web.Context
    32  	Writer        http.ResponseWriter
    33  	Request       *http.Request
    34  }
    35  
    36  // Init adds manualtest endpoint to the API.
    37  func Init(api4 *api4.API) {
    38  	api4.BaseRoutes.Root.Handle("/manualtest", api4.ApiHandler(manualTest)).Methods("GET")
    39  }
    40  
    41  func manualTest(c *web.Context, w http.ResponseWriter, r *http.Request) {
    42  	// Let the world know
    43  	mlog.Info("Setting up for manual test...")
    44  
    45  	// URL Parameters
    46  	params, err := url.ParseQuery(r.URL.RawQuery)
    47  	if err != nil {
    48  		c.Err = model.NewAppError("/manual", "manaultesting.manual_test.parse.app_error", nil, "", http.StatusBadRequest)
    49  		return
    50  	}
    51  
    52  	// Grab a uuid (if available) to seed the random number generator so we don't get conflicts.
    53  	uid, ok := params["uid"]
    54  	if ok {
    55  		hasher := fnv.New32a()
    56  		hasher.Write([]byte(uid[0] + strconv.Itoa(int(time.Now().UTC().UnixNano()))))
    57  		hash := hasher.Sum32()
    58  		rand.Seed(int64(hash))
    59  	} else {
    60  		mlog.Debug("No uid in URL")
    61  	}
    62  
    63  	// Create a client for tests to use
    64  	client := model.NewAPIv4Client("http://localhost" + *c.App.Config().ServiceSettings.ListenAddress)
    65  
    66  	// Check for username parameter and create a user if present
    67  	username, ok1 := params["username"]
    68  	teamDisplayName, ok2 := params["teamname"]
    69  	var teamID string
    70  	var userID string
    71  	if ok1 && ok2 {
    72  		mlog.Info("Creating user and team")
    73  		// Create team for testing
    74  		team := &model.Team{
    75  			DisplayName: teamDisplayName[0],
    76  			Name:        "zz" + utils.RandomName(utils.Range{Begin: 20, End: 20}, utils.LOWERCASE),
    77  			Email:       "success+" + model.NewId() + "simulator.amazonses.com",
    78  			Type:        model.TEAM_OPEN,
    79  		}
    80  
    81  		createdTeam, err := c.App.Srv().Store.Team().Save(team)
    82  		if err != nil {
    83  			var invErr *store.ErrInvalidInput
    84  			var appErr *model.AppError
    85  			switch {
    86  			case errors.As(err, &invErr):
    87  				c.Err = model.NewAppError("manualTest", "app.team.save.existing.app_error", nil, invErr.Error(), http.StatusBadRequest)
    88  			case errors.As(err, &appErr):
    89  				c.Err = appErr
    90  			default:
    91  				c.Err = model.NewAppError("manualTest", "app.team.save.app_error", nil, err.Error(), http.StatusInternalServerError)
    92  			}
    93  			return
    94  		}
    95  
    96  		channel := &model.Channel{DisplayName: "Town Square", Name: "town-square", Type: model.CHANNEL_OPEN, TeamId: createdTeam.Id}
    97  		if _, err := c.App.CreateChannel(c.AppContext, channel, false); err != nil {
    98  			c.Err = err
    99  			return
   100  		}
   101  
   102  		teamID = createdTeam.Id
   103  
   104  		// Create user for testing
   105  		user := &model.User{
   106  			Email:    "success+" + model.NewId() + "simulator.amazonses.com",
   107  			Nickname: username[0],
   108  			Password: slashcommands.UserPassword}
   109  
   110  		user, resp := client.CreateUser(user)
   111  		if resp.Error != nil {
   112  			c.Err = resp.Error
   113  			return
   114  		}
   115  
   116  		c.App.Srv().Store.User().VerifyEmail(user.Id, user.Email)
   117  		c.App.Srv().Store.Team().SaveMember(&model.TeamMember{TeamId: teamID, UserId: user.Id}, *c.App.Config().TeamSettings.MaxUsersPerTeam)
   118  
   119  		userID = user.Id
   120  
   121  		// Login as user to generate auth token
   122  		_, resp = client.LoginById(user.Id, slashcommands.UserPassword)
   123  		if resp.Error != nil {
   124  			c.Err = resp.Error
   125  			return
   126  		}
   127  
   128  		// Respond with an auth token this can be overridden by a specific test as required
   129  		sessionCookie := &http.Cookie{
   130  			Name:     model.SESSION_COOKIE_TOKEN,
   131  			Value:    client.AuthToken,
   132  			Path:     "/",
   133  			MaxAge:   *c.App.Config().ServiceSettings.SessionLengthWebInDays * 60 * 60 * 24,
   134  			HttpOnly: true,
   135  		}
   136  		http.SetCookie(w, sessionCookie)
   137  		http.Redirect(w, r, "/channels/town-square", http.StatusTemporaryRedirect)
   138  	}
   139  
   140  	// Setup test environment
   141  	env := TestEnvironment{
   142  		Params:        params,
   143  		Client:        client,
   144  		CreatedTeamID: teamID,
   145  		CreatedUserID: userID,
   146  		Context:       c,
   147  		Writer:        w,
   148  		Request:       r,
   149  	}
   150  
   151  	// Grab the test ID and pick the test
   152  	testname, ok := params["test"]
   153  	if !ok {
   154  		c.Err = model.NewAppError("/manual", "manaultesting.manual_test.parse.app_error", nil, "", http.StatusBadRequest)
   155  		return
   156  	}
   157  
   158  	switch testname[0] {
   159  	case "autolink":
   160  		c.Err = testAutoLink(env)
   161  		// ADD YOUR NEW TEST HERE!
   162  	case "general":
   163  	}
   164  }
   165  
   166  func getChannelID(a app.AppIface, channelname string, teamid string, userid string) (string, bool) {
   167  	// Grab all the channels
   168  	channels, err := a.Srv().Store.Channel().GetChannels(teamid, userid, false, 0)
   169  	if err != nil {
   170  		mlog.Debug("Unable to get channels")
   171  		return "", false
   172  	}
   173  
   174  	for _, channel := range *channels {
   175  		if channel.Name == channelname {
   176  			return channel.Id, true
   177  		}
   178  	}
   179  	mlog.Debug("Could not find channel", mlog.String("Channel name", channelname), mlog.Int("Possibilities searched", len(*channels)))
   180  	return "", false
   181  }