Best Rod code snippet using rod.Shape
e_rjoint.go
Source:e_rjoint.go
1// Copyright 2015 Dorival Pedroso and Raul Durand. All rights reserved.2// Use of this source code is governed by a BSD-style3// license that can be found in the LICENSE file.4package fem5import (6 "github.com/cpmech/gofem/inp"7 "github.com/cpmech/gofem/msolid"8 "github.com/cpmech/gosl/fun"9 "github.com/cpmech/gosl/io"10 "github.com/cpmech/gosl/la"11 "github.com/cpmech/gosl/tsr"12 "github.com/cpmech/gosl/utl"13)14// Rjoint implements the rod-joint (interface/link) element for reinforced solids.15// The following convention is considered:16// n or N -- means [N]odes17// p or P -- means integratioin [P]oints18// nn or Nn -- number of nodes19// np or Np -- number of integration [P]points20// ndim -- space dimension21// nsig -- number of stress/strain components == 2 * ndim22// rod -- means rod element23// rodH -- rod shape structure24// rodNn -- rod number of nodes25// rodNp -- rod number of integration points26// rodS -- rod shape functions27// sld -- means solid element28// sldH -- rod shape structure29// sldNn -- solid number of nodes30// sldNp -- solid number of integration points31// sldS -- solid shape functions32// rodYn -- rod's (real) coordinates of node33// rodYp -- rod's (real) coordinates of integration point34// r or R -- means natural coordinates in the solids' system35// z or Z -- means natural coordinates in the rod's system36// s or S -- parametric coordinate along rod37// rodRn -- natural coordinates or rod's nodes w.r.t solid's system38// rodRp -- natural coordinates of rod's integration point w.r.t to solid's system39// Nmat -- solid shape functions evaluated at rod nodes40// Pmat -- solid shape functions evaluated at rod integration points41// References:42// [1] R Durand, MM Farias, DM Pedroso. Modelling the strengthening of solids with43// incompatible line finite elements, Computers and Structures (2014). Submitted.44// [2] R Durand, MM Farias, DM Pedroso, Computing intersections between non-compatible45// curves and finite elements, Computational Mechanics (2014). Submitted.46// [3] R Durand, MM Farias. A local extrapolation method for finite elements,47// Advances in Engineering Software 67 (2014) 1-9.48// http://dx.doi.org/10.1016/j.advengsoft.2013.07.00249type Rjoint struct {50 // basic data51 Edat *inp.ElemData // element data; stored in allocator to be used in Connect52 Cid int // cell/element id53 Ny int // total number of dofs == rod.Nu + sld.Nu54 // essential55 Rod *Rod // rod element56 Sld *ElemU // solid element57 Mdl msolid.RjointM1 // material model58 // parameters59 h float64 // perimeter of rod element; Eq (34)60 k1 float64 // lateral stiffness; Eq (37)61 k2 float64 // lateral stiffness; Eq (37)62 // optional data63 Ncns bool // use non-consistent model64 // shape functions evaluations and extrapolator matrices65 Nmat [][]float64 // [sldNn][rodNn] shape functions of solids @ [N]odes of rod element66 Pmat [][]float64 // [sldNn][rodNp] shape functions of solids @ integration [P]oints of rod element (for Coulomb model)67 Emat [][]float64 // [sldNn][sldNp] solid's extrapolation matrix (for Coulomb model)68 // variables for Coulomb model69 Coulomb bool // use Coulomb model70 rodRp [][]float64 // [rodNp][ndim] natural coordinates of ips of rod w.r.t. solid's system71 ÏNo [][]float64 // [nneSld][nsig] Ï at nodes of solid72 ÏIp []float64 // [nsig] Ï at ips of rod73 t1 []float64 // [ndim] traction vectors for Ïc74 t2 []float64 // [ndim] traction vectors for Ïc75 T1 [][]float64 // [rodNp][nsig] tensor (e1 dy e1)76 T2 [][]float64 // [rodNp][nsig] tensor (e2 dy e2)77 DÏNoDu [][][][]float64 // [sldNn][nsig][sldNn][ndim] âÏSldNod/âuSldNod : derivatives of Ï @ nodes of solid w.r.t displacements of solid78 DÏDun [][]float64 // [nsig][ndim] âÏIp/âus : derivatives of Ï @ ip of solid w.r.t displacements of solid79 // corotational system aligned with rod element80 e0 [][]float64 // [rodNp][ndim] local directions at each integration point of rod81 e1 [][]float64 // [rodNp][ndim] local directions at each integration point of rod82 e2 [][]float64 // [rodNp][ndim] local directions at each integration point of rod83 // auxiliary variables84 ÎuC [][]float64 // [rodNn][ndim] relative displ. increment of solid @ nodes of rod; Eq (30)85 Îw []float64 // [ndim] relative velocity; Eq (32)86 qb []float64 // [ndim] resultant traction vector 'holding' the rod @ ip; Eq (34)87 fC []float64 // [rodNu] internal/contact forces vector; Eq (34)88 // temporary Jacobian matrices. see Eq. (57)89 Krr [][]float64 // [rodNu][rodNu] Eq. (58)90 Krs [][]float64 // [rodNu][sldNu] Eq. (59)91 Ksr [][]float64 // [sldNu][rodNu] Eq. (60)92 Kss [][]float64 // [sldNu][sldNu] Eq. (61)93 // internal values94 States []*msolid.OnedState // [nip] internal states95 StatesBkp []*msolid.OnedState // [nip] backup internal states96}97// initialisation ///////////////////////////////////////////////////////////////////////////////////98// register element99func init() {100 // information allocator101 infogetters["rjoint"] = func(cellType string, faceConds []*FaceCond) *Info {102 return &Info{}103 }104 // element allocator105 eallocators["rjoint"] = func(cellType string, faceConds []*FaceCond, cid int, edat *inp.ElemData, x [][]float64) Elem {106 var o Rjoint107 o.Edat = edat108 o.Cid = cid109 return &o110 }111}112// Id returns the cell Id113func (o Rjoint) Id() int { return o.Cid }114// Connect connects rod/solid elements in this Rjoint115func (o *Rjoint) Connect(cid2elem []Elem, c *inp.Cell) (nnzK int, ok bool) {116 // get rod and solid elements117 rodId := c.JlinId118 sldId := c.JsldId119 o.Rod = cid2elem[rodId].(*Rod)120 o.Sld = cid2elem[sldId].(*ElemU)121 if LogErrCond(o.Rod == nil, "cannot find joint's rod cell with id == %d", rodId) {122 return123 }124 if LogErrCond(o.Sld == nil, "cannot find joint's solid cell with id == %d", sldId) {125 return126 }127 // total number of dofs128 o.Ny = o.Rod.Nu + o.Sld.Nu129 // material model name130 matname := o.Edat.Mat131 matdata := Global.Sim.Mdb.Get(matname)132 if LogErrCond(matdata == nil, "materials database failed on getting %q material\n", matname) {133 return134 }135 // initialise model136 if LogErr(o.Mdl.Init(matdata.Prms), "cannot initialise model for Rjoint element") {137 return138 }139 // parameters140 for _, p := range matdata.Prms {141 switch p.N {142 case "h":143 o.h = p.V144 case "k1":145 o.k1 = p.V146 case "k2":147 o.k2 = p.V148 case "mu":149 if p.V > 0.0 {150 o.Coulomb = true151 }152 }153 }154 // auxiliary155 ndim := Global.Ndim156 nsig := 2 * ndim157 // rod data158 rodH := o.Rod.Shp159 rodNp := len(o.Rod.IpsElem)160 rodNn := rodH.Nverts161 rodNu := o.Rod.Nu162 // solid data163 sldH := o.Sld.Shp164 sldS := sldH.S165 sldNp := len(o.Sld.IpsElem)166 sldNn := sldH.Nverts167 sldNu := o.Sld.Nu168 // shape functions of solid @ nodes of rod169 o.Nmat = la.MatAlloc(sldNn, rodNn)170 rodYn := make([]float64, ndim)171 rodRn := make([]float64, 3)172 for m := 0; m < rodNn; m++ {173 for i := 0; i < ndim; i++ {174 rodYn[i] = o.Rod.X[i][m]175 }176 if LogErr(sldH.InvMap(rodRn, rodYn, o.Sld.X), "inverse map failed") {177 return178 }179 if LogErr(sldH.CalcAtR(o.Sld.X, rodRn, false), "shape functions calculation failed") {180 return181 }182 for n := 0; n < sldNn; n++ {183 o.Nmat[n][m] = sldH.S[n]184 }185 }186 // coulomb model => Ïc depends on p values of solid187 if o.Coulomb {188 // allocate variables189 o.Pmat = la.MatAlloc(sldNn, rodNp)190 o.Emat = la.MatAlloc(sldNn, sldNp)191 o.rodRp = la.MatAlloc(rodNp, 3)192 o.ÏNo = la.MatAlloc(sldNn, nsig)193 o.ÏIp = make([]float64, nsig)194 o.t1 = make([]float64, ndim)195 o.t2 = make([]float64, ndim)196 o.T1 = la.MatAlloc(rodNp, nsig)197 o.T2 = la.MatAlloc(rodNp, nsig)198 o.DÏNoDu = utl.Deep4alloc(sldNn, nsig, sldNn, ndim)199 o.DÏDun = la.MatAlloc(nsig, ndim)200 // extrapolator matrix201 if LogErr(sldH.Extrapolator(o.Emat, o.Sld.IpsElem), "Extrapolator of solid failed") {202 return203 }204 // shape function of solid @ ips of rod205 for idx, ip := range o.Rod.IpsElem {206 rodYp := rodH.IpRealCoords(o.Rod.X, ip)207 if LogErr(sldH.InvMap(o.rodRp[idx], rodYp, o.Sld.X), "inverse map failed") {208 return209 }210 if LogErr(sldH.CalcAtR(o.Sld.X, o.rodRp[idx], false), "shape functions calculation failed") {211 return212 }213 for n := 0; n < sldNn; n++ {214 o.Pmat[n][idx] = sldS[n]215 }216 }217 }218 // joint direction @ ip[idx]; corotational system aligned with rod element219 o.e0 = la.MatAlloc(rodNp, ndim)220 o.e1 = la.MatAlloc(rodNp, ndim)221 o.e2 = la.MatAlloc(rodNp, ndim)222 Ï := make([]float64, ndim) // Eq. (27)223 Q := la.MatAlloc(ndim, ndim)224 α := 666.0225 Jvec := rodH.Jvec3d[:ndim]226 for idx, ip := range o.Rod.IpsElem {227 // auxiliary228 e0, e1, e2 := o.e0[idx], o.e1[idx], o.e2[idx]229 // interpolation functions and gradients230 if LogErr(rodH.CalcAtIp(o.Rod.X, ip, true), "shape functions calculation failed") {231 return232 }233 // compute basis vectors234 J := rodH.J235 Ï[0] = Jvec[0] + α236 Ï[1] = Jvec[1]237 e0[0] = Jvec[0] / J238 e0[1] = Jvec[1] / J239 if ndim == 3 {240 Ï[2] = Jvec[2]241 e0[2] = Jvec[2] / J242 }243 la.MatSetDiag(Q, 1)244 la.VecOuterAdd(Q, -1, e0, e0) // Q := I - e0 dyad e0245 la.MatVecMul(e1, 1, Q, Ï) // Eq. (29) * norm(E1)246 la.VecScale(e1, 0, 1.0/la.VecNorm(e1), e1)247 if ndim == 3 {248 e2[0] = e0[1]*e1[2] - e0[2]*e1[1]249 e2[1] = e0[2]*e1[0] - e0[0]*e1[2]250 e2[2] = e0[0]*e1[1] - e0[1]*e1[0]251 }252 // compute auxiliary tensors253 if o.Coulomb {254 e1_dy_e1 := tsr.Alloc2()255 e2_dy_e2 := tsr.Alloc2()256 for i := 0; i < ndim; i++ {257 for j := 0; j < ndim; j++ {258 e1_dy_e1[i][j] = e1[i] * e1[j]259 e2_dy_e2[i][j] = e2[i] * e2[j]260 }261 }262 tsr.Ten2Man(o.T1[idx], e1_dy_e1)263 tsr.Ten2Man(o.T2[idx], e2_dy_e2)264 }265 }266 // auxiliary variables267 o.ÎuC = la.MatAlloc(rodNn, ndim)268 o.Îw = make([]float64, ndim)269 o.qb = make([]float64, ndim)270 o.fC = make([]float64, rodNu)271 // temporary Jacobian matrices. see Eq. (57)272 o.Krr = la.MatAlloc(rodNu, rodNu)273 o.Krs = la.MatAlloc(rodNu, sldNu)274 o.Ksr = la.MatAlloc(sldNu, rodNu)275 o.Kss = la.MatAlloc(sldNu, sldNu)276 // debugging277 //if true {278 if false {279 o.debug_print_init()280 }281 // success282 return o.Ny * o.Ny, true283}284// implementation ///////////////////////////////////////////////////////////////////////////////////285// SetEqs set equations286func (o *Rjoint) SetEqs(eqs [][]int, mixedform_eqs []int) (ok bool) {287 return true288}289// SetEleConds set element conditions290func (o *Rjoint) SetEleConds(key string, f fun.Func, extra string) (ok bool) {291 return true292}293// InterpStarVars interpolates star variables to integration points294func (o *Rjoint) InterpStarVars(sol *Solution) (ok bool) {295 return true296}297// adds -R to global residual vector fb298func (o *Rjoint) AddToRhs(fb []float64, sol *Solution) (ok bool) {299 // auxiliary300 ndim := Global.Ndim301 rodH := o.Rod.Shp302 rodS := rodH.S303 rodNn := rodH.Nverts304 sldH := o.Sld.Shp305 sldNn := sldH.Nverts306 // internal forces vector307 la.VecFill(o.fC, 0)308 // loop over rod's integration points309 var coef, Ï, qn1, qn2 float64310 for idx, ip := range o.Rod.IpsElem {311 // auxiliary312 e0, e1, e2 := o.e0[idx], o.e1[idx], o.e2[idx]313 // interpolation functions and gradients314 if LogErr(rodH.CalcAtIp(o.Rod.X, ip, true), "AddToRhs") {315 return316 }317 coef = ip.W * rodH.J318 // state variables319 Ï = o.States[idx].Sig320 qn1 = o.States[idx].Phi[0]321 qn2 = o.States[idx].Phi[1]322 // fC vector. Eq. (34)323 for i := 0; i < ndim; i++ {324 o.qb[i] = Ï*o.h*e0[i] + qn1*e1[i] + qn2*e2[i]325 for m := 0; m < rodNn; m++ {326 r := i + m*ndim327 o.fC[r] += coef * rodS[m] * o.qb[i]328 }329 }330 }331 // fb = -Resid; fR = -fC and fS = Nmat*fC => fb := {fC, -Nmat*fC}332 for i := 0; i < ndim; i++ {333 for m := 0; m < rodNn; m++ {334 r := i + m*ndim335 I := o.Rod.Umap[r]336 fb[I] += o.fC[r] // fb := - (fR == -fC Eq (35))337 for n := 0; n < sldNn; n++ {338 s := i + n*ndim339 J := o.Sld.Umap[s]340 fb[J] -= o.Nmat[n][m] * o.fC[r] // fb := - (fS Eq (36))341 }342 }343 }344 return true345}346// adds element K to global Jacobian matrix Kb347func (o *Rjoint) AddToKb(Kb *la.Triplet, sol *Solution, firstIt bool) (ok bool) {348 // auxiliary349 ndim := Global.Ndim350 nsig := 2 * ndim351 rodH := o.Rod.Shp352 rodS := rodH.S353 rodNn := rodH.Nverts354 sldH := o.Sld.Shp355 sldNn := sldH.Nverts356 // compute DÏNoDu357 if o.Coulomb {358 // clear deep4 structure359 utl.Deep4set(o.DÏNoDu, 0)360 // loop over solid's integration points361 for idx, ip := range o.Sld.IpsElem {362 // interpolation functions, gradients and variables @ ip363 if LogErr(sldH.CalcAtIp(o.Sld.X, ip, true), "AddToKb") {364 return365 }366 // consistent tangent model matrix367 if LogErr(o.Sld.MdlSmall.CalcD(o.Sld.D, o.Sld.States[idx], firstIt), "AddToKb") {368 return369 }370 // extrapolate derivatives371 for n := 0; n < sldNn; n++ {372 DerivSig(o.DÏDun, n, ndim, sldH.G, o.Sld.D)373 for m := 0; m < sldNn; m++ {374 for i := 0; i < nsig; i++ {375 for j := 0; j < ndim; j++ {376 o.DÏNoDu[m][i][n][j] += o.Emat[m][idx] * o.DÏDun[i][j]377 }378 }379 }380 }381 }382 }383 // debugging384 //if true {385 if false {386 utl.PrintDeep4("DÏNoDu", o.DÏNoDu, "%20.10f")387 }388 // zero K matrices389 for i, _ := range o.Rod.Umap {390 for j, _ := range o.Rod.Umap {391 o.Krr[i][j] = 0392 }393 for j, _ := range o.Sld.Umap {394 o.Krs[i][j] = 0395 o.Ksr[j][i] = 0396 }397 }398 la.MatFill(o.Kss, 0)399 // auxiliary400 var coef float64401 var DÏDÏ, DÏDÏc, DÏcDu_nj float64402 var Dp1Du_nj, Dp2Du_nj float64403 var Dwb0Du_nj, Dwb1Du_nj, Dwb2Du_nj float64404 var DÏDu_nj, DqbDu_nij float64405 var Dwb0Dur_nj, Dwb1Dur_nj, Dwb2Dur_nj float64406 var DqbDur_nij float64407 // loop over rod's integration points408 var err error409 for idx, ip := range o.Rod.IpsElem {410 // auxiliary411 e0, e1, e2 := o.e0[idx], o.e1[idx], o.e2[idx]412 // interpolation functions and gradients413 if LogErr(rodH.CalcAtIp(o.Rod.X, ip, true), "AddToKb") {414 return415 }416 coef = ip.W * rodH.J417 // model derivatives418 DÏDÏ, DÏDÏc, err = o.Mdl.CalcD(o.States[idx], firstIt)419 if LogErr(err, "AddToKb") {420 return421 }422 // compute derivatives423 for j := 0; j < ndim; j++ {424 // Krr and Ksr; derivatives with respect to ur_nj425 for n := 0; n < rodNn; n++ {426 // âwb/âur Eq (A.4)427 Dwb0Dur_nj = -rodS[n] * e0[j]428 Dwb1Dur_nj = -rodS[n] * e1[j]429 Dwb2Dur_nj = -rodS[n] * e2[j]430 // compute ââ /âur derivatives431 c := j + n*ndim432 for i := 0; i < ndim; i++ {433 // âqb/âur Eq (A.2)434 DqbDur_nij = o.h*e0[i]*(DÏDÏ*Dwb0Dur_nj) + o.k1*e1[i]*Dwb1Dur_nj + o.k2*e2[i]*Dwb2Dur_nj435 // Krr := âfr/âur Eq (58)436 for m := 0; m < rodNn; m++ {437 r := i + m*ndim438 o.Krr[r][c] -= coef * rodS[m] * DqbDur_nij439 }440 // Ksr := âfs/âur Eq (60)441 for m := 0; m < sldNn; m++ {442 r := i + m*ndim443 for p := 0; p < rodNn; p++ {444 o.Ksr[r][c] += coef * o.Nmat[m][p] * rodS[p] * DqbDur_nij445 }446 }447 }448 }449 // Krs and Kss450 for n := 0; n < sldNn; n++ {451 // âÏc/âus_nj452 DÏcDu_nj = 0453 if o.Coulomb {454 // Eqs (A.10) (A.11) and (A.12)455 Dp1Du_nj, Dp2Du_nj = 0, 0456 for m := 0; m < sldNn; m++ {457 for i := 0; i < nsig; i++ {458 Dp1Du_nj += o.Pmat[m][idx] * o.T1[idx][i] * o.DÏNoDu[m][i][n][j]459 Dp2Du_nj += o.Pmat[m][idx] * o.T2[idx][i] * o.DÏNoDu[m][i][n][j]460 }461 }462 DÏcDu_nj = (Dp1Du_nj + Dp2Du_nj) / 2.0463 }464 // âwb/âus Eq (A.5)465 Dwb0Du_nj, Dwb1Du_nj, Dwb2Du_nj = 0, 0, 0466 for m := 0; m < rodNn; m++ {467 Dwb0Du_nj += rodS[m] * o.Nmat[n][m] * e0[j]468 Dwb1Du_nj += rodS[m] * o.Nmat[n][m] * e1[j]469 Dwb2Du_nj += rodS[m] * o.Nmat[n][m] * e2[j]470 }471 // âÏ/âus_nj hightlighted term in Eq (A.3)472 DÏDu_nj = DÏDÏ*Dwb0Du_nj + DÏDÏc*DÏcDu_nj473 if o.Ncns {474 DÏDu_nj = DÏDÏ * Dwb0Du_nj475 }476 // compute ââ /âus derivatives477 c := j + n*ndim478 for i := 0; i < ndim; i++ {479 // âqb/âus Eq (A.3)480 DqbDu_nij = o.h*e0[i]*DÏDu_nj + o.k1*e1[i]*Dwb1Du_nj + o.k2*e2[i]*Dwb2Du_nj481 // Krs := âfr/âus Eq (59)482 for m := 0; m < rodNn; m++ {483 r := i + m*ndim484 o.Krs[r][c] -= coef * rodS[m] * DqbDu_nij485 }486 // Kss := âfs/âus Eq (61)487 for m := 0; m < sldNn; m++ {488 r := i + m*ndim489 for p := 0; p < rodNn; p++ {490 o.Kss[r][c] += coef * o.Nmat[m][p] * rodS[p] * DqbDu_nij491 }492 }493 }494 }495 }496 }497 // debug498 //if true {499 if false {500 o.debug_print_K()501 }502 // add K to sparse matrix Kb503 for i, I := range o.Rod.Umap {504 for j, J := range o.Rod.Umap {505 Kb.Put(I, J, o.Krr[i][j])506 }507 for j, J := range o.Sld.Umap {508 Kb.Put(I, J, o.Krs[i][j])509 Kb.Put(J, I, o.Ksr[j][i])510 }511 }512 for i, I := range o.Sld.Umap {513 for j, J := range o.Sld.Umap {514 Kb.Put(I, J, o.Kss[i][j])515 }516 }517 return true518}519// Update perform (tangent) update520func (o *Rjoint) Update(sol *Solution) (ok bool) {521 // auxiliary522 ndim := Global.Ndim523 nsig := 2 * ndim524 rodH := o.Rod.Shp525 rodS := rodH.S526 rodNn := rodH.Nverts527 sldH := o.Sld.Shp528 sldNn := sldH.Nverts529 // extrapolate stresses at integration points of solid element to its nodes530 if o.Coulomb {531 la.MatFill(o.ÏNo, 0)532 for idx, _ := range o.Sld.IpsElem {533 Ï := o.Sld.States[idx].Sig534 for i := 0; i < nsig; i++ {535 for m := 0; m < sldNn; m++ {536 o.ÏNo[m][i] += o.Emat[m][idx] * Ï[i]537 }538 }539 }540 }541 // interpolate Îu of solid to find ÎuC @ rod node; Eq (30)542 var r, I int543 for m := 0; m < rodNn; m++ {544 for i := 0; i < ndim; i++ {545 o.ÎuC[m][i] = 0546 for n := 0; n < sldNn; n++ {547 r = i + n*ndim548 I = o.Sld.Umap[r]549 o.ÎuC[m][i] += o.Nmat[n][m] * sol.ÎY[I] // Eq (30)550 }551 }552 }553 // loop over ips of rod554 var Îwb0, Îwb1, Îwb2, Ïc float64555 for idx, ip := range o.Rod.IpsElem {556 // auxiliary557 e0, e1, e2 := o.e0[idx], o.e1[idx], o.e2[idx]558 // interpolation functions and gradients559 if LogErr(rodH.CalcAtIp(o.Rod.X, ip, true), "Update") {560 return561 }562 // interpolated relative displacements @ ip of join; Eqs (31) and (32)563 for i := 0; i < ndim; i++ {564 o.Îw[i] = 0565 for m := 0; m < rodNn; m++ {566 r = i + m*ndim567 I = o.Rod.Umap[r]568 o.Îw[i] += rodS[m] * (o.ÎuC[m][i] - sol.ÎY[I]) // Eq (31) and (32)569 }570 }571 // relative displacents in the coratational system572 Îwb0, Îwb1, Îwb2 = 0, 0, 0573 for i := 0; i < ndim; i++ {574 Îwb0 += e0[i] * o.Îw[i]575 Îwb1 += e1[i] * o.Îw[i]576 Îwb2 += e2[i] * o.Îw[i]577 }578 // new confining stress579 Ïc = 0.0580 if o.Coulomb {581 // calculate ÏIp582 for j := 0; j < nsig; j++ {583 o.ÏIp[j] = 0584 for n := 0; n < sldNn; n++ {585 o.ÏIp[j] += o.Pmat[n][idx] * o.ÏNo[n][j]586 }587 }588 // calculate t1 and t2589 for i := 0; i < ndim; i++ {590 o.t1[i], o.t2[i] = 0, 0591 for j := 0; j < ndim; j++ {592 o.t1[i] += tsr.M2T(o.ÏIp, i, j) * e1[j]593 o.t2[i] += tsr.M2T(o.ÏIp, i, j) * e2[j]594 }595 }596 // calculate p1, p2 and ÏcNew597 p1, p2 := 0.0, 0.0598 for i := 0; i < ndim; i++ {599 p1 += o.t1[i] * e1[i]600 p2 += o.t2[i] * e2[i]601 }602 // ÏcNew603 Ïc = -(p1 + p2) / 2.0604 }605 // update model606 if LogErr(o.Mdl.Update(o.States[idx], Ïc, Îwb0), "Update") {607 return608 }609 o.States[idx].Phi[0] += o.k1 * Îwb1 // qn1610 o.States[idx].Phi[1] += o.k2 * Îwb2 // qn2611 // debugging612 //if true {613 if false {614 o.debug_update(idx, Îwb0, Îwb1, Îwb2, Ïc)615 }616 }617 return true618}619// internal variables ///////////////////////////////////////////////////////////////////////////////620// Ipoints returns the real coordinates of integration points [nip][ndim]621func (o Rjoint) Ipoints() (coords [][]float64) {622 return o.Rod.Ipoints()623}624// SetIniIvs sets initial ivs for given values in sol and ivs map625func (o *Rjoint) SetIniIvs(sol *Solution, ivs map[string][]float64) (ok bool) {626 nip := len(o.Rod.IpsElem)627 o.States = make([]*msolid.OnedState, nip)628 o.StatesBkp = make([]*msolid.OnedState, nip)629 for i := 0; i < nip; i++ {630 o.States[i], _ = o.Mdl.InitIntVars()631 o.StatesBkp[i] = o.States[i].GetCopy()632 }633 return true634}635// BackupIvs create copy of internal variables636func (o *Rjoint) BackupIvs() (ok bool) {637 for i, s := range o.StatesBkp {638 s.Set(o.States[i])639 }640 return true641}642// RestoreIvs restore internal variables from copies643func (o *Rjoint) RestoreIvs() (ok bool) {644 for i, s := range o.States {645 s.Set(o.StatesBkp[i])646 }647 return true648}649// Ureset fixes internal variables after u (displacements) have been zeroed650func (o *Rjoint) Ureset(sol *Solution) (ok bool) {651 return true652}653// writer ///////////////////////////////////////////////////////////////////////////////////////////654// Encode encodes internal variables655func (o Rjoint) Encode(enc Encoder) (ok bool) {656 return !LogErr(enc.Encode(o.States), "Encode")657}658// Decode decodes internal variables659func (o Rjoint) Decode(dec Decoder) (ok bool) {660 if LogErr(dec.Decode(&o.States), "Decode") {661 return662 }663 return o.BackupIvs()664}665// OutIpsData returns data from all integration points for output666func (o Rjoint) OutIpsData() (data []*OutIpData) {667 return668}669// debugging ////////////////////////////////////////////////////////////////////////////////////////670func (o Rjoint) debug_print_init() {671 sldNn := o.Sld.Shp.Nverts672 rodNn := o.Rod.Shp.Nverts673 rodNp := len(o.Rod.IpsElem)674 io.Pf("Nmat =\n")675 for i := 0; i < sldNn; i++ {676 for j := 0; j < rodNn; j++ {677 io.Pf("%g ", o.Nmat[i][j])678 }679 io.Pf("\n")680 }681 io.Pf("\nPmat =\n")682 for i := 0; i < sldNn; i++ {683 for j := 0; j < rodNp; j++ {684 io.Pf("%g ", o.Pmat[i][j])685 }686 io.Pf("\n")687 }688 io.Pf("\n")689 la.PrintMat("e0", o.e0, "%20.13f", false)690 io.Pf("\n")691 la.PrintMat("e1", o.e1, "%20.13f", false)692 io.Pf("\n")693 la.PrintMat("e2", o.e2, "%20.13f", false)694 io.Pf("\n")695 la.PrintMat("T1", o.T1, "%20.13f", false)696 io.Pf("\n")697 la.PrintMat("T2", o.T2, "%20.13f", false)698}699func (o Rjoint) debug_print_K() {700 ndim := Global.Ndim701 sldNn := o.Sld.Shp.Nverts702 rodNn := o.Rod.Shp.Nverts703 K := la.MatAlloc(o.Ny, o.Ny)704 start := o.Sld.Nu705 for i := 0; i < ndim; i++ {706 for m := 0; m < sldNn; m++ {707 r := i + m*ndim708 for j := 0; j < ndim; j++ {709 for n := 0; n < sldNn; n++ {710 c := j + n*ndim711 K[r][c] = o.Kss[r][c]712 }713 for n := 0; n < rodNn; n++ {714 c := j + n*ndim715 K[r][start+c] = o.Ksr[r][c]716 K[start+c][r] = o.Krs[c][r]717 }718 }719 }720 }721 for i := 0; i < ndim; i++ {722 for m := 0; m < rodNn; m++ {723 r := i + m*ndim724 for j := 0; j < ndim; j++ {725 for n := 0; n < rodNn; n++ {726 c := j + n*ndim727 K[start+r][start+c] = o.Krr[r][c]728 }729 }730 }731 }732 la.PrintMat("K", K, "%20.10f", false)733}734func (o Rjoint) debug_update(idx int, Îwb0, Îwb1, Îwb2, Ïc float64) {735 Ï := o.States[idx].Sig736 qn1 := o.States[idx].Phi[0]737 qn2 := o.States[idx].Phi[1]738 la.PrintVec("Îw", o.Îw, "%13.10f", false)739 io.Pf("Îwb0=%13.10f Îwb1=%13.10f Îwb2=%13.10f\n", Îwb0, Îwb1, Îwb2)740 la.PrintVec("ÏIp", o.ÏIp, "%13.10f", false)741 io.Pf("Ïc=%13.10f t1=%13.10f t2=%13.10f\n", Ïc, o.t1, o.t2)742 io.Pf("Ï=%13.10f qn1=%13.10f qn2=%13.10f\n", Ï, qn1, qn2)743}...
element_test.go
Source:element_test.go
...40func TestClickWrapped(t *testing.T) {41 g := setup(t)42 p := g.page.MustNavigate(g.srcFile("fixtures/click-wrapped.html")).MustWaitLoad()43 el := p.MustElement("#target")44 shape := el.MustShape()45 g.Len(shape.Quads, 2)46 el.MustClick()47 g.True(p.MustHas("[a=ok]"))48}49func TestTap(t *testing.T) {50 g := setup(t)51 page := g.newPage()52 page.MustEmulate(devices.IPad).53 MustNavigate(g.srcFile("fixtures/touch.html")).54 MustWaitLoad()55 el := page.MustElement("button")56 el.MustTap()57 g.True(page.MustHas("[tapped=true]"))58 g.Panic(func() {59 g.mc.stubErr(1, proto.RuntimeCallFunctionOn{})60 el.MustTap()61 })62 g.Panic(func() {63 g.mc.stubErr(1, proto.DOMScrollIntoViewIfNeeded{})64 el.MustTap()65 })66 g.Panic(func() {67 g.mc.stubErr(4, proto.RuntimeCallFunctionOn{})68 el.MustTap()69 })70 g.Panic(func() {71 g.mc.stubErr(7, proto.RuntimeCallFunctionOn{})72 el.MustTap()73 })74}75func TestInteractable(t *testing.T) {76 g := setup(t)77 p := g.page.MustNavigate(g.srcFile("fixtures/click.html"))78 el := p.MustElement("button")79 g.True(el.MustInteractable())80 g.mc.stubErr(4, proto.RuntimeCallFunctionOn{})81 g.Err(el.Interactable())82}83func TestNotInteractable(t *testing.T) {84 g := setup(t)85 p := g.page.MustNavigate(g.srcFile("fixtures/click.html"))86 el := p.MustElement("button")87 // cover the button with a green div88 p.MustWaitLoad().MustEval(`() => {89 let div = document.createElement('div')90 div.style = 'position: absolute; left: 0; top: 0; width: 500px; height: 500px;'91 document.body.append(div)92 }`)93 _, err := el.Interactable()94 g.Has(err.Error(), "element covered by: <div>")95 g.Is(err, &rod.ErrNotInteractable{})96 g.Is(err, &rod.ErrCovered{})97 g.False(el.MustInteractable())98 var ee *rod.ErrNotInteractable99 g.True(errors.As(err, &ee))100 g.Eq(ee.Error(), "element is not cursor interactable")101 p.MustElement("div").MustRemove()102 g.mc.stubErr(1, proto.DOMGetContentQuads{})103 _, err = el.Interactable()104 g.Err(err)105 g.mc.stubErr(1, proto.RuntimeCallFunctionOn{})106 g.Err(el.Interactable())107 g.mc.stubErr(1, proto.DOMDescribeNode{})108 g.Err(el.Interactable())109 g.mc.stubErr(2, proto.RuntimeCallFunctionOn{})110 g.Err(el.Interactable())111}112func TestInteractableWithNoShape(t *testing.T) {113 g := setup(t)114 p := g.page.MustNavigate(g.srcFile("fixtures/interactable.html"))115 el := p.MustElement("#no-shape")116 _, err := el.Interactable()117 g.Is(err, &rod.ErrInvisibleShape{})118 g.Is(err, &rod.ErrNotInteractable{})119 g.Eq(err.Error(), "element has no visible shape or outside the viewport: <div#no-shape>")120 el = p.MustElement("#outside")121 _, err = el.Interactable()122 g.Is(err, &rod.ErrInvisibleShape{})123 el = p.MustElement("#invisible")124 _, err = el.Interactable()125 g.Is(err, &rod.ErrInvisibleShape{})126}127func TestNotInteractableWithNoPointerEvents(t *testing.T) {128 g := setup(t)129 p := g.page.MustNavigate(g.srcFile("fixtures/interactable.html"))130 _, err := p.MustElementR("#no-pointer-events", "click me").Interactable()131 g.Is(err, &rod.ErrNoPointerEvents{})132 g.Is(err, &rod.ErrNotInteractable{})133 g.Eq(err.Error(), "element's pointer-events is none: <span#no-pointer-events>")134}135func TestWaitInteractable(t *testing.T) {136 g := setup(t)137 p := g.page.MustNavigate(g.srcFile("fixtures/click.html"))138 el := p.MustElement("button")139 start := time.Now()140 // cover the button with a green div for 1sec141 p.MustWaitLoad().MustEval(`() => {142 let div = document.createElement('div')143 div.style = 'position: absolute; left: 0; top: 0; width: 500px; height: 500px;'144 document.body.append(div)145 setTimeout(() => div.remove(), 1000)146 }`)147 el.MustWaitInteractable()148 g.Gt(time.Since(start), time.Second)149 g.mc.stubErr(1, proto.DOMScrollIntoViewIfNeeded{})150 g.Err(el.WaitInteractable())151}152func TestHover(t *testing.T) {153 g := setup(t)154 p := g.page.MustNavigate(g.srcFile("fixtures/click.html"))155 el := p.MustElement("button")156 el.MustEval(`() => this.onmouseenter = () => this.dataset['a'] = 1`)157 el.MustHover()158 g.Eq("1", el.MustEval(`() => this.dataset['a']`).String())159 g.mc.stubErr(1, proto.DOMScrollIntoViewIfNeeded{})160 g.Err(el.Hover())161 g.mc.stubErr(1, proto.DOMGetContentQuads{})162 g.Err(el.Hover())163 g.mc.stubErr(3, proto.DOMGetContentQuads{})164 g.Err(el.Hover())165 g.mc.stubErr(1, proto.InputDispatchMouseEvent{})166 g.Err(el.Hover())167}168func TestElementMoveMouseOut(t *testing.T) {169 g := setup(t)170 p := g.page.MustNavigate(g.srcFile("fixtures/click.html"))171 btn := p.MustElement("button")172 btn.MustEval(`() => this.onmouseout = () => this.setAttribute('name', 'mouse moved.')`)173 g.Eq("mouse moved.", *btn.MustHover().MustMoveMouseOut().MustAttribute("name"))174 g.mc.stubErr(1, proto.DOMGetContentQuads{})175 g.Err(btn.MoveMouseOut())176}177func TestElementContext(t *testing.T) {178 g := setup(t)179 p := g.page.MustNavigate(g.srcFile("fixtures/click.html"))180 el := p.MustElement("button").Timeout(time.Hour).CancelTimeout()181 el, cancel := el.WithCancel()182 defer cancel()183 el.Sleeper(rod.DefaultSleeper).MustClick()184}185func TestIframes(t *testing.T) {186 g := setup(t)187 p := g.page.MustNavigate(g.srcFile("fixtures/click-iframes.html"))188 frame01 := p.MustElement("iframe").MustFrame()189 frame02 := frame01.MustElement("iframe").MustFrame()190 el := frame02.MustElement("button")191 el.MustClick()192 g.Eq(frame01.MustEval(`() => testIsolation()`).Str(), "ok")193 g.True(frame02.MustHas("[a=ok]"))194}195func TestContains(t *testing.T) {196 g := setup(t)197 p := g.page.MustNavigate(g.srcFile("fixtures/click.html"))198 a := p.MustElement("button")199 b := p.MustElementFromNode(a.MustDescribe())200 g.True(a.MustContainsElement(b))201 pt := a.MustShape().OnePointInside()202 el := p.MustElementFromPoint(int(pt.X), int(pt.Y))203 g.True(a.MustContainsElement(el))204 g.mc.stubErr(1, proto.RuntimeCallFunctionOn{})205 g.Err(a.ContainsElement(el))206}207func TestShadowDOM(t *testing.T) {208 g := setup(t)209 p := g.page.MustNavigate(g.srcFile("fixtures/shadow-dom.html")).MustWaitLoad()210 el := p.MustElement("#container")211 g.Eq("inside", el.MustShadowRoot().MustElement("p").MustText())212 g.Panic(func() {213 g.mc.stubErr(1, proto.DOMDescribeNode{})214 el.MustShadowRoot()215 })216 g.Panic(func() {217 g.mc.stubErr(1, proto.DOMResolveNode{})218 el.MustShadowRoot()219 })220}221func TestInputTime(t *testing.T) {222 g := setup(t)223 now := time.Now()224 p := g.page.MustNavigate(g.srcFile("fixtures/input.html"))225 var el *rod.Element226 {227 el = p.MustElement("[type=date]")228 el.MustInputTime(now)229 g.Eq(el.MustText(), now.Format("2006-01-02"))230 g.True(p.MustHas("[event=input-date-change]"))231 }232 {233 el = p.MustElement("[type=datetime-local]")234 el.MustInputTime(now)235 g.Eq(el.MustText(), now.Format("2006-01-02T15:04"))236 g.True(p.MustHas("[event=input-datetime-local-change]"))237 }238 g.Panic(func() {239 g.mc.stubErr(1, proto.RuntimeCallFunctionOn{})240 el.MustInputTime(now)241 })242 g.Panic(func() {243 g.mc.stubErr(5, proto.RuntimeCallFunctionOn{})244 el.MustInputTime(now)245 })246 g.Panic(func() {247 g.mc.stubErr(6, proto.RuntimeCallFunctionOn{})248 el.MustInputTime(now)249 })250 g.Panic(func() {251 g.mc.stubErr(7, proto.RuntimeCallFunctionOn{})252 el.MustInputTime(now)253 })254}255func TestElementInputDate(t *testing.T) {256 g := setup(t)257 p := g.page.MustNavigate(g.srcFile("fixtures/input.html"))258 p.MustElement("[type=date]").MustInput("12")259}260func TestCheckbox(t *testing.T) {261 g := setup(t)262 p := g.page.MustNavigate(g.srcFile("fixtures/input.html"))263 el := p.MustElement("[type=checkbox]")264 g.True(el.MustClick().MustProperty("checked").Bool())265}266func TestSelectText(t *testing.T) {267 g := setup(t)268 p := g.page.MustNavigate(g.srcFile("fixtures/input.html"))269 el := p.MustElement("textarea")270 el.MustInput("test")271 el.MustSelectAllText()272 el.MustInput("test")273 g.Eq("test", el.MustText())274 el.MustSelectText(`es`)275 el.MustInput("__")276 g.Eq("t__t", el.MustText())277 g.Panic(func() {278 g.mc.stubErr(1, proto.DOMScrollIntoViewIfNeeded{})279 el.MustSelectText("")280 })281 g.Panic(func() {282 g.mc.stubErr(1, proto.DOMScrollIntoViewIfNeeded{})283 el.MustSelectAllText()284 })285 g.Panic(func() {286 g.mc.stubErr(1, proto.DOMScrollIntoViewIfNeeded{})287 el.MustInput("")288 })289 g.Panic(func() {290 g.mc.stubErr(1, proto.InputInsertText{})291 el.MustInput("")292 })293}294func TestBlur(t *testing.T) {295 g := setup(t)296 p := g.page.MustNavigate(g.srcFile("fixtures/input.html"))297 el := p.MustElement("#blur").MustInput("test").MustBlur()298 g.Eq("ok", *el.MustAttribute("a"))299}300func TestSelectQuery(t *testing.T) {301 g := setup(t)302 p := g.page.MustNavigate(g.srcFile("fixtures/input.html"))303 el := p.MustElement("select")304 err := el.Select([]string{`[value="c"]`}, true, rod.SelectorTypeCSSSector)305 g.E(err)306 g.Eq(2, el.MustEval("() => this.selectedIndex").Int())307}308func TestSelectOptions(t *testing.T) {309 g := setup(t)310 p := g.page.MustNavigate(g.srcFile("fixtures/input.html"))311 el := p.MustElement("select")312 el.MustSelect("B", "C")313 g.Eq("B,C", el.MustText())314 g.Eq(1, el.MustProperty("selectedIndex").Int())315 // unselect with regex316 err := el.Select([]string{`^B$`}, false, rod.SelectorTypeRegex)317 g.E(err)318 g.Eq("C", el.MustText())319 // unselect with css selector320 err = el.Select([]string{`[value="c"]`}, false, rod.SelectorTypeCSSSector)321 g.E(err)322 g.Eq("", el.MustText())323 // option not found error324 g.Is(el.Select([]string{"not-exists"}, true, rod.SelectorTypeCSSSector), &rod.ErrElementNotFound{})325 {326 g.mc.stubErr(5, proto.RuntimeCallFunctionOn{})327 g.Err(el.Select([]string{"B"}, true, rod.SelectorTypeText))328 }329}330func TestMatches(t *testing.T) {331 g := setup(t)332 p := g.page.MustNavigate(g.srcFile("fixtures/input.html"))333 el := p.MustElement("textarea")334 g.True(el.MustMatches(`[cols="30"]`))335 g.Panic(func() {336 g.mc.stubErr(1, proto.RuntimeCallFunctionOn{})337 el.MustMatches("")338 })339}340func TestAttribute(t *testing.T) {341 g := setup(t)342 p := g.page.MustNavigate(g.srcFile("fixtures/input.html"))343 el := p.MustElement("textarea")344 cols := el.MustAttribute("cols")345 rows := el.MustAttribute("rows")346 g.Eq("30", *cols)347 g.Eq("10", *rows)348 p = g.page.MustNavigate(g.srcFile("fixtures/click.html"))349 el = p.MustElement("button").MustClick()350 g.Eq("ok", *el.MustAttribute("a"))351 g.Nil(el.MustAttribute("b"))352 g.Panic(func() {353 g.mc.stubErr(1, proto.RuntimeCallFunctionOn{})354 el.MustAttribute("")355 })356}357func TestProperty(t *testing.T) {358 g := setup(t)359 p := g.page.MustNavigate(g.srcFile("fixtures/input.html"))360 el := p.MustElement("textarea")361 cols := el.MustProperty("cols")362 rows := el.MustProperty("rows")363 g.Eq(float64(30), cols.Num())364 g.Eq(float64(10), rows.Num())365 p = g.page.MustNavigate(g.srcFile("fixtures/open-page.html"))366 el = p.MustElement("a")367 g.Eq("link", el.MustProperty("id").Str())368 g.Eq("_blank", el.MustProperty("target").Str())369 g.True(el.MustProperty("test").Nil())370 g.Panic(func() {371 g.mc.stubErr(1, proto.RuntimeCallFunctionOn{})372 el.MustProperty("")373 })374}375func TestSetFiles(t *testing.T) {376 g := setup(t)377 p := g.page.MustNavigate(g.srcFile("fixtures/input.html"))378 el := p.MustElement(`[type=file]`)379 el.MustSetFiles(380 slash("fixtures/click.html"),381 slash("fixtures/alert.html"),382 )383 list := el.MustEval("() => Array.from(this.files).map(f => f.name)").Arr()384 g.Len(list, 2)385 g.Eq("alert.html", list[1].String())386}387func TestEnter(t *testing.T) {388 g := setup(t)389 p := g.page.MustNavigate(g.srcFile("fixtures/input.html"))390 el := p.MustElement("[type=submit]")391 el.MustType(input.Enter)392 g.True(p.MustHas("[event=submit]"))393}394func TestWaitInvisible(t *testing.T) {395 g := setup(t)396 p := g.page.MustNavigate(g.srcFile("fixtures/click.html"))397 h4 := p.MustElement("h4")398 btn := p.MustElement("button")399 g.True(h4.MustVisible())400 h4.MustWaitVisible()401 go func() {402 utils.Sleep(0.03)403 h4.MustEval(`() => this.remove()`)404 utils.Sleep(0.03)405 btn.MustEval(`() => this.style.visibility = 'hidden'`)406 }()407 h4.MustWaitInvisible()408 btn.MustWaitInvisible()409 g.False(p.MustHas("h4"))410}411func TestWaitEnabled(t *testing.T) {412 g := setup(t)413 p := g.page.MustNavigate(g.srcFile("fixtures/click.html"))414 p.MustElement("button").MustWaitEnabled()415}416func TestWaitWritable(t *testing.T) {417 g := setup(t)418 p := g.page.MustNavigate(g.srcFile("fixtures/input.html"))419 p.MustElement("input").MustWaitWritable()420}421func TestWaitStable(t *testing.T) {422 g := setup(t)423 p := g.page.MustNavigate(g.srcFile("fixtures/wait-stable.html"))424 el := p.MustElement("button")425 go func() {426 utils.Sleep(1)427 el.MustEval(`() => this.classList.remove("play")`)428 }()429 start := time.Now()430 el.MustWaitStable()431 g.Gt(time.Since(start), time.Second)432 ctx := g.Context()433 g.mc.stub(1, proto.DOMGetContentQuads{}, func(send StubSend) (gson.JSON, error) {434 go func() {435 utils.Sleep(0.1)436 ctx.Cancel()437 }()438 return send()439 })440 g.Err(el.Context(ctx).WaitStable(time.Minute))441 g.Panic(func() {442 g.mc.stubErr(1, proto.DOMGetContentQuads{})443 el.MustWaitStable()444 })445 g.Panic(func() {446 g.mc.stubErr(2, proto.DOMGetContentQuads{})447 el.MustWaitStable()448 })449}450func TestWaitStableRAP(t *testing.T) {451 g := setup(t)452 p := g.page.MustNavigate(g.srcFile("fixtures/wait-stable.html"))453 el := p.MustElement("button")454 go func() {455 utils.Sleep(1)456 el.MustEval(`() => this.classList.remove("play")`)457 }()458 start := time.Now()459 g.E(el.WaitStableRAF())460 g.Gt(time.Since(start), time.Second)461 g.mc.stubErr(2, proto.RuntimeCallFunctionOn{})462 g.Err(el.WaitStableRAF())463 g.mc.stubErr(1, proto.DOMGetContentQuads{})464 g.Err(el.WaitStableRAF())465}466func TestCanvasToImage(t *testing.T) {467 g := setup(t)468 p := g.page.MustNavigate(g.srcFile("fixtures/canvas.html"))469 src, err := png.Decode(bytes.NewBuffer(p.MustElement("#canvas").MustCanvasToImage()))470 g.E(err)471 g.Eq(src.At(50, 50), color.NRGBA{0xFF, 0x00, 0x00, 0xFF})472}473func TestElementWaitLoad(t *testing.T) {474 g := setup(t)475 p := g.page.MustNavigate(g.srcFile("fixtures/resource.html"))476 p.MustElement("img").MustWaitLoad()477}478func TestResource(t *testing.T) {479 g := setup(t)480 p := g.page.MustNavigate(g.srcFile("fixtures/resource.html"))481 el := p.MustElement("img")482 g.Eq(len(el.MustResource()), 22661)483 g.mc.stub(1, proto.PageGetResourceContent{}, func(send StubSend) (gson.JSON, error) {484 return gson.New(proto.PageGetResourceContentResult{485 Content: "ok",486 Base64Encoded: false,487 }), nil488 })489 g.Eq([]byte("ok"), el.MustResource())490 g.Panic(func() {491 g.mc.stubErr(1, proto.RuntimeCallFunctionOn{})492 el.MustResource()493 })494 g.Panic(func() {495 g.mc.stubErr(1, proto.PageGetResourceContent{})496 el.MustResource()497 })498}499func TestBackgroundImage(t *testing.T) {500 g := setup(t)501 p := g.page.MustNavigate(g.srcFile("fixtures/resource.html"))502 el := p.MustElement("div")503 g.Eq(len(el.MustBackgroundImage()), 22661)504 {505 g.mc.stubErr(1, proto.RuntimeCallFunctionOn{})506 g.Err(el.BackgroundImage())507 }508}509func TestElementScreenshot(t *testing.T) {510 g := setup(t)511 f := filepath.Join("tmp", "screenshots", g.RandStr(16)+".png")512 p := g.page.MustNavigate(g.srcFile("fixtures/click.html"))513 el := p.MustElement("h4")514 data := el.MustScreenshot(f)515 img, err := png.Decode(bytes.NewBuffer(data))516 g.E(err)517 g.Eq(200, img.Bounds().Dx())518 g.Eq(30, img.Bounds().Dy())519 g.Nil(os.Stat(f))520 g.Panic(func() {521 g.mc.stubErr(1, proto.DOMScrollIntoViewIfNeeded{})522 el.MustScreenshot()523 })524 g.Panic(func() {525 g.mc.stubErr(1, proto.PageCaptureScreenshot{})526 el.MustScreenshot()527 })528 g.Panic(func() {529 g.mc.stubErr(3, proto.DOMGetContentQuads{})530 el.MustScreenshot()531 })532}533func TestUseReleasedElement(t *testing.T) {534 g := setup(t)535 p := g.page.MustNavigate(g.srcFile("fixtures/click.html"))536 btn := p.MustElement("button")537 btn.MustRelease()538 g.Err(btn.Click("left", 1))539 btn = p.MustElement("button")540 g.E(proto.RuntimeReleaseObject{ObjectID: btn.Object.ObjectID}.Call(p))541 g.Is(btn.Click("left", 1), cdp.ErrObjNotFound)542}543func TestElementRemove(t *testing.T) {544 g := setup(t)545 p := g.page.MustNavigate(g.srcFile("fixtures/click.html"))546 btn := p.MustElement("button")547 g.mc.stubErr(1, proto.RuntimeCallFunctionOn{})548 g.Err(btn.Remove())549}550func TestElementMultipleTimes(t *testing.T) {551 g := setup(t)552 // To see whether chrome will reuse the remote object ID or not.553 // Seems like it will not.554 page := g.page.MustNavigate(g.srcFile("fixtures/click.html"))555 btn01 := page.MustElement("button")556 btn02 := page.MustElement("button")557 g.Eq(btn01.MustText(), btn02.MustText())558 g.Neq(btn01.Object, btn02.Object)559}560func TestFnErr(t *testing.T) {561 g := setup(t)562 p := g.page.MustNavigate(g.srcFile("fixtures/click.html"))563 el := p.MustElement("button")564 _, err := el.Eval("foo()")565 g.Err(err)566 g.Has(err.Error(), "ReferenceError: foo is not defined")567 var e *rod.ErrEval568 g.True(errors.As(err, &e))569 g.Eq(proto.RuntimeRemoteObjectSubtypeError, e.Exception.Subtype)570 _, err = el.ElementByJS(rod.Eval("() => foo()"))571 g.Err(err)572 g.Has(err.Error(), "ReferenceError: foo is not defined")573 g.True(errors.Is(err, &rod.ErrEval{}))574}575func TestElementEWithDepth(t *testing.T) {576 g := setup(t)577 checkStr := `green tea`578 p := g.page.MustNavigate(g.srcFile("fixtures/describe.html"))579 ulDOMNode, err := p.MustElement(`ul`).Describe(-1, true)580 g.Nil(errors.Unwrap(err))581 data, err := json.Marshal(ulDOMNode)582 g.Nil(errors.Unwrap(err))583 // The depth is -1, should contain checkStr584 g.Has(string(data), checkStr)585}586func TestElementOthers(t *testing.T) {587 g := setup(t)588 p := g.page.MustNavigate(g.srcFile("fixtures/input.html"))589 el := p.MustElement("form")590 el.MustFocus()591 el.MustScrollIntoView()592 g.Eq("submit", el.MustElement("[type=submit]").MustText())593 g.Eq("<input type=\"submit\" value=\"submit\">", el.MustElement("[type=submit]").MustHTML())594 el.MustWait(`() => true`)595 g.Eq("form", el.MustElementByJS(`() => this`).MustDescribe().LocalName)596 g.Len(el.MustElementsByJS(`() => []`), 0)597}598func TestElementEqual(t *testing.T) {599 g := setup(t)600 p := g.page.MustNavigate(g.srcFile("fixtures/describe.html"))601 el1 := p.MustElement("body > ul")602 el2 := p.MustElement("html > body > ul")603 g.True(el1.MustEqual(el2))604 el3 := p.MustElement("ul ul")605 g.False(el1.MustEqual(el3))606}607func TestElementWait(t *testing.T) {608 g := setup(t)609 p := g.page.MustNavigate(g.srcFile("fixtures/describe.html"))610 e1 := p.MustElement("body > ul > li")611 g.Eq(e1.MustText(), "coffee")612 params := []interface{}{1, 3, 4}613 go func() {614 utils.Sleep(0.3)615 e1.MustEval(`(a, b, c) => this.innerText = 'x'.repeat(a + b + c)`, params...)616 }()617 e1.MustWait(`(a, b, c) => this.innerText.length === (a + b + c)`, params...)618 g.Eq(e1.MustText(), "xxxxxxxx")619}620func TestShapeInIframe(t *testing.T) {621 g := setup(t)622 p := g.page.MustNavigate(g.srcFile("fixtures/click-iframe.html"))623 pt := p.MustElement("iframe").MustFrame().MustElement("button").MustShape().OnePointInside()624 g.InDelta(pt.X, 238, 1)625 g.InDelta(pt.Y, 287, 1)626}627func TestElementFromPointErr(t *testing.T) {628 g := setup(t)629 g.mc.stubErr(1, proto.DOMGetNodeForLocation{})630 g.Err(g.page.ElementFromPoint(10, 10))631}632func TestElementFromNodeErr(t *testing.T) {633 g := setup(t)634 p := g.page.MustNavigate(g.srcFile("fixtures/click.html"))635 el := p.MustElementX("//button/text()")636 g.mc.stubErr(3, proto.RuntimeCallFunctionOn{})637 g.Err(p.ElementFromNode(el.MustDescribe()))...
page.go
Source:page.go
...65 }66 return false67}68func (p *PageTemplate) MoveMouseTo(el *rod.Element) {69 shape, err := el.Shape()70 if err == nil {71 point := shape.OnePointInside()72 p.P.Mouse.MustMove(point.X, point.Y)73 } else {74 if cErr, ok := err.(*cdp.Error); ok {75 log.Println("failed to get element shape", cErr)76 } else {77 panic(err)78 }79 }80}81func (p *PageTemplate) URL() string {82 return p.P.MustInfo().URL83}84func (p *PageTemplate) Input(selector string, value string) {85 for i := 0; i < 100; i++ {86 if p.P.MustHas(selector) {87 break88 }89 time.Sleep(time.Millisecond * 100)90 }91 if !p.P.MustHas(selector) {92 log.Fatalf("failed to find input having selector %s\n", selector)93 }94 el := p.P.MustElement(selector)95 el.MustClick().MustSelectAllText().MustInput(value)96}97func (p *PageTemplate) PressKey(keyCode int32) {98 p.P.Keyboard.MustPress(keyCode)99}100func (p *PageTemplate) WaitLoadAndIdle() {101 p.P.MustWaitNavigation()102 p.WaitLoad()103 p.WaitIdle()104}105func (p *PageTemplate) Has(selector string) bool {106 has, _, err := p.P.Has(selector)107 if err != nil {108 log.Printf("failed to find element using selector %s\n", selector)109 return false110 }111 return has112}113func (p PageTemplate) GetVisibleHeight(selector string) float64 {114 if p.Has(selector) {115 el := p.El(selector)116 if el.MustVisible() {117 return el.Height()118 }119 }120 return 0.0121}122func (p *PageTemplate) El(selector string) *ElementTemplate {123 return &ElementTemplate{Element: p.P.MustElement(selector)}124}125func (p *PageTemplate) Els(selector string) ElementsTemplate {126 return toElementsTemplate(p.P.MustElements(selector))127}128func (p *PageTemplate) Reload() {129 p.P.MustReload()130}131func (p *PageTemplate) FrameID() proto.PageFrameID {132 return p.P.FrameID133}134func (p *PageTemplate) WaitIdle() {135 p.P.MustWaitIdle()136}137func (p *PageTemplate) WaitLoad() {138 if err := p.P.WaitLoad(); err != nil {139 if cErr, ok := err.(*cdp.Error); ok {140 log.Println("failed to wait", cErr)141 } else {142 panic(err)143 }144 }145}146func (p *PageTemplate) WaitRepaint() {147 if err := p.P.WaitRepaint(); err != nil {148 log.Println("failed to wait", err)149 }150}151func (p *PageTemplate) ScrollTop() {152 p.P.Keyboard.MustPress(input.Home)153}154func (p *PageTemplate) ScrollBottom() {155 p.P.Keyboard.MustPress(input.End)156}157func (p *PageTemplate) ScrollBottomHuman() {158 metrics, err := proto.PageGetLayoutMetrics{}.Call(p.P)159 if err != nil {160 panic(err)161 }162 width := int(metrics.ContentSize.Width)163 height := int(metrics.ContentSize.Height)164 if err = p.P.Mouse.Scroll(float64(width), float64(height), height/128); err != nil {165 panic(fmt.Errorf("failed to scroll for %s", err.Error()))166 }167}168func (p *PageTemplate) ScrollTo(e *ElementTemplate) {169 quad := e.MustShape().Quads[0]170 bottom := quad[7]171 if err := p.P.Mouse.Scroll(0.0, bottom, 1); err != nil {172 log.Println("failed to scroll mouse", err)173 }174}175func (p *PageTemplate) Body() string {176 return p.El("body").MustHTML()177}178func (p *PageTemplate) HTML() string {179 return p.El("html").MustHTML()180}181func (p *PageTemplate) Event() <-chan *rod.Message {182 return p.P.Event()183}184func (p *PageTemplate) MaximizeToWindowBounds() {185 bounds := p.P.MustGetWindow()186 p.SetViewport(bounds.Width, bounds.Height)187}188func (p *PageTemplate) SetViewport(width, height int) {189 p.P.MustSetViewport(width, height, 0, false)190}191func (p *PageTemplate) ScreenShotFull(dumpPath string) []byte {192 opt := ScreenShotOption{193 Format: proto.PageCaptureScreenshotFormatJpeg,194 Quality: 95,195 }196 return p.ScreenShotFullWithOption(dumpPath, opt)197}198func (p *PageTemplate) ScreenShotFullWithOption(dumpPath string, opt ScreenShotOption) []byte {199 metrics, err := proto.PageGetLayoutMetrics{}.Call(p.P)200 if err != nil {201 panic(err)202 }203 oldView := proto.EmulationSetDeviceMetricsOverride{}204 set := p.P.LoadState(&oldView)205 view := oldView206 view.Width = int(metrics.ContentSize.Width)207 view.Height = int(metrics.ContentSize.Height)208 err = p.P.SetViewport(&view)209 if err != nil {210 panic(err)211 }212 defer func() { // try to recover the viewport213 if !set {214 _ = proto.EmulationClearDeviceMetricsOverride{}.Call(p.P)215 return216 }217 _ = p.P.SetViewport(&oldView)218 }()219 return p.ScreenShotWithOption(p.El("html"), dumpPath, opt)220}221func (p *PageTemplate) ScreenShot(el *ElementTemplate, dumpPath string, yDelta float64) []byte {222 opt := ScreenShotOption{223 Format: proto.PageCaptureScreenshotFormatJpeg,224 Quality: 95,225 YDelta: yDelta,226 }227 return p.ScreenShotWithOption(el, dumpPath, opt)228}229func (p *PageTemplate) ScreenShotWithOption(el *ElementTemplate, dumpPath string, opt ScreenShotOption) []byte {230 err := el.ScrollIntoView()231 if err != nil {232 panic(err)233 }234 quad := el.MustShape().Quads[0]235 width := quad[2] - quad[0] + opt.WidthDelta236 height := quad[7] - quad[1] + opt.HeightDelta237 req := &proto.PageCaptureScreenshot{238 Format: opt.Format,239 Quality: opt.Quality,240 Clip: &proto.PageViewport{241 X: quad[0] + opt.XDelta,242 Y: quad[1] + opt.YDelta,243 Width: width,244 Height: height,245 Scale: 1,246 },247 }248 byteArr, errScreenShot := p.P.Screenshot(false, req)...
Shape
Using AI Code Generation
1import "fmt"2type Shape interface {3 Area() float644}5type rod struct {6}7func (r rod) Area() float64 {8}9func main() {10 r := rod{length: 5, width: 10}11 fmt.Println(s.Area())12}13import "fmt"14type Animal interface {15 Speak() string16}17type Dog struct {18}19type Cat struct {20}21func (d Dog) Speak() string {22}23func (c Cat) Speak() string {24}25func main() {26 animals := []Animal{Dog{}, Cat{}}27 for _, animal := range animals {28 fmt.Println(animal.Speak())29 }30}
Shape
Using AI Code Generation
1import "fmt"2type Shape interface {3 Area() float644}5type Rod struct {6}7func (r Rod) Area() float64 {8}9func main() {10 r := Rod{3, 4}11 fmt.Println(r.Area())12}
Shape
Using AI Code Generation
1import "fmt"2func main() {3 s = new(Circle)4 s = new(Rectangle)5 s = new(Triangle)6 s = new(Square)7 s = new(Pentagon)8 s = new(Hexagon)9}10import "fmt"11func main() {12 s = new(Circle)13 s = new(Rectangle)14 s = new(Triangle)15 s = new(Square)16 s = new(Pentagon)17 s = new(Hexagon)18 s = new(Octagon)19}20import "fmt"21func main() {22 s = new(Circle)23 s = new(Rectangle)24 s = new(Triangle)25 s = new(Square)26 s = new(Pentagon)27 s = new(Hexagon)28 s = new(Octagon)29 s = new(Nonagon)30}31import "fmt"32func main() {33 s = new(Circle)34 s = new(Rectangle)35 s = new(Triangle)36 s = new(Square)37 s = new(Pentagon)38 s = new(Hexagon)39 s = new(Octagon)40 s = new(Nonagon)41 s = new(Decagon)42}43import "fmt"44func main() {45 s = new(Circle)46 s = new(Rectangle)47 s = new(Triangle)48 s = new(Square)49 s = new(Pentagon)50 s = new(Hexagon)51 s = new(Octagon)52 s = new(Nonagon)53 s = new(Decagon)54 s = new(Hendecagon)55}56import "fmt"57func main() {58 s = new(Circle)
Shape
Using AI Code Generation
1import "fmt"2func main() {3 s = rod{length: 3.5, radius: 0.5}4 fmt.Println("Area of rod is: ", s.Area())5}6import "fmt"7type Shape interface {8 Area() float649}10type rod struct {11}12func (r rod) Area() float64 {13}14type cylinder struct {15}16func (c cylinder) Area() float64 {17 return c.rod.Area() * 2 + c.rod.radius * 2 * 3.1415 * c.height18}19func main() {20 s = cylinder{rod{length: 3.5, radius: 0.5}, 4.5}21 fmt.Println("Area of cylinder is: ", s.Area())22}23import "fmt"24type Shape interface {25 Area() float6426}27type rod struct {28}29func (r rod) Area() float64 {30}31type cylinder struct {32}33func (c cylinder) Area() float64 {34 return c.rod.Area() * 2 + c.rod.radius * 2 * 3.1415 * c.height35}36func main() {37 s = cylinder{rod{length: 3.5, radius: 0.5}, 4.5}38 fmt.Println("Area of cylinder is: ",
Shape
Using AI Code Generation
1import (2func main() {3 r.set(2, 2)4 fmt.Println(r.Shape())5}6import (7type rod struct {8}9func (r *rod) set(l, b float32) {10}11func (r *rod) Shape() string {12 return fmt.Sprintf("length: %.2f, breadth: %.2f", r.length, r.breadth)13}
Shape
Using AI Code Generation
1import "fmt"2func main() {3 s = new(Rod)4 s.Shape()5}6type NewType struct {7}8import "fmt"9type Shape interface {10 Shape()11}12type Rod struct {13}14func (r Rod) Shape() {15 fmt.Println("Shape: Rod")16}17type Cylinder struct {18}19func (c Cylinder) Shape() {20 fmt.Println("Shape: Cylinder")21}22func main() {23 s = Cylinder{Rod{3}, 4}24 s.Shape()25}26type NewType struct {27}28import "fmt"29type Shape interface {30 Shape()31}32type Rod struct {33}34func (r Rod) Shape() {35 fmt.Println("Shape: Rod")36}37type Cylinder struct {38}39func (c Cylinder) Shape() {40 fmt.Println("Shape: Cylinder")41}42func main() {43 s = Cylinder{Rod{3}, 4}44 s.Shape()45}
Shape
Using AI Code Generation
1import "fmt"2func main() {3 fmt.Println(a.Shape())4}5type circle struct {6}7func (c circle) Shape() string {8}9type square struct {10}11func (s square) Shape() string {12}13type Shape interface {14 Shape() string15}16func Shape(s Shape) string {17 return s.Shape()18}19import "fmt"20func main() {21 fmt.Println(Shape(a))22}23import "fmt"24func main() {25 a = new(rod)26 fmt.Println(Shape(a))27}28import "fmt"29func main() {30 a = new(rod)31 a.(*rod).length = 232 a.(*rod).breadth = 333 fmt.Println(Shape(a))34}
Shape
Using AI Code Generation
1import "fmt"2func main() {3fmt.Println("Area of rod", r.Shape())4}5import "fmt"6func main() {7fmt.Println("Area of rod", r.Shape())8}9import "fmt"10func main() {11r=new(rod)12fmt.Println("Area of rod", r.Shape())13}14import "fmt"15func main() {16r=new(rod)17fmt.Println("Area of rod", r.Shape())18}19import "fmt"20func main() {21r=new(rod)22fmt.Println("Area of rod", r.Shape())23}24import "fmt"25func main() {26r=new(rod)27fmt.Println("Area of rod", r.Shape())28}
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!!