Best Testkube code snippet using client.DownloadFile
datadragon.go
Source:datadragon.go  
1package riotclientdd2import (3	"encoding/json"4	"fmt"5	"io/ioutil"6	"net/http"7	"strings"8	"git.abyle.org/hps/alolstats/config"9	"git.abyle.org/hps/alolstats/logging"10	"github.com/sirupsen/logrus"11)12// N holds the actual versions13type N struct {14	Item        string `json:"item"`15	Rune        string `json:"rune"`16	Mastery     string `json:"mastery"`17	Summoner    string `json:"summoner"`18	Champion    string `json:"champion"`19	Profileicon string `json:"profileicon"`20	Map         string `json:"map"`21	Language    string `json:"language"`22	Sticker     string `json:"sticker"`23}24type currentVersions struct {25	N              N           `json:"n"`26	V              string      `json:"v"`27	L              string      `json:"l"`28	Cdn            string      `json:"cdn"`29	Dd             string      `json:"dd"`30	Lg             string      `json:"lg"`31	CSS            string      `json:"css"`32	Profileiconmax int         `json:"profileiconmax"`33	Store          interface{} `json:"store"`34}35// RiotClientDD Riot LoL API DataDragon client36type RiotClientDD struct {37	config     config.RiotClient38	httpClient httpClient39	log        *logrus.Entry40}41type httpClient interface {42	Get(url string) (resp *http.Response, err error)43}44func checkConfig(cfg config.RiotClient) error {45	if len(cfg.Region) < 2 {46		return fmt.Errorf("Region does not comply to Riot region conventions, check config file")47	}48	return nil49}50// New creates a new Riot LoL API Data Dragon client51func New(httpClient httpClient, cfg config.RiotClient) (*RiotClientDD, error) {52	err := checkConfig(cfg)53	if err != nil {54		return nil, err55	}56	cfg.Region = strings.ToLower(cfg.Region)57	c := &RiotClientDD{58		config:     cfg,59		httpClient: httpClient,60		log:        logging.Get("RiotClientDD"),61	}62	return c, nil63}64func (c *RiotClientDD) downloadFile(url string) ([]byte, error) {65	response, err := c.httpClient.Get(url)66	if err != nil {67		return nil, err68	}69	defer response.Body.Close()70	if response.StatusCode != http.StatusOK {71		return nil, fmt.Errorf("downloadFile failed, got status code %d", response.StatusCode)72	}73	return ioutil.ReadAll(response.Body)74}75func (c *RiotClientDD) getRegion() string {76	region := strings.ToLower(c.config.Region)77	return string(region[:len(region)-1])78}79func (c *RiotClientDD) getVersions() (*currentVersions, error) {80	versionURL := "https://ddragon.leagueoflegends.com/realms/" + c.getRegion() + ".json"81	versionData, err := c.downloadFile(versionURL)82	if err != nil {83		return nil, fmt.Errorf("Error downloading versions data from Data Dragon: %s", err)84	}85	versions := currentVersions{}86	err = json.Unmarshal(versionData, &versions)87	if err != nil {88		return nil, err89	}90	return &versions, nil91}92// GetLoLVersions returns all currenctly known LoL Versions93func (c *RiotClientDD) GetLoLVersions() ([]byte, error) {94	versionsURL := "https://ddragon.leagueoflegends.com/api/versions.json"95	body, err := c.downloadFile(versionsURL)96	if err != nil {97		return nil, fmt.Errorf("Error downloading Verions data from Data Dragon: %s", err)98	}99	return body, nil100}101// GetDataDragonChampions returns the current champions available for the live game version102func (c *RiotClientDD) GetDataDragonChampions() ([]byte, error) {103	versions, err := c.getVersions()104	if err != nil {105		return nil, err106	}107	championsURL := versions.Cdn + "/" + versions.N.Champion + "/data/" + versions.L + "/champion.json"108	body, err := c.downloadFile(championsURL)109	if err != nil {110		return nil, fmt.Errorf("Error downloading Champions data from Data Dragon: %s", err)111	}112	return body, nil113}114// GetDataDragonChampionsSpecificVersionLanguage returns the champions for a given game version and language115func (c *RiotClientDD) GetDataDragonChampionsSpecificVersionLanguage(gameVersion, language string) ([]byte, error) {116	versions, err := c.getVersions()117	if err != nil {118		return nil, err119	}120	championsURL := versions.Cdn + "/" + gameVersion + "/data/" + language + "/champion.json"121	body, err := c.downloadFile(championsURL)122	if err != nil {123		return nil, fmt.Errorf("Error downloading Champions data for game version %s and language %s from Data Dragon: %s", gameVersion, language, err)124	}125	return body, nil126}127// GetDataDragonSummonerSpells returns the current summoner spells available for the live game version128func (c *RiotClientDD) GetDataDragonSummonerSpells() ([]byte, error) {129	versions, err := c.getVersions()130	if err != nil {131		return nil, err132	}133	championsURL := versions.Cdn + "/" + versions.N.Summoner + "/data/" + versions.L + "/summoner.json"134	body, err := c.downloadFile(championsURL)135	if err != nil {136		return nil, fmt.Errorf("Error downloading Summoner Spells data from Data Dragon: %s", err)137	}138	return body, nil139}140// GetDataDragonSummonerSpellsSpecificVersionLanguage returns the Summoner Spells for a given game version and language141func (c *RiotClientDD) GetDataDragonSummonerSpellsSpecificVersionLanguage(gameVersion, language string) ([]byte, error) {142	versions, err := c.getVersions()143	if err != nil {144		return nil, fmt.Errorf("Unable to get versions from data dragon: %s", err)145	}146	championsURL := versions.Cdn + "/" + gameVersion + "/data/" + language + "/summoner.json"147	body, err := c.downloadFile(championsURL)148	if err != nil {149		return nil, fmt.Errorf("Error downloading Summoner Spells data for game version %s and language %s from Data Dragon: %s", gameVersion, language, err)150	}151	return body, nil152}153// GetDataDragonItems returns the current items available for the live game version154func (c *RiotClientDD) GetDataDragonItems() ([]byte, error) {155	versions, err := c.getVersions()156	if err != nil {157		return nil, err158	}159	championsURL := versions.Cdn + "/" + versions.N.Item + "/data/" + versions.L + "/item.json"160	body, err := c.downloadFile(championsURL)161	if err != nil {162		return nil, fmt.Errorf("Error downloading Items data from Data Dragon: %s", err)163	}164	return body, nil165}166// GetDataDragonItemsSpecificVersionLanguage returns the Items  for a given game version and language167func (c *RiotClientDD) GetDataDragonItemsSpecificVersionLanguage(gameVersion, language string) ([]byte, error) {168	versions, err := c.getVersions()169	if err != nil {170		return nil, err171	}172	championsURL := versions.Cdn + "/" + gameVersion + "/data/" + language + "/item.json"173	body, err := c.downloadFile(championsURL)174	if err != nil {175		return nil, fmt.Errorf("Error downloading Items data for game version %s and language %s from Data Dragon: %s", gameVersion, language, err)176	}177	return body, nil178}179// GetDataDragonRunesReforged returns the current Runes Reforged available for the live game version180func (c *RiotClientDD) GetDataDragonRunesReforged() ([]byte, error) {181	versions, err := c.getVersions()182	if err != nil {183		return nil, err184	}185	// We use the Item version as there seems to be no special version for Runes Reforged186	championsURL := versions.Cdn + "/" + versions.N.Item + "/data/" + versions.L + "/runesReforged.json"187	body, err := c.downloadFile(championsURL)188	if err != nil {189		return nil, fmt.Errorf("Error downloading Runes Reforged data from Data Dragon: %s", err)190	}191	return body, nil192}193// GetDataDragonRunesReforgedSpecificVersionLanguage returns the Runes Reforged for a given game version and language194func (c *RiotClientDD) GetDataDragonRunesReforgedSpecificVersionLanguage(gameVersion, language string) ([]byte, error) {195	versions, err := c.getVersions()196	if err != nil {197		return nil, err198	}199	championsURL := versions.Cdn + "/" + gameVersion + "/data/" + language + "/runesReforged.json"200	body, err := c.downloadFile(championsURL)201	if err != nil {202		return nil, fmt.Errorf("Error downloading Runes Reforged data for game version %s and language %s from Data Dragon: %s", gameVersion, language, err)203	}204	return body, nil205}...gitiles_test.go
Source:gitiles_test.go  
...114				So(err, ShouldBeNil)115				So(revision, ShouldEqual, "fake-revision")116			})117		})118		Convey("DownloadFile", func() {119			Convey("fails if getting gitiles client fails", func() {120				ctx := UseGitilesClientFactory(ctx, func(ctx context.Context, host string) (GitilesClient, error) {121					return nil, errors.New("test gitiles client factory failure")122				})123				client := NewClient(ctx)124				contents, err := client.DownloadFile(ctx, "fake-host", "fake/project", "fake-revision", "fake-file")125				So(err, ShouldNotBeNil)126				So(contents, ShouldBeEmpty)127			})128			Convey("fails if API call fails", func() {129				ctl := gomock.NewController(t)130				defer ctl.Finish()131				mockGitilesClient := mock_gitiles.NewMockGitilesClient(ctl)132				ctx := UseGitilesClientFactory(ctx, func(ctx context.Context, host string) (GitilesClient, error) {133					return mockGitilesClient, nil134				})135				mockGitilesClient.EXPECT().136					DownloadFile(gomock.Any(), gomock.Any()).137					Return(nil, errors.New("fake DownloadFile failure"))138				client := NewClient(ctx)139				contents, err := client.DownloadFile(ctx, "fake-host", "fake/project", "fake-revision", "fake-file")140				So(err, ShouldNotBeNil)141				So(contents, ShouldBeEmpty)142			})143			Convey("returns file contents", func() {144				ctl := gomock.NewController(t)145				defer ctl.Finish()146				mockGitilesClient := mock_gitiles.NewMockGitilesClient(ctl)147				ctx := UseGitilesClientFactory(ctx, func(ctx context.Context, host string) (GitilesClient, error) {148					return mockGitilesClient, nil149				})150				matcher := proto.MatcherEqual(&gitilespb.DownloadFileRequest{151					Project:    "fake/project",152					Committish: "fake-revision",153					Path:       "fake-file",154				})155				// Check that potentially transient errors are retried156				mockGitilesClient.EXPECT().157					DownloadFile(gomock.Any(), matcher).158					Return(nil, status.Error(codes.NotFound, "fake transient DownloadFile failure"))159				mockGitilesClient.EXPECT().160					DownloadFile(gomock.Any(), matcher).161					Return(nil, status.Error(codes.NotFound, "fake transient DownloadFile failure"))162				mockGitilesClient.EXPECT().163					DownloadFile(gomock.Any(), matcher).164					Return(&gitilespb.DownloadFileResponse{165						Contents: "fake-contents",166					}, nil)167				client := NewClient(ctx)168				contents, err := client.DownloadFile(ctx, "fake-host", "fake/project", "fake-revision", "fake-file")169				So(err, ShouldBeNil)170				So(contents, ShouldEqual, "fake-contents")171			})172		})173	})174}...task_download.go
Source:task_download.go  
...7	"path"8	"github.com/Arman92/go-tdlib/v2/tdlib"9	"github.com/ffenix113/teleporter/tasks"10)11type DownloadFile struct {12	*Common13	RelativePath string14}15// NewDownloadFile will return a download file task.16//17// filePath can be absolute or relative.18func NewDownloadFile(cl *Client, filePath string, details ...string) *DownloadFile {19	return &DownloadFile{20		Common: &Common{21			Client:   cl,22			taskType: "DownloadFile",23			details:  detailsOrEmpty(details...),24		},25		RelativePath: cl.RelativePath(filePath),26	}27}28func (f *DownloadFile) Name() string {29	return f.RelativePath30}31func (f *DownloadFile) Run(ctx context.Context) {32	f.status = tasks.TaskStatusInProgress33	msgID, ok := f.Client.PinnedHeader.Files[f.RelativePath]34	if !ok {35		f.SetError(fmt.Errorf("file %q is not present in remote chat", f.RelativePath))36		return37	}38	if err := f.Client.EnsureMessagesAreKnown(ctx, msgID); err != nil {39		f.SetError(err)40		return41	}42	msg, err := f.Client.TDClient.GetMessage(f.Client.chatID, msgID)43	if err != nil {44		f.SetError(err)45		return46	}47	msgDoc, ok := msg.Content.(*tdlib.MessageDocument)48	if !ok {49		f.SetError(fmt.Errorf("message is not document: %v", msg.Content))50		return51	}52	fileID := msgDoc.Document.Document.ID53	var filePath string54	if file, err := f.Client.TDClient.GetFile(fileID); err == nil {55		if !file.Local.IsDownloadingCompleted {56			if _, err := f.Client.TDClient.CancelDownloadFile(fileID, false); err != nil {57				f.SetError(err)58				return59			}60			watcher := f.watchDownload(fileID) // This may dangle if download will screw up.61			// Download(msgDoc.Document.Document.ID, DownloadFilePartSize)62			_, err = f.Client.TDClient.DownloadFile(fileID, 1, 0, 0, false)63			if err != nil {64				f.SetError(err)65				return66			}67			file = <-watcher68		}69		filePath = file.Local.Path70	}71	if err := os.MkdirAll(path.Dir(f.Client.AbsPath(f.RelativePath)), os.ModeDir|0755); err != nil {72		f.SetError(err)73		return74	}75	if err := os.Rename(filePath, f.Client.AbsPath(f.RelativePath)); err != nil {76		f.SetError(fmt.Errorf("move file: %w", err))77	}78	f.SetDone()79}80func (f *DownloadFile) Download(fileID int32, partSize int32) (*tdlib.File, error) {81	var offset int3282	var file *tdlib.File83	var err error84	for {85		file, err = f.Client.TDClient.DownloadFile(fileID, 1, offset, partSize, true)86		if err != nil {87			return nil, err88		}89		if file.Local.IsDownloadingCompleted {90			return file, nil91		}92		f.progress = int(100 * (file.Local.DownloadedSize / file.ExpectedSize))93		offset += partSize94	}95}96func (f *DownloadFile) watchDownload(fileID int32) chan *tdlib.File {97	watcher := make(chan *tdlib.File, 1)98	var fileUpdate tdlib.UpdateFile99	f.Client.AddUpdateHandler(func(update tdlib.UpdateMsg) bool {100		if update.Data["@type"] != string(tdlib.UpdateFileType) {101			return false102		}103		if err := json.Unmarshal(update.Raw, &fileUpdate); err != nil {104			panic(fmt.Sprintf("failed to unmarshal update: %v", err))105		}106		if fileUpdate.File.ID != fileID {107			return false108		}109		f.progress = int(100 * (float64(fileUpdate.File.Local.DownloadedSize) / float64(fileUpdate.File.ExpectedSize)))110		if fileUpdate.File.Local.IsDownloadingCompleted {...DownloadFile
Using AI Code Generation
1import (2func main() {3	client := client.New(nil)4	if err != nil {5		fmt.Println(err)6	}7}8            var _satellite = window._satellite = window._satellite || {};9            _satellite.pageBottom = new Date();DownloadFile
Using AI Code Generation
1import (2func main() {3	client := client.NewClient()4	fmt.Println("Downloaded image.png")5}6import (7func main() {8	client := client.NewClient()9	fmt.Println("Downloaded image.png")10}11import (12func main() {13	client := client.NewClient()14	fmt.Println("Downloaded image.png")15}16import (17func main() {18	client := client.NewClient()19	fmt.Println("Downloaded image.png")20}21import (22func main() {23	client := client.NewClient()24	fmt.Println("Downloaded image.png")25}26import (27func main()DownloadFile
Using AI Code Generation
1import (2func main() {3    err := client.DownloadFile("google.png", url)4    if err != nil {5        panic(err)6    }7    fmt.Println("Downloaded: ", url)8}DownloadFile
Using AI Code Generation
1import (2func main() {3	client := kafka_client.NewClient("localhost:9092")4	err := client.DownloadFile("test", "test.txt")5	if err != nil {6		fmt.Println("Error while downloading file")7	}8}9import (10func main() {11	client := kafka_client.NewClient("localhost:9092")12	err := client.DownloadFile("test", "test.txt")13	if err != nil {14		fmt.Println("Error while downloading file")15	}16}17import (18func main() {19	client := kafka_client.NewClient("localhost:9092")20	err := client.DownloadFile("test", "test.txt")21	if err != nil {22		fmt.Println("Error while downloading file")23	}24}25import (26func main() {27	client := kafka_client.NewClient("localhost:9092")28	err := client.DownloadFile("test", "test.txt")29	if err != nil {30		fmt.Println("Error while downloading file")31	}32}33import (34func main() {35	client := kafka_client.NewClient("localhost:9092")DownloadFile
Using AI Code Generation
1import (2func main() {3	if err := cl.DownloadFile("test.txt"); err != nil {4		fmt.Println(err)5	}6}7import (8func main() {9	if err := cl.UploadFile("test.txt"); err != nil {10		fmt.Println(err)11	}12}13import (14func main() {15	cl.SetHeader("Accept", "application/json")16	if err := cl.SendRequest(); err != nil {17		fmt.Println(err)18	}19	if err := cl.ReadResponse(); err != nil {20		fmt.Println(err)21	}22}23import (24func main() {25	cl.SetBody([]byte("Hello World"))26	if err := cl.SendRequest(); err != nil {27		fmt.Println(err)28	}29	if err := cl.ReadResponse(); err != nil {30		fmt.Println(err)31	}32}33import (DownloadFile
Using AI Code Generation
1import (2func main() {3	client := client.NewClient()4	fmt.Println("Downloaded")5}6import (7func main() {8	client := client.NewClient()9	fmt.Println("Downloaded")10}11import (12func main() {13	client := client.NewClient()14	fmt.Println("Downloaded")15}16import (17func main() {18	client := client.NewClient()19	fmt.Println("Downloaded")20}21import (22func main() {23	client := client.NewClient()Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
