How to use init method of generated Package

Best Syzkaller code snippet using generated.init

manager.go

Source:manager.go Github

copy

Full Screen

...54}55func Initialize() (*Manager, error) {56 var err error57 once.Do(func() {58 err = initialize()59 })60 return instance, err61}62func initialize() error {63 ctx := context.TODO()64 cfg, err := config.Initialize()65 if err != nil {66 return fmt.Errorf("initializing configuration: %w", err)67 }68 l := initLog()69 initProfiling(cfg.GetCPUProfilePath())70 instance = &Manager{71 Config: cfg,72 Logger: l,73 ReadLockManager: fsutil.NewReadLockManager(),74 DownloadStore: NewDownloadStore(),75 PluginCache: plugin.NewCache(cfg),76 TxnManager: sqlite.NewTransactionManager(),77 scanSubs: &subscriptionManager{},78 }79 instance.JobManager = initJobManager()80 sceneServer := SceneServer{81 TXNManager: instance.TxnManager,82 }83 instance.DLNAService = dlna.NewService(instance.TxnManager, instance.Config, &sceneServer)84 if !cfg.IsNewSystem() {85 logger.Infof("using config file: %s", cfg.GetConfigFile())86 if err == nil {87 err = cfg.Validate()88 }89 if err != nil {90 return fmt.Errorf("error initializing configuration: %w", err)91 } else if err := instance.PostInit(ctx); err != nil {92 return err93 }94 initSecurity(cfg)95 } else {96 cfgFile := cfg.GetConfigFile()97 if cfgFile != "" {98 cfgFile += " "99 }100 // create temporary session store - this will be re-initialised101 // after config is complete102 instance.SessionStore = session.NewStore(cfg)103 logger.Warnf("config file %snot found. Assuming new system...", cfgFile)104 }105 if err = initFFMPEG(ctx); err != nil {106 logger.Warnf("could not initialize FFMPEG subsystem: %v", err)107 }108 // if DLNA is enabled, start it now109 if instance.Config.GetDLNADefaultEnabled() {110 if err := instance.DLNAService.Start(nil); err != nil {111 logger.Warnf("could not start DLNA service: %v", err)112 }113 }114 return nil115}116func initJobManager() *job.Manager {117 ret := job.NewManager()118 // desktop notifications119 ctx := context.Background()120 c := ret.Subscribe(context.Background())121 go func() {122 for {123 select {124 case j := <-c.RemovedJob:125 if instance.Config.GetNotificationsEnabled() {126 cleanDesc := strings.TrimRight(j.Description, ".")127 if j.StartTime == nil {128 // Task was never started129 return130 }131 timeElapsed := j.EndTime.Sub(*j.StartTime)132 desktop.SendNotification("Task Finished", "Task \""+cleanDesc+"\" is finished in "+formatDuration(timeElapsed)+".")133 }134 case <-ctx.Done():135 return136 }137 }138 }()139 return ret140}141func formatDuration(t time.Duration) string {142 return fmt.Sprintf("%02.f:%02.f:%02.f", t.Hours(), t.Minutes(), t.Seconds())143}144func initSecurity(cfg *config.Instance) {145 if err := session.CheckExternalAccessTripwire(cfg); err != nil {146 session.LogExternalAccessError(*err)147 }148}149func initProfiling(cpuProfilePath string) {150 if cpuProfilePath == "" {151 return152 }153 f, err := os.Create(cpuProfilePath)154 if err != nil {155 logger.Fatalf("unable to create cpu profile file: %s", err.Error())156 }157 logger.Infof("profiling to %s", cpuProfilePath)158 // StopCPUProfile is defer called in main159 if err = pprof.StartCPUProfile(f); err != nil {160 logger.Warnf("could not start CPU profiling: %v", err)161 }162}163func initFFMPEG(ctx context.Context) error {164 // only do this if we have a config file set165 if instance.Config.GetConfigFile() != "" {166 // use same directory as config path167 configDirectory := instance.Config.GetConfigPath()168 paths := []string{169 configDirectory,170 paths.GetStashHomeDirectory(),171 }172 ffmpegPath, ffprobePath := ffmpeg.GetPaths(paths)173 if ffmpegPath == "" || ffprobePath == "" {174 logger.Infof("couldn't find FFMPEG, attempting to download it")175 if err := ffmpeg.Download(ctx, configDirectory); err != nil {176 msg := `Unable to locate / automatically download FFMPEG177 Check the readme for download links.178 The FFMPEG and FFProbe binaries should be placed in %s179 The error was: %s180 `181 logger.Errorf(msg, configDirectory, err)182 return err183 } else {184 // After download get new paths for ffmpeg and ffprobe185 ffmpegPath, ffprobePath = ffmpeg.GetPaths(paths)186 }187 }188 instance.FFMPEG = ffmpeg.FFMpeg(ffmpegPath)189 instance.FFProbe = ffmpeg.FFProbe(ffprobePath)190 }191 return nil192}193func initLog() *log.Logger {194 config := config.GetInstance()195 l := log.NewLogger()196 l.Init(config.GetLogFile(), config.GetLogOut(), config.GetLogLevel())197 logger.Logger = l198 return l199}200// PostInit initialises the paths, caches and txnManager after the initial201// configuration has been set. Should only be called if the configuration202// is valid.203func (s *Manager) PostInit(ctx context.Context) error {204 if err := s.Config.SetInitialConfig(); err != nil {205 logger.Warnf("could not set initial configuration: %v", err)206 }207 s.Paths = paths.NewPaths(s.Config.GetGeneratedPath())208 s.RefreshConfig()209 s.SessionStore = session.NewStore(s.Config)210 s.PluginCache.RegisterSessionStore(s.SessionStore)211 if err := s.PluginCache.LoadPlugins(); err != nil {212 logger.Errorf("Error reading plugin configs: %s", err.Error())213 }214 s.ScraperCache = instance.initScraperCache()215 writeStashIcon()216 // clear the downloads and tmp directories217 // #1021 - only clear these directories if the generated folder is non-empty218 if s.Config.GetGeneratedPath() != "" {219 const deleteTimeout = 1 * time.Second220 utils.Timeout(func() {221 if err := fsutil.EmptyDir(instance.Paths.Generated.Downloads); err != nil {222 logger.Warnf("could not empty Downloads directory: %v", err)223 }224 if err := fsutil.EmptyDir(instance.Paths.Generated.Tmp); err != nil {225 logger.Warnf("could not empty Tmp directory: %v", err)226 }227 }, deleteTimeout, func(done chan struct{}) {228 logger.Info("Please wait. Deleting temporary files...") // print229 <-done // and wait for deletion230 logger.Info("Temporary files deleted.")231 })232 }233 if err := database.Initialize(s.Config.GetDatabasePath()); err != nil {234 return err235 }236 if database.Ready() == nil {237 s.PostMigrate(ctx)238 }239 return nil240}241func writeStashIcon() {242 p := FaviconProvider{243 UIBox: ui.UIBox,244 }245 iconPath := filepath.Join(instance.Config.GetConfigPath(), "icon.png")246 err := ioutil.WriteFile(iconPath, p.GetFaviconPng(), 0644)247 if err != nil {248 logger.Errorf("Couldn't write icon file: %s", err.Error())249 }250}251// initScraperCache initializes a new scraper cache and returns it.252func (s *Manager) initScraperCache() *scraper.Cache {253 ret, err := scraper.NewCache(config.GetInstance(), s.TxnManager)254 if err != nil {255 logger.Errorf("Error reading scraper configs: %s", err.Error())256 }257 return ret258}259func (s *Manager) RefreshConfig() {260 s.Paths = paths.NewPaths(s.Config.GetGeneratedPath())261 config := s.Config262 if config.Validate() == nil {263 if err := fsutil.EnsureDir(s.Paths.Generated.Screenshots); err != nil {264 logger.Warnf("could not create directory for Screenshots: %v", err)265 }266 if err := fsutil.EnsureDir(s.Paths.Generated.Vtt); err != nil {267 logger.Warnf("could not create directory for VTT: %v", err)268 }269 if err := fsutil.EnsureDir(s.Paths.Generated.Markers); err != nil {270 logger.Warnf("could not create directory for Markers: %v", err)271 }272 if err := fsutil.EnsureDir(s.Paths.Generated.Transcodes); err != nil {273 logger.Warnf("could not create directory for Transcodes: %v", err)274 }275 if err := fsutil.EnsureDir(s.Paths.Generated.Downloads); err != nil {276 logger.Warnf("could not create directory for Downloads: %v", err)277 }278 if err := fsutil.EnsureDir(s.Paths.Generated.InteractiveHeatmap); err != nil {279 logger.Warnf("could not create directory for Interactive Heatmaps: %v", err)280 }281 }282}283// RefreshScraperCache refreshes the scraper cache. Call this when scraper284// configuration changes.285func (s *Manager) RefreshScraperCache() {286 s.ScraperCache = s.initScraperCache()287}288func setSetupDefaults(input *models.SetupInput) {289 if input.ConfigLocation == "" {290 input.ConfigLocation = filepath.Join(fsutil.GetHomeDirectory(), ".stash", "config.yml")291 }292 configDir := filepath.Dir(input.ConfigLocation)293 if input.GeneratedLocation == "" {294 input.GeneratedLocation = filepath.Join(configDir, "generated")295 }296 if input.DatabaseFile == "" {297 input.DatabaseFile = filepath.Join(configDir, "stash-go.sqlite")298 }299}300func (s *Manager) Setup(ctx context.Context, input models.SetupInput) error {301 setSetupDefaults(&input)302 c := s.Config303 // create the config directory if it does not exist304 // don't do anything if config is already set in the environment305 if !config.FileEnvSet() {306 configDir := filepath.Dir(input.ConfigLocation)307 if exists, _ := fsutil.DirExists(configDir); !exists {308 if err := os.Mkdir(configDir, 0755); err != nil {309 return fmt.Errorf("error creating config directory: %v", err)310 }311 }312 if err := fsutil.Touch(input.ConfigLocation); err != nil {313 return fmt.Errorf("error creating config file: %v", err)314 }315 s.Config.SetConfigFile(input.ConfigLocation)316 }317 // create the generated directory if it does not exist318 if !c.HasOverride(config.Generated) {319 if exists, _ := fsutil.DirExists(input.GeneratedLocation); !exists {320 if err := os.Mkdir(input.GeneratedLocation, 0755); err != nil {321 return fmt.Errorf("error creating generated directory: %v", err)322 }323 }324 s.Config.Set(config.Generated, input.GeneratedLocation)325 }326 // set the configuration327 if !c.HasOverride(config.Database) {328 s.Config.Set(config.Database, input.DatabaseFile)329 }330 s.Config.Set(config.Stash, input.Stashes)331 if err := s.Config.Write(); err != nil {332 return fmt.Errorf("error writing configuration file: %v", err)333 }334 // initialise the database335 if err := s.PostInit(ctx); err != nil {336 return fmt.Errorf("error initializing the database: %v", err)337 }338 s.Config.FinalizeSetup()339 if err := initFFMPEG(ctx); err != nil {340 return fmt.Errorf("error initializing FFMPEG subsystem: %v", err)341 }342 return nil343}344func (s *Manager) validateFFMPEG() error {345 if s.FFMPEG == "" || s.FFProbe == "" {346 return errors.New("missing ffmpeg and/or ffprobe")347 }348 return nil349}350func (s *Manager) Migrate(ctx context.Context, input models.MigrateInput) error {351 // always backup so that we can roll back to the previous version if352 // migration fails353 backupPath := input.BackupPath354 if backupPath == "" {...

Full Screen

Full Screen

store_test.go

Source:store_test.go Github

copy

Full Screen

1package storage2import (3 "math/rand"4 "testing"5 "time"6)7func genAlphaNum(length int) string {8 var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")9 s := make([]rune, length)10 for i := range s {11 s[i] = letters[rand.Intn(len(letters))]12 }13 return string(s)14}15func genRandomData(length int) []string {16 bucket := make([]string, length)17 for i := range bucket {18 bucket[i] = genAlphaNum(17)19 }20 return bucket21}22func getStorage(d time.Duration) *MapStore {23 return InitMapStore(d)24}25func TestMapStore_Write(t *testing.T) {26 storage := getStorage(2 * time.Second) // Инициализируем время хранения 1 секунда27 storage.Write("foo1", "bar1") // Пишем первое значение28 storage.Write("foo2", "bar2") // Пишем второе значение29 if i, value := storage.Read("foo1"); i != 0 || value != "bar1" {30 t.Errorf("cannot found the wrote data with foo1 key")31 }32 if i, value := storage.Read("foo2"); i != 1 || value != "bar2" {33 t.Errorf("cannot found the wrote data with foo1 key")34 }35 if size := storage.Size(); size != 2 {36 t.Errorf("Size() must be 2, not %d", size)37 }38 time.Sleep(3 * time.Second) // Ждем пока срок хранения данных не истечет39 if i, value := storage.Read("foo1"); i == 0 && value == "bar1" {40 t.Errorf("expired data found: foo1")41 }42 if i, value := storage.Read("foo2"); i == 1 && value == "bar2" {43 t.Errorf("expired data found: foo2")44 }45 if size := storage.Size(); size != 0 {46 t.Errorf("Size() must be 0, not %d", size)47 }48}49func TestMapStore_Inc(t *testing.T) {50 store := InitMapStore(3 * time.Second)51 defer store.Close()52 testData := map[string]string{53 "foo1": "bar1",54 "foo2": "bar2",55 "foo3": "bar3",56 "foo4": "bar4",57 "foo5": "bar5",58 "foo6": "bar6",59 }60 for k, v := range testData {61 store.Write(k, v)62 }63 tests := []struct {64 name string65 store *MapStore66 wantValue interface{}67 }{68 {69 name: "IncTest",70 store: store,71 wantValue: nil,72 },73 }74 for _, tt := range tests {75 t.Run(tt.name, func(t *testing.T) {76 iter := 077 for _, _ = range testData {78 iter++79 value := store.Inc()80 if value == nil {81 t.Errorf("cannot found value on %d iteration", iter)82 }83 }84 })85 }86}87func BenchmarkMapStore_Write_18(bench *testing.B) {88 store := InitMapStore(3 * time.Second)89 defer store.Close()90 bench.ReportAllocs()91 bench.ResetTimer()92 bench.RunParallel(func(pb *testing.PB) {93 for pb.Next() {94 store.Write(genAlphaNum(18), struct{}{})95 }96 })97}98func BenchmarkMapStore_Write_1000(bench *testing.B) {99 store := InitMapStore(3 * time.Second)100 defer store.Close()101 bench.ReportAllocs()102 bench.ResetTimer()103 bench.RunParallel(func(pb *testing.PB) {104 for pb.Next() {105 store.Write(genAlphaNum(1000), struct{}{})106 }107 })108}109func BenchmarkMapStore_Read_100(bench *testing.B) {110 generatedData := genRandomData(100)111 store := InitMapStore(3 * time.Second)112 defer store.Close()113 for _, d := range generatedData {114 store.Write(d, struct{}{})115 }116 bench.ReportAllocs()117 bench.ResetTimer()118 bench.RunParallel(func(pb *testing.PB) {119 for pb.Next() {120 for _, k := range generatedData {121 store.Read(k)122 }123 }124 })125}126func BenchmarkMapStore_Read_10000(bench *testing.B) {127 generatedData := genRandomData(10000)128 store := InitMapStore(3 * time.Second)129 defer store.Close()130 for _, d := range generatedData {131 store.Write(d, struct{}{})132 }133 bench.ReportAllocs()134 bench.ResetTimer()135 bench.RunParallel(func(pb *testing.PB) {136 for pb.Next() {137 for _, k := range generatedData {138 store.Read(k)139 }140 }141 })142}143func BenchmarkMapStore_Read_1000000(bench *testing.B) {144 generatedData := genRandomData(1000000)145 store := InitMapStore(3 * time.Second)146 defer store.Close()147 for _, d := range generatedData {148 store.Write(d, struct{}{})149 }150 bench.ReportAllocs()151 bench.ResetTimer()152 bench.RunParallel(func(pb *testing.PB) {153 for pb.Next() {154 for _, k := range generatedData {155 store.Read(k)156 }157 }158 })159}160func BenchmarkMapStore_Inc_100(bench *testing.B) {161 generatedData := genRandomData(100)162 store := InitMapStore(3 * time.Second)163 defer store.Close()164 for _, d := range generatedData {165 store.Write(d, struct{}{})166 }167 bench.ReportAllocs()168 bench.ResetTimer()169 bench.RunParallel(func(pb *testing.PB) {170 for pb.Next() {171 store.Inc()172 }173 })174}175func BenchmarkMapStore_Inc_10000(bench *testing.B) {176 generatedData := genRandomData(10000)177 store := InitMapStore(3 * time.Second)178 defer store.Close()179 for _, d := range generatedData {180 store.Write(d, struct{}{})181 }182 bench.ReportAllocs()183 bench.ResetTimer()184 bench.RunParallel(func(pb *testing.PB) {185 for pb.Next() {186 store.Inc()187 }188 })189}190func BenchmarkMapStore_Inc_1000000(bench *testing.B) {191 generatedData := genRandomData(1000000)192 store := InitMapStore(3 * time.Second)193 defer store.Close()194 for _, d := range generatedData {195 store.Write(d, struct{}{})196 }197 bench.ReportAllocs()198 bench.ResetTimer()199 bench.RunParallel(func(pb *testing.PB) {200 for pb.Next() {201 store.Inc()202 }203 })204}...

Full Screen

Full Screen

generator_test.go

Source:generator_test.go Github

copy

Full Screen

1/*2Copyright 2020 The Magma Authors.3This source code is licensed under the BSD-style license found in the4LICENSE file in the root directory of this source tree.5Unless required by applicable law or agreed to in writing, software6distributed under the License is distributed on an "AS IS" BASIS,7WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.8See the License for the specific language governing permissions and9limitations under the License.10*/11package dictionarygen12import (13 "bytes"14 "io/ioutil"15 "os"16 "path/filepath"17 "strings"18 "testing"19 "fbc/lib/go/radius/dictionary"20)21func TestTestData(t *testing.T) {22 tbl := []struct {23 Name string24 InitParser func(*dictionary.Parser)25 InitGenerator func(*Generator)26 Err string27 }{28 {29 Name: "identical-attributes",30 InitParser: func(p *dictionary.Parser) {31 p.IgnoreIdenticalAttributes = true32 },33 },34 {35 Name: "identifier-collision",36 Err: "conflicting identifier between First_Name (200) and First-Name (201)",37 },38 {39 Name: "tlv-attributes",40 },41 }42 for _, tt := range tbl {43 t.Run(tt.Name, func(t *testing.T) {44 parser := &dictionary.Parser{45 Opener: &dictionary.FileSystemOpener{},46 }47 if tt.InitParser != nil {48 tt.InitParser(parser)49 }50 dictFile := filepath.Join("testdata", tt.Name+".dictionary")51 dict, err := parser.ParseFile(dictFile)52 if err != nil {53 t.Fatalf("could not parse file: %s", err)54 }55 generator := &Generator{56 Package: "main",57 }58 if tt.InitGenerator != nil {59 tt.InitGenerator(generator)60 }61 generatedCode, err := generator.Generate(dict)62 if err != nil {63 if tt.Err != "" {64 if !strings.Contains(err.Error(), tt.Err) {65 t.Fatalf("got generate error %v; expected %v", err, tt.Err)66 }67 return68 }69 t.Fatalf("could not generate dictionary code: %s", err)70 }71 generatedFile := filepath.Join("testdata", tt.Name+".generated")72 if err := ioutil.WriteFile(generatedFile, generatedCode, 0644); err != nil {73 t.Fatalf("could not write generated file: %s", err)74 }75 expectedFile := filepath.Join("testdata", tt.Name+".expected")76 expectedCode, err := ioutil.ReadFile(expectedFile)77 if err != nil {78 t.Fatalf("could not read expected output: %s", err)79 }80 if !bytes.Equal(generatedCode, expectedCode) {81 t.Fatal("generated code does not equal expected")82 }83 os.Remove(generatedFile)84 })85 }86}...

Full Screen

Full Screen

init

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Printf("Hello, world. Sqrt(2) = %v\n", def.Sqrt(2))4}5import (6func main() {7 fmt.Printf("Hello, world. Sqrt(2) = %v\n", def.Sqrt(2))8}9import (10func main() {11 fmt.Printf("Hello, world. Sqrt(2) = %v\n", def.Sqrt(2))12}13import (14func main() {15 fmt.Printf("Hello, world. Sqrt(2) = %v\n", def.Sqrt(2))16}17import (18func main() {19 fmt.Printf("Hello, world. Sqrt(2) = %v\n", def.Sqrt(2))20}21import (22func main() {23 fmt.Printf("Hello, world. Sqrt(2) = %v\n", def.Sqrt(2))24}25import (26func main() {27 fmt.Printf("Hello, world. Sqrt(2) = %v\n", def.Sqrt(2))28}29import (30func main() {31 fmt.Printf("Hello, world. Sqrt(2) = %v\n", def.Sqrt(2))32}

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Syzkaller automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful